neyuki 0.3.0

A small Lua-like scripting language implemented in Rust
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
//! Reads `.nyc` bytecode files and verifies what it loads.

use crate::bytecode::format::BytecodeHeader;
use crate::bytecode::instruction::Instruction;
use crate::bytecode::proto::{Constant, Proto, UpvalueDesc};
use crate::bytecode::verify::verify_proto;
use num_bigint::{BigInt, Sign};

pub fn deserialize(bytes: &[u8]) -> Result<Proto, String> {
    let (header, mut cursor) = BytecodeHeader::parse(bytes)?;
    let payload = &bytes[cursor..];
    let actual_checksum = crate::bytecode::format::compute_crc32(payload);
    if actual_checksum != header.checksum {
        return Err(format!(
            "bytecode integrity check failed: checksum mismatch (expected 0x{:08X}, got 0x{:08X})",
            header.checksum, actual_checksum
        ));
    }
    let proto = read_proto(bytes, &mut cursor, 0, None)?;
    // Verify bytecode integrity before allowing execution
    verify_proto(&proto).map_err(|e| e.to_string())?;
    Ok(proto)
}

fn read_u8(bytes: &[u8], cursor: &mut usize) -> Result<u8, String> {
    if *cursor >= bytes.len() {
        return Err("unexpected end of bytecode".to_string());
    }
    let val = bytes[*cursor];
    *cursor += 1;
    Ok(val)
}

fn read_u16(bytes: &[u8], cursor: &mut usize) -> Result<u16, String> {
    if *cursor + 2 > bytes.len() {
        return Err("unexpected end of bytecode".to_string());
    }
    let val = u16::from_le_bytes([bytes[*cursor], bytes[*cursor + 1]]);
    *cursor += 2;
    Ok(val)
}

fn read_i16(bytes: &[u8], cursor: &mut usize) -> Result<i16, String> {
    if *cursor + 2 > bytes.len() {
        return Err("unexpected end of bytecode".to_string());
    }
    let val = i16::from_le_bytes([bytes[*cursor], bytes[*cursor + 1]]);
    *cursor += 2;
    Ok(val)
}

fn read_u32(bytes: &[u8], cursor: &mut usize) -> Result<u32, String> {
    if *cursor + 4 > bytes.len() {
        return Err("unexpected end of bytecode".to_string());
    }
    let val = u32::from_le_bytes([
        bytes[*cursor],
        bytes[*cursor + 1],
        bytes[*cursor + 2],
        bytes[*cursor + 3],
    ]);
    *cursor += 4;
    Ok(val)
}

fn read_i32(bytes: &[u8], cursor: &mut usize) -> Result<i32, String> {
    if *cursor + 4 > bytes.len() {
        return Err("unexpected end of bytecode".to_string());
    }
    let val = i32::from_le_bytes([
        bytes[*cursor],
        bytes[*cursor + 1],
        bytes[*cursor + 2],
        bytes[*cursor + 3],
    ]);
    *cursor += 4;
    Ok(val)
}

fn read_f64(bytes: &[u8], cursor: &mut usize) -> Result<f64, String> {
    if *cursor + 8 > bytes.len() {
        return Err("unexpected end of bytecode".to_string());
    }
    let mut b = [0u8; 8];
    b.copy_from_slice(&bytes[*cursor..*cursor + 8]);
    *cursor += 8;
    Ok(f64::from_le_bytes(b))
}

fn read_string(bytes: &[u8], cursor: &mut usize) -> Result<String, String> {
    let len = read_u32(bytes, cursor)? as usize;
    if *cursor + len > bytes.len() {
        return Err("unexpected end of bytecode in string".to_string());
    }
    let s = std::str::from_utf8(&bytes[*cursor..*cursor + len])
        .map_err(|e| format!("invalid utf-8: {}", e))?
        .to_string();
    *cursor += len;
    Ok(s)
}

