luallaby 0.1.0

**Work in progress** A pure-Rust Lua interpreter/compiler
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
use std::ffi::{c_double, c_float, c_int, c_uchar, c_uint, c_ulong, c_ushort};
use std::iter::{repeat, Peekable};
use std::mem::size_of;

use crate::value::{LuaFloat, LuaInt};
use crate::vm::stdlib::string::index_start;
use crate::{LuaError, Result, Value, VM};

struct PackHead {
    endian: PackEndian,
    align: usize,
    total: usize,
}

impl Default for PackHead {
    fn default() -> Self {
        Self {
            endian: PackEndian::Native,
            align: 1,
            total: 0,
        }
    }
}

struct PackOpt {
    opt: char,
    endian: PackEndian,
    size: usize,
    padding: usize,
}

#[derive(Clone, Copy)]
enum PackEndian {
    Big,
    Little,
    Native,
}

fn parse_opt(
    head: &mut PackHead,
    fmt: &mut Peekable<impl Iterator<Item = u8>>,
) -> Result<Option<PackOpt>> {
    #[inline]
    fn num(fmt: &mut Peekable<impl Iterator<Item = u8>>) -> Option<usize> {
        let mut num = match fmt.peek().and_then(|c| char::from(*c).to_digit(10)) {
            Some(digit) => {
                fmt.next();
                digit as usize
            }
            None => return None,
        };
        while let Some(digit) = fmt.peek().and_then(|c| char::from(*c).to_digit(10)) {
            let (mul, o1) = num.overflowing_mul(10);
            let (add, o2) = mul.overflowing_add(digit as usize);
            if o1 || o2 {
                break;
            }
            fmt.next();
            num = add;
        }
        Some(num)
    }

    #[inline]
    fn num_checked(fmt: &mut Peekable<impl Iterator<Item = u8>>) -> Result<Option<usize>> {
        match num(fmt) {
            Some(num) => {
                if !(1..=16).contains(&num) {
                    err!(LuaError::PackSizeLimit(num))
                } else {
                    Ok(Some(num))
                }
            }
            None => Ok(None),
        }
    }

    #[inline]
    fn opt(
        fmt: &mut Peekable<impl Iterator<Item = u8>>,
        total: &mut usize,
        c: Option<u8>,
        endian: PackEndian,
        max_align: usize,
        empty: bool,
    ) -> Result<PackOpt> {
        let c = c.or_else(|| fmt.next()).unwrap_or(b'-');
        let size = match c {
            b'b' | b'B' => size_of::<c_uchar>(),
            b'h' | b'H' => size_of::<c_ushort>(),
            b'l' | b'L' => size_of::<c_ulong>(),
            b'j' | b'J' => size_of::<LuaInt>(),
            b'T' => size_of::<usize>(),
            b'i' | b'I' => num_checked(fmt)?.unwrap_or(size_of::<c_uint>()),
            b'f' => size_of::<c_float>(),
            b'd' => size_of::<c_double>(),
            b'n' => size_of::<LuaFloat>(),
            b'c' => match num(fmt) {
                Some(s) => s,
                None => return err!(LuaError::PackMissingSize),
            },
            b'z' => 0,
            b's' => num_checked(fmt)?.unwrap_or(size_of::<usize>()),
            b'x' => 1,
            _ => {
                return if empty {
                    err!(LuaError::PackInvalidX)
                } else {
                    err!(LuaError::PackFormatOption(char::from(c)))
                }
            }
        };

        if empty && matches!(c, b'c' | b'z') {
            return err!(LuaError::PackInvalidX);
        }

        let padding = if size <= 1 || matches!(c, b'c' | b'z') {
            0
        } else {
            let align = size.min(max_align);
            if !align.is_power_of_two() {
                return err!(LuaError::PackAlign);
            }
            (align - (*total & (align - 1))) & (align - 1)
        };
        let size = if empty { 0 } else { size };

        *total += padding + size;

        Ok(PackOpt {
            opt: char::from(c),
            endian,
            size,
            padding,
        })
    }

    while let Some(c) = fmt.next() {
        match c {
            b' ' => {}
            b'<' => head.endian = PackEndian::Little,
            b'>' => head.endian = PackEndian::Big,
            b'=' => head.endian = PackEndian::Native,
            b'!' => head.align = num_checked(fmt)?.unwrap_or(std::mem::size_of::<usize>()),
            b'X' => {
                return Ok(Some(opt(
                    fmt,
                    &mut head.total,
                    None,
                    head.endian,
                    head.align,
                    true,
                )?))
            }
            c => {
                return Ok(Some(opt(
                    fmt,
                    &mut head.total,
                    Some(c),
                    head.endian,
                    head.align,
                    false,
                )?))
            }
        }
    }
    Ok(None)
}