fn read_bigint(bytes: &[u8], cursor: &mut usize) -> Result<BigInt, String> {
    let sign_byte = read_u8(bytes, cursor)?;
    let sign = match sign_byte {
        0 => Sign::Minus,
        1 => Sign::NoSign,
        2 => Sign::Plus,
        _ => return Err("invalid bigint sign".to_string()),
    };
    let len = read_u32(bytes, cursor)? as usize;
    if *cursor + len > bytes.len() {
        return Err("unexpected end of bytecode in bigint".to_string());
    }
    let b = BigInt::from_bytes_le(sign, &bytes[*cursor..*cursor + len]);
    *cursor += len;
    Ok(b)
}

fn read_constant(bytes: &[u8], cursor: &mut usize) -> Result<Constant, String> {
    let tag = read_u8(bytes, cursor)?;
    match tag {
        0 => Ok(Constant::Nil),
        1 => {
            let b = read_u8(bytes, cursor)? != 0;
            Ok(Constant::Bool(b))
        }
        2 => {
            let bi = read_bigint(bytes, cursor)?;
            Ok(Constant::Int(bi))
        }
        3 => {
            let f = read_f64(bytes, cursor)?;
            Ok(Constant::Float(f))
        }
        4 => {
            let s = read_string(bytes, cursor)?;
            Ok(Constant::String(s))
        }
        _ => Err(format!("invalid constant tag: {}", tag)),
    }
}

fn read_instruction(bytes: &[u8], cursor: &mut usize) -> Result<Instruction, String> {
    let tag = read_u8(bytes, cursor)?;
    match tag {
        1 => Ok(Instruction::LoadNil {
            dst: read_u8(bytes, cursor)?,
        }),
        2 => Ok(Instruction::LoadBool {
            dst: read_u8(bytes, cursor)?,
            val: read_u8(bytes, cursor)? != 0,
        }),
        3 => Ok(Instruction::LoadInt {
            dst: read_u8(bytes, cursor)?,
            val: read_i32(bytes, cursor)?,
        }),
        4 => Ok(Instruction::LoadK {
            dst: read_u8(bytes, cursor)?,
            k: read_u16(bytes, cursor)?,
        }),
        5 => Ok(Instruction::Move {
            dst: read_u8(bytes, cursor)?,
            src: read_u8(bytes, cursor)?,
        }),
        6 => Ok(Instruction::GetGlobal {
            dst: read_u8(bytes, cursor)?,
            name_k: read_u16(bytes, cursor)?,
        }),
        7 => Ok(Instruction::SetGlobal {
            src: read_u8(bytes, cursor)?,
            name_k: read_u16(bytes, cursor)?,
        }),
        8 => Ok(Instruction::GetUpval {
            dst: read_u8(bytes, cursor)?,
            upval_idx: read_u8(bytes, cursor)?,
        }),
        9 => Ok(Instruction::SetUpval {
            src: read_u8(bytes, cursor)?,
            upval_idx: read_u8(bytes, cursor)?,
        }),
        10 => Ok(Instruction::NewTable {
            dst: read_u8(bytes, cursor)?,
            array_cap: read_u8(bytes, cursor)?,
            fields_cap: read_u8(bytes, cursor)?,
        }),
        11 => Ok(Instruction::GetTable {
            dst: read_u8(bytes, cursor)?,
            table: read_u8(bytes, cursor)?,
            key: read_u8(bytes, cursor)?,
        }),
        12 => Ok(Instruction::SetTable {
            table: read_u8(bytes, cursor)?,
            key: read_u8(bytes, cursor)?,
            val: read_u8(bytes, cursor)?,
        }),
        13 => Ok(Instruction::GetTableK {
            dst: read_u8(bytes, cursor)?,
            table: read_u8(bytes, cursor)?,
            key_k: read_u16(bytes, cursor)?,
        }),
        14 => Ok(Instruction::SetTableK {
            table: read_u8(bytes, cursor)?,
            key_k: read_u16(bytes, cursor)?,
            val: read_u8(bytes, cursor)?,
        }),
        15 => Ok(Instruction::AppendArray {
            table: read_u8(bytes, cursor)?,
            src: read_u8(bytes, cursor)?,
        }),
        16 => Ok(Instruction::Add {
            dst: read_u8(bytes, cursor)?,
            a: read_u8(bytes, cursor)?,
            b: read_u8(bytes, cursor)?,
        }),
        17 => Ok(Instruction::Sub {
            dst: read_u8(bytes, cursor)?,
            a: read_u8(bytes, cursor)?,
            b: read_u8(bytes, cursor)?,
        }),
        18 => Ok(Instruction::Mul {
            dst: read_u8(bytes, cursor)?,
            a: read_u8(bytes, cursor)?,
            b: read_u8(bytes, cursor)?,
        }),
        19 => Ok(Instruction::Div {
            dst: read_u8(bytes, cursor)?,
            a: read_u8(bytes, cursor)?,
            b: read_u8(bytes, cursor)?,
        }),
        20 => Ok(Instruction::IDiv {
            dst: read_u8(bytes, cursor)?,
            a: read_u8(bytes, cursor)?,
            b: read_u8(bytes, cursor)?,
        }),
        21 => Ok(Instruction::Mod {
            dst: read_u8(bytes, cursor)?,
            a: read_u8(bytes, cursor)?,
            b: read_u8(bytes, cursor)?,
        }),
        22 => Ok(Instruction::Pow {
            dst: read_u8(bytes, cursor)?,
            a: read_u8(bytes, cursor)?,
            b: read_u8(bytes, cursor)?,
        }),
        23 => Ok(Instruction::BitAnd {
            dst: read_u8(bytes, cursor)?,
            a: read_u8(bytes, cursor)?,
            b: read_u8(bytes, cursor)?,
        }),
        24 => Ok(Instruction::BitOr {
            dst: read_u8(bytes, cursor)?,
            a: read_u8(bytes, cursor)?,
            b: read_u8(bytes, cursor)?,
        }),
        25 => Ok(Instruction::BitXor {
            dst: read_u8(bytes, cursor)?,
            a: read_u8(bytes, cursor)?,
            b: read_u8(bytes, cursor)?,
        }),
        26 => Ok(Instruction::Shl {
            dst: read_u8(bytes, cursor)?,
            a: read_u8(bytes, cursor)?,
            b: read_u8(bytes, cursor)?,
        }),
        27 => Ok(Instruction::Shr {
            dst: read_u8(bytes, cursor)?,
            a: read_u8(bytes, cursor)?,
            b: read_u8(bytes, cursor)?,
        }),
        28 => Ok(Instruction::Concat {
            dst: read_u8(bytes, cursor)?,
            a: read_u8(bytes, cursor)?,
            b: read_u8(bytes, cursor)?,
        }),
        29 => Ok(Instruction::Unm {
            dst: read_u8(bytes, cursor)?,
            src: read_u8(bytes, cursor)?,
        }),
        30 => Ok(Instruction::Not {
            dst: read_u8(bytes, cursor)?,
            src: read_u8(bytes, cursor)?,
        }),
        31 => Ok(Instruction::Len {
            dst: read_u8(bytes, cursor)?,
            src: read_u8(bytes, cursor)?,
        }),
        32 => Ok(Instruction::BitNot {
            dst: read_u8(bytes, cursor)?,
            src: read_u8(bytes, cursor)?,
        }),
        33 => Ok(Instruction::Coalesce {
            dst: read_u8(bytes, cursor)?,
            a: read_u8(bytes, cursor)?,
            b: read_u8(bytes, cursor)?,
        }),
        34 => Ok(Instruction::Eq {
            a: read_u8(bytes, cursor)?,
            b: read_u8(bytes, cursor)?,
            jump_if_false: read_i16(bytes, cursor)?,
        }),
        35 => Ok(Instruction::Ne {
            a: read_u8(bytes, cursor)?,
            b: read_u8(bytes, cursor)?,
            jump_if_false: read_i16(bytes, cursor)?,
        }),
        36 => Ok(Instruction::Lt {
            a: read_u8(bytes, cursor)?,
            b: read_u8(bytes, cursor)?,
            jump_if_false: read_i16(bytes, cursor)?,
        }),
        37 => Ok(Instruction::Le {
            a: read_u8(bytes, cursor)?,
            b: read_u8(bytes, cursor)?,
            jump_if_false: read_i16(bytes, cursor)?,
        }),
        38 => Ok(Instruction::Gt {
            a: read_u8(bytes, cursor)?,
            b: read_u8(bytes, cursor)?,
            jump_if_false: read_i16(bytes, cursor)?,
        }),
        39 => Ok(Instruction::Ge {
            a: read_u8(bytes, cursor)?,
            b: read_u8(bytes, cursor)?,
            jump_if_false: read_i16(bytes, cursor)?,
        }),
        40 => Ok(Instruction::Test {
            reg: read_u8(bytes, cursor)?,
            jump_if_false: read_i16(bytes, cursor)?,
        }),
        41 => Ok(Instruction::Jump {
            offset: read_i16(bytes, cursor)?,
        }),
        42 => Ok(Instruction::Call {
            callee: read_u8(bytes, cursor)?,
            argc: read_u8(bytes, cursor)?,
            retc: read_u8(bytes, cursor)?,
        }),
        43 => Ok(Instruction::Return {
            base: read_u8(bytes, cursor)?,
            count: read_u8(bytes, cursor)?,
        }),
        44 => Ok(Instruction::Closure {
            dst: read_u8(bytes, cursor)?,
            proto_idx: read_u16(bytes, cursor)?,
        }),
        45 => Ok(Instruction::Vararg {
            dst: read_u8(bytes, cursor)?,
            count: read_u8(bytes, cursor)?,
        }),
        46 => Ok(Instruction::ForPrep {
            base: read_u8(bytes, cursor)?,
            jump: read_i16(bytes, cursor)?,
        }),
        47 => Ok(Instruction::ForLoop {
            base: read_u8(bytes, cursor)?,
            jump: read_i16(bytes, cursor)?,
        }),
        48 => Ok(Instruction::SetList {
            table: read_u8(bytes, cursor)?,
            base: read_u8(bytes, cursor)?,
            count: read_u8(bytes, cursor)?,
        }),
        49 => Ok(Instruction::TForCall {
            base: read_u8(bytes, cursor)?,
            retc: read_u8(bytes, cursor)?,
        }),
        50 => Ok(Instruction::TForLoop {
            base: read_u8(bytes, cursor)?,
            jump: read_i16(bytes, cursor)?,
        }),
        51 => Ok(Instruction::LShl {
            dst: read_u8(bytes, cursor)?,
            a: read_u8(bytes, cursor)?,
            b: read_u8(bytes, cursor)?,
        }),
        52 => Ok(Instruction::LShr {
            dst: read_u8(bytes, cursor)?,
            a: read_u8(bytes, cursor)?,
            b: read_u8(bytes, cursor)?,
        }),
        53 => Ok(Instruction::GetImport {
            dst: read_u8(bytes, cursor)?,
            mod_k: read_u16(bytes, cursor)?,
            field_k: read_u16(bytes, cursor)?,
            site: read_u16(bytes, cursor)?,
        }),
        54 => Ok(Instruction::CloseUpval {
            reg: read_u8(bytes, cursor)?,
        }),
        _ => Err(format!("unknown instruction tag: {}", tag)),
    }
}