pub(super) fn pack(vm: &mut VM) -> Result<Value> {
    #[inline]
    fn pack_int(packed: &mut Vec<u8>, num: u128, size: usize, endian: PackEndian) {
        let bytes = &num.to_le_bytes();
        let bytes = bytes.iter().take(size);
        match endian {
            PackEndian::Big => packed.extend(bytes.rev()),
            PackEndian::Little => packed.extend(bytes),
            PackEndian::Native => {
                if cfg!(target_endian = "big") {
                    packed.extend(bytes.rev())
                } else {
                    packed.extend(bytes)
                }
            }
        }
    }

    let fmt = vm.arg_string_coerce(0)?;
    let mut fmt = fmt.into_iter().peekable();
    let mut head = PackHead::default();
    let mut args = vm.arg_split(1).into_iter();
    let mut packed = Vec::new();

    while let Some(opt) = parse_opt(&mut head, &mut fmt)? {
        packed.extend(repeat(b'\0').take(opt.padding));
        if opt.size == 0 && !matches!(opt.opt, 'c' | 'z') {
            continue; // X option
        }
        let arg = args.next().unwrap_or(Value::Nil);
        match opt.opt {
            'b' | 'h' | 'l' | 'j' | 'i' => {
                let num = arg.to_number_coerce()?.to_int()?;
                if opt.size < size_of::<LuaInt>() {
                    let limit = (1u64 << (opt.size * 8 - 1)) as i64;
                    if num < -limit || limit <= num {
                        return err!(LuaError::PackIntOverflow);
                    }
                }
                // Sign extend
                pack_int(&mut packed, num as i128 as u128, opt.size, opt.endian);
            }
            'B' | 'H' | 'L' | 'J' | 'I' | 'T' => {
                let num = arg.to_number_coerce()?.to_int()? as u64; // Don't sign extend
                if opt.size < size_of::<LuaInt>() && num >= (1u64 << (opt.size * 8)) {
                    return err!(LuaError::PackIntOverflow);
                }
                pack_int(&mut packed, num as u128, opt.size, opt.endian);
            }
            'f' => {
                let num = arg.to_number_coerce()?.to_float() as f32;
                packed.extend_from_slice(&match opt.endian {
                    PackEndian::Big => num.to_be_bytes(),
                    PackEndian::Little => num.to_le_bytes(),
                    PackEndian::Native => num.to_ne_bytes(),
                });
            }
            'd' | 'n' => {
                let num = arg.to_number_coerce()?.to_float();
                packed.extend_from_slice(&match opt.endian {
                    PackEndian::Big => num.to_be_bytes(),
                    PackEndian::Little => num.to_le_bytes(),
                    PackEndian::Native => num.to_ne_bytes(),
                });
            }
            'c' => {
                let str = arg.to_string_coerce()?;
                let len = str.len();
                if len > opt.size {
                    return err!(LuaError::PackStringC);
                }
                packed.extend(str);
                if len < opt.size {
                    packed.extend(repeat(b'\0').take(opt.size - len));
                }
            }
            'z' => {
                let str = arg.to_string_coerce()?;
                if str.contains(&b'\0') {
                    return err!(LuaError::StringZeros);
                }
                head.total += str.len() + 1;
                packed.extend(str);
                packed.push(b'\0');
            }
            's' => {
                let str = arg.to_string_coerce()?;
                if opt.size < size_of::<usize>() && str.len() >= (1 << (opt.size * 8)) {
                    return err!(LuaError::PackStringLength);
                }
                pack_int(&mut packed, str.len() as u128, opt.size, opt.endian);
                head.total += str.len();
                packed.extend(str);
            }
            'x' => packed.push(b'\0'),
            _ => unreachable!(),
        }
    }

    Ok(Value::str_bytes(packed))
}

pub(super) fn packsize(vm: &mut VM) -> Result<Value> {
    const MAX: usize = if size_of::<isize>() < size_of::<c_int>() {
        isize::MAX as usize
    } else {
        c_int::MAX as usize
    };

    let fmt = vm.arg_string_coerce(0)?;
    let mut fmt = fmt.into_iter().peekable();
    let mut head = PackHead::default();

    while let Some(opt) = parse_opt(&mut head, &mut fmt)? {
        if matches!(opt.opt, 's' | 'z') {
            return err!(LuaError::PackSizeVariableLength);
        }
        let size = opt.size + opt.padding;
        if head.total.wrapping_sub(size) > MAX.saturating_sub(size) {
            return err!(LuaError::PackSizeTooLarge);
        }
    }

    Ok(Value::int(head.total as i64))
}