fn read_proto(
    bytes: &[u8],
    cursor: &mut usize,
    depth: usize,
    parent_source: Option<std::rc::Rc<str>>,
) -> Result<Proto, String> {
    const MAX_PROTO_DEPTH: usize = 64;
    if depth > MAX_PROTO_DEPTH {
        return Err(format!(
            "bytecode nested prototype depth limit ({}) exceeded",
            MAX_PROTO_DEPTH
        ));
    }

    let has_name = read_u8(bytes, cursor)? != 0;
    let name = if has_name {
        Some(read_string(bytes, cursor)?)
    } else {
        None
    };
    let source: Option<std::rc::Rc<str>> = match read_u8(bytes, cursor)? {
        0 => None,
        1 => Some(read_string(bytes, cursor)?.into()),
        2 => parent_source,
        tag => return Err(format!("invalid source tag {}", tag)),
    };
    let num_params = read_u8(bytes, cursor)?;
    let max_registers = read_u8(bytes, cursor)?;
    let is_vararg = read_u8(bytes, cursor)? != 0;

    let num_constants = read_u32(bytes, cursor)? as usize;
    if num_constants > 65535 {
        return Err(format!(
            "proto constant pool too large: {} (max 65535)",
            num_constants
        ));
    }
    let mut constants = Vec::with_capacity(num_constants);
    for _ in 0..num_constants {
        constants.push(read_constant(bytes, cursor)?);
    }

    let num_instructions = read_u32(bytes, cursor)? as usize;
    if num_instructions > 0x10_0000 {
        return Err(format!(
            "proto instruction count too large: {} (max 1048576)",
            num_instructions
        ));
    }
    let mut instructions = Vec::with_capacity(num_instructions);
    for _ in 0..num_instructions {
        instructions.push(read_instruction(bytes, cursor)?);
    }

    let num_protos = read_u32(bytes, cursor)? as usize;
    if num_protos > 4096 {
        return Err(format!(
            "proto nested prototype count too large: {} (max 4096)",
            num_protos
        ));
    }
    let mut protos = Vec::with_capacity(num_protos);
    for _ in 0..num_protos {
        protos.push(std::rc::Rc::new(read_proto(
            bytes,
            cursor,
            depth + 1,
            source.clone(),
        )?));
    }

    let num_upvalues = read_u32(bytes, cursor)? as usize;
    if num_upvalues > 255 {
        return Err(format!(
            "proto upvalue count too large: {} (max 255)",
            num_upvalues
        ));
    }
    let mut upvalues = Vec::with_capacity(num_upvalues);
    let mut upvalue_names = Vec::with_capacity(num_upvalues);
    for _ in 0..num_upvalues {
        let in_stack = read_u8(bytes, cursor)? != 0;
        let index = read_u8(bytes, cursor)?;
        upvalues.push(UpvalueDesc { in_stack, index });
        upvalue_names.push(read_string(bytes, cursor)?);
    }

    let num_lines = read_u32(bytes, cursor)? as usize;
    if num_lines > 0x10_0000 {
        return Err(format!(
            "proto line info too large: {} (max 1048576)",
            num_lines
        ));
    }
    let mut lines = Vec::with_capacity(num_lines);
    for _ in 0..num_lines {
        lines.push(read_u32(bytes, cursor)?);
    }

    let num_locals = read_u32(bytes, cursor)? as usize;
    if num_locals > 65535 {
        return Err(format!(
            "proto local variable count too large: {} (max 65535)",
            num_locals
        ));
    }
    let mut local_names = Vec::with_capacity(num_locals);
    for _ in 0..num_locals {
        let name = read_string(bytes, cursor)?;
        let reg = read_u8(bytes, cursor)?;
        let from_pc = read_u32(bytes, cursor)?;
        let to_pc = read_u32(bytes, cursor)?;
        local_names.push(crate::bytecode::proto::LocalVarInfo {
            name,
            reg,
            from_pc,
            to_pc,
        });
    }

    Ok(Proto {
        name,
        num_params,
        max_registers,
        is_vararg,
        constants,
        instructions,
        protos,
        upvalues,
        lines,
        local_names,
        source,
        upvalue_names,
        cache: Default::default(),
    })
}