pub(super) fn unpack(vm: &mut VM) -> Result<Value> {
    #[inline]
    fn unpack_int(bytes: &[u8], endian: PackEndian) -> u128 {
        #[inline]
        fn parse<T: Iterator<Item = u8>>(iter: T) -> u128 {
            u128::from_le_bytes(
                iter.chain(repeat(b'\0'))
                    .take(size_of::<u128>())
                    .collect::<Vec<_>>()
                    .try_into()
                    .unwrap(),
            )
        }
        if matches!(endian, PackEndian::Big)
            || (matches!(endian, PackEndian::Native) && cfg!(target_endian = "big"))
        {
            parse(bytes.iter().copied().rev())
        } else {
            parse(bytes.iter().copied())
        }
    }

    let s = vm.arg_string_coerce(1)?;
    let mut s = s.as_slice();
    let mut head = PackHead::default();
    match vm.arg_or_nil(2) {
        Value::Nil => {}
        v => {
            let pos = index_start(v, s.len())?;
            if pos > s.len() {
                return err!(LuaError::UnpackPosition);
            }
            head.total += pos;
            s = &s[pos..];
        }
    };
    let fmt = vm.arg_string_coerce(0)?;
    let mut fmt = fmt.into_iter().peekable();
    let mut res = Vec::new();

    while let Some(opt) = parse_opt(&mut head, &mut fmt)? {
        if s.len() < opt.padding + opt.size {
            return err!(LuaError::UnpackTooShort);
        }
        let (bytes, rest) = s[opt.padding..].split_at(opt.size);
        s = rest;
        if opt.size == 0 && !matches!(opt.opt, 'c' | 'z') {
            continue; // X option
        }
        res.push(match opt.opt {
            'b' | 'h' | 'l' | 'j' | 'i' => {
                let num = unpack_int(bytes, opt.endian);
                let num = if opt.size > size_of::<LuaInt>() {
                    // Check for overflow
                    let mask = ((1 << (opt.size * 8 - 1)) - 1) - (-1i64 as u64 as u128);
                    let neg = (num as i64) < 0;
                    if (!neg && num & mask > 0) || (neg && num & mask != mask) {
                        return err!(LuaError::UnpackIntOverflow(opt.size));
                    }
                    num
                } else {
                    // Sign extension
                    let mask = 0x1 << (opt.size * 8 - 1);
                    (num ^ mask).wrapping_sub(mask)
                };
                Value::int(num as i64)
            }
            'B' | 'H' | 'L' | 'J' | 'I' | 'T' => {
                let num = unpack_int(bytes, opt.endian);
                if opt.size > size_of::<LuaInt>() {
                    // Check for overflow
                    let mask = ((1 << (opt.size * 8 - 1)) - 1) - (-1i64 as u64 as u128);
                    if num & mask > 0 {
                        return err!(LuaError::UnpackIntOverflow(opt.size));
                    }
                }
                Value::int(num as i64)
            }
            'f' => {
                let bytes = <[u8; 4]>::try_from(bytes).unwrap();
                Value::float(match opt.endian {
                    PackEndian::Big => f32::from_be_bytes(bytes),
                    PackEndian::Little => f32::from_le_bytes(bytes),
                    PackEndian::Native => f32::from_ne_bytes(bytes),
                } as f64)
            }
            'd' | 'n' => {
                let bytes = <[u8; 8]>::try_from(bytes).unwrap();
                Value::float(match opt.endian {
                    PackEndian::Big => f64::from_be_bytes(bytes),
                    PackEndian::Little => f64::from_le_bytes(bytes),
                    PackEndian::Native => f64::from_ne_bytes(bytes),
                })
            }
            'c' => Value::str_bytes(bytes.to_vec()),
            'z' => match s.iter().position(|c| c == &b'\0') {
                Some(idx) => {
                    let (bytes, rest) = s.split_at(idx);
                    s = &rest[1..];
                    let bytes = bytes.to_vec();
                    head.total += bytes.len() + 1;
                    Value::str_bytes(bytes)
                }
                None => return err!(LuaError::UnpackStringZ),
            },
            's' => {
                let num = unpack_int(bytes, opt.endian) as usize;
                if num <= s.len() {
                    let (bytes, rest) = s.split_at(num);
                    s = rest;
                    head.total += num;
                    Value::str_bytes(bytes.to_vec())
                } else {
                    return err!(LuaError::UnpackStringS);
                }
            }
            'x' => continue,
            _ => unreachable!(),
        });
    }

    res.push(Value::int((head.total + 1) as i64));
    Ok(Value::Mult(res))
}