neyuki 0.6.2

A small Lua-like scripting language implemented in Rust
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
//! The `debug` library: stack inspection, locals and upvalues, hooks and
//! tracebacks.
//!
//! Levels count stack frames from the function that called the debug
//! function (level 1) outwards. Native functions have no frames of their
//! own.

use std::cell::RefCell;
use std::rc::Rc;

use crate::bytecode::proto::{LocalVarInfo, Proto};
use crate::vm::frame::CallFrame;
use crate::vm::machine::VM;
use crate::vm::value::{Value, VmTable};

pub fn create_debug_lib() -> Value {
    let mut table = VmTable::new();
    macro_rules! reg {
        ($($name:literal => $func:ident),* $(,)?) => {
            $(table.set_str($name, crate::native!(concat!("debug.", $name), $func));)*
        };
    }
    reg! {
        "getinfo" => debug_getinfo,
        "getlocal" => debug_getlocal,
        "getmetatable" => debug_getmetatable,
        "gethook" => debug_gethook,
        "getupvalue" => debug_getupvalue,
        "setlocal" => debug_setlocal,
        "setmetatable" => debug_setmetatable,
        "sethook" => debug_sethook,
        "setupvalue" => debug_setupvalue,
        "traceback" => debug_traceback,
        "upvalueid" => debug_upvalueid,
    }
    crate::vm::libs::args::frozen(table)
}

/// A non-negative level or index argument.
fn count_arg(args: &[Value], index: usize, name: &str, default: i64) -> Result<i64, String> {
    match args.get(index) {
        None | Some(Value::Nil) => Ok(default),
        Some(Value::Int(i)) => Ok(*i),
        Some(Value::Float(f)) if f.fract() == 0.0 => Ok(*f as i64),
        Some(other) => Err(format!(
            "{} must be an integer, got {}",
            name,
            other.type_name()
        )),
    }
}

/// The frame `level` steps out from the caller of the debug function.
fn frame_at(vm: &VM, level: i64) -> Option<&CallFrame> {
    if level < 1 {
        return None;
    }
    let level = level as usize;
    vm.frames.len().checked_sub(level).map(|i| &vm.frames[i])
}

/// The instruction a frame is executing (its ip points past it).
fn current_pc(frame: &CallFrame) -> usize {
    frame.ip.saturating_sub(1)
}

fn current_line(frame: &CallFrame) -> i64 {
    let proto = &frame.closure.proto;
    proto
        .lines
        .get(current_pc(frame))
        .map(|l| *l as i64)
        .unwrap_or(-1)
}

/// `debug.traceback(message?, level?)`: the message followed by the stack,
/// one `file:line in function` entry per frame.
fn debug_traceback(vm: &mut VM, args: &[Value]) -> Result<Vec<Value>, String> {
    let message = match args.first() {
        None | Some(Value::Nil) => None,
        Some(Value::String(s)) => Some(s.to_string()),
        // A non-string message is passed through untouched, as in Lua.
        Some(other) => return Ok(vec![other.clone()]),
    };
    let level = count_arg(args, 1, "level", 1)?.max(1) as usize;
    let mut out = message.map(|m| format!("{}\n", m)).unwrap_or_default();
    out.push_str("stack traceback:");
    for frame in vm.capture_trace().into_iter().skip(level - 1) {
        out.push_str("\n    ");
        if frame.source.is_none() && frame.line == 0 {
            out.push_str(frame.function.as_deref().unwrap_or(""));
        } else {
            out.push_str(&frame.to_string());
        }
    }
    Ok(vec![Value::string(out)])
}

fn proto_info(table: &mut VmTable, proto: &Proto) {
    let name = proto.name.as_deref();
    table.set_str(
        "name",
        match name {
            Some("main") | None => Value::Nil,
            Some(n) => Value::str(n),
        },
    );
    table.set_str(
        "what",
        Value::str(if name == Some("main") {
            "main"
        } else {
            "Neyuki"
        }),
    );
    let source = proto.source.as_deref().unwrap_or("?");
    table.set_str("source", Value::str(source));
    table.set_str(
        "short_src",
        Value::str(source.rsplit(['/', '\\']).next().unwrap_or(source)),
    );
    let first = proto.lines.iter().copied().filter(|l| *l > 0).min();
    let last = proto.lines.iter().copied().max();
    table.set_str("linedefined", Value::Int(first.unwrap_or(0) as i64));
    table.set_str("lastlinedefined", Value::Int(last.unwrap_or(0) as i64));
    table.set_str("numparams", Value::Int(proto.num_params as i64));
    table.set_str("isvararg", Value::Bool(proto.is_vararg));
    table.set_str("nups", Value::Int(proto.upvalues.len() as i64));
}

fn native_info(table: &mut VmTable, name: &str) {
    table.set_str("name", Value::str(name));
    table.set_str("what", Value::str("native"));
    table.set_str("source", Value::str("=[native]"));
    table.set_str("short_src", Value::str("[native]"));
    table.set_str("linedefined", Value::Int(-1));
    table.set_str("lastlinedefined", Value::Int(-1));
    table.set_str("currentline", Value::Int(-1));
    table.set_str("numparams", Value::Int(0));
    table.set_str("isvararg", Value::Bool(true));
    table.set_str("nups", Value::Int(0));
}

/// `debug.getinfo(level | function)`: a table describing a running frame or
/// a function: name, what, source, short_src, linedefined, lastlinedefined,
/// currentline (frames only), numparams, isvararg, nups and func.
fn debug_getinfo(vm: &mut VM, args: &[Value]) -> Result<Vec<Value>, String> {
    let mut table = VmTable::new();
    match args.first() {
        Some(Value::Closure(c)) => {
            proto_info(&mut table, &c.proto);
            table.set_str("currentline", Value::Int(-1));
        }
        Some(Value::Native(def)) => native_info(&mut table, def.name),
        Some(level @ (Value::Int(_) | Value::Float(_))) => {
            let level = count_arg(std::slice::from_ref(level), 0, "level", 1)?;
            if level == 0 {
                native_info(&mut table, "debug.getinfo");
            } else {
                let Some(frame) = frame_at(vm, level) else {
                    return Ok(vec![Value::Nil]);
                };
                proto_info(&mut table, &frame.closure.proto);
                table.set_str("currentline", Value::Int(current_line(frame)));
                table.set_str("func", Value::Closure(frame.closure.clone()));
            }
        }
        _ => return Err("getinfo expects a level or a function".to_string()),
    }
    if let Some(f @ (Value::Closure(_) | Value::Native(_))) = args.first() {
        table.set_str("func", f.clone());
    }
    Ok(vec![Value::Table(Rc::new(RefCell::new(table)))])
}

/// The locals in scope at the frame's current instruction, in declaration
/// order.
fn active_locals(frame: &CallFrame) -> Vec<&LocalVarInfo> {
    let pc = current_pc(frame) as u32;
    frame
        .closure
        .proto
        .local_names
        .iter()
        .filter(|info| info.from_pc <= pc && pc < info.to_pc)
        .collect()
}

/// `debug.getlocal(level, n)`: the name and value of the `n`th local in
/// scope; a negative `n` reads the `-n`th vararg. `debug.getlocal(f, n)`
/// names a function's `n`th parameter.
fn debug_getlocal(vm: &mut VM, args: &[Value]) -> Result<Vec<Value>, String> {
    let n = count_arg(args, 1, "n", 1)?;
    if let Some(Value::Closure(c)) = args.first() {
        let name = c
            .proto
            .local_names
            .iter()
            .filter(|info| info.from_pc == 0 && (info.reg as i64) < c.proto.num_params as i64)
            .nth((n - 1).max(0) as usize)
            .filter(|_| n >= 1)
            .map(|info| Value::str(&info.name));
        return Ok(vec![name.unwrap_or(Value::Nil)]);
    }
    let level = count_arg(args, 0, "level", 1)?;
    let Some(frame) = frame_at(vm, level) else {
        return Err("level out of range".to_string());
    };
    if n < 0 {
        let index = (-n - 1) as usize;
        return Ok(match frame.varargs.get(index) {
            Some(v) => vec![Value::str("(vararg)"), v.clone()],
            None => vec![Value::Nil],
        });
    }
    let locals = active_locals(frame);
    let Some(info) = (n >= 1).then(|| locals.get(n as usize - 1)).flatten() else {
        return Ok(vec![Value::Nil]);
    };
    let value = vm
        .stack
        .get(frame.base + info.reg as usize)
        .cloned()
        .unwrap_or(Value::Nil);
    Ok(vec![Value::str(&info.name), value])
}

/// `debug.setlocal(level, n, value)`: assigns the `n`th local in scope and
/// returns its name, or nil when there is no such local.
fn debug_setlocal(vm: &mut VM, args: &[Value]) -> Result<Vec<Value>, String> {
    let level = count_arg(args, 0, "level", 1)?;
    let n = count_arg(args, 1, "n", 1)?;
    let value = args.get(2).cloned().unwrap_or(Value::Nil);
    let Some(frame) = frame_at(vm, level) else {
        return Err("level out of range".to_string());
    };
    if n < 0 {
        let index = (-n - 1) as usize;
        let at = vm.frames.len() - level as usize;
        return Ok(match vm.frames[at].varargs.get_mut(index) {
            Some(slot) => {
                *slot = value;
                vec![Value::str("(vararg)")]
            }
            None => vec![Value::Nil],
        });
    }
    let target = active_locals(frame)
        .get((n - 1).max(0) as usize)
        .filter(|_| n >= 1)
        .map(|info| (info.name.clone(), frame.base + info.reg as usize));
    let Some((name, slot)) = target else {
        return Ok(vec![Value::Nil]);
    };
    if slot >= vm.stack.len() {
        vm.stack.resize(slot + 1, Value::Nil);
    }
    vm.stack[slot] = value;
    Ok(vec![Value::string(name)])
}

fn upvalue_name(c: &crate::vm::value::VmClosure, index: usize) -> Value {
    match c.proto.upvalue_names.get(index) {
        Some(name) if !name.is_empty() => Value::str(name),
        _ => Value::str("?"),
    }
}

/// `debug.getupvalue(f, n)`: the name and value of `f`'s `n`th upvalue.
fn debug_getupvalue(vm: &mut VM, args: &[Value]) -> Result<Vec<Value>, String> {
    let Some(Value::Closure(c)) = args.first() else {
        return Ok(vec![Value::Nil]);
    };
    let n = count_arg(args, 1, "n", 1)?;
    if n < 1 || n as usize > c.upvalues.len() {
        return Ok(vec![Value::Nil]);
    }
    let value = vm.upvalue_get(&c.upvalues[n as usize - 1]);
    Ok(vec![upvalue_name(c, n as usize - 1), value])
}

/// `debug.setupvalue(f, n, value)`: assigns `f`'s `n`th upvalue and returns
/// its name.
fn debug_setupvalue(vm: &mut VM, args: &[Value]) -> Result<Vec<Value>, String> {
    let Some(Value::Closure(c)) = args.first() else {
        return Ok(vec![Value::Nil]);
    };
    let n = count_arg(args, 1, "n", 1)?;
    if n < 1 || n as usize > c.upvalues.len() {
        return Ok(vec![Value::Nil]);
    }
    let value = args.get(2).cloned().unwrap_or(Value::Nil);
    let uv = c.upvalues[n as usize - 1].clone();
    vm.upvalue_set(&uv, value);
    Ok(vec![upvalue_name(c, n as usize - 1)])
}

/// `debug.upvalueid(f, n)`: a number identifying the variable behind `f`'s
/// `n`th upvalue, equal for closures that share it.
fn debug_upvalueid(_vm: &mut VM, args: &[Value]) -> Result<Vec<Value>, String> {
    let Some(Value::Closure(c)) = args.first() else {
        return Err("upvalueid expects a function".to_string());
    };
    let n = count_arg(args, 1, "n", 1)?;
    match (n >= 1).then(|| c.upvalues.get(n as usize - 1)).flatten() {
        Some(uv) => Ok(vec![Value::Int(Rc::as_ptr(uv) as i64)]),
        None => Ok(vec![Value::Nil]),
    }
}

/// `debug.getmetatable(t)`, ignoring a `__metatable` field.
fn debug_getmetatable(_vm: &mut VM, args: &[Value]) -> Result<Vec<Value>, String> {
    Ok(vec![match args.first() {
        Some(Value::Table(t)) => t
            .borrow()
            .metatable
            .clone()
            .map(Value::Table)
            .unwrap_or(Value::Nil),
        _ => Value::Nil,
    }])
}

/// `debug.setmetatable(t, mt)`, ignoring a `__metatable` field.
fn debug_setmetatable(vm: &mut VM, args: &[Value]) -> Result<Vec<Value>, String> {
    let Some(Value::Table(t)) = args.first() else {
        return Err("setmetatable expects a table".to_string());
    };
    let mt = match args.get(1) {
        None | Some(Value::Nil) => None,
        Some(Value::Table(mt)) => Some(mt.clone()),
        Some(other) => {
            return Err(format!(
                "metatable must be a table or nil, got {}",
                other.type_name()
            ));
        }
    };
    let gc_handler = mt.as_ref().is_some_and(|mt| {
        matches!(
            mt.borrow().get_str("__gc"),
            Value::Closure(_) | Value::Native(_)
        )
    });
    t.borrow_mut().metatable = mt;
    if gc_handler {
        vm.gc.pin_table(t);
    } else {
        vm.gc.unpin_table(t);
    }
    if crate::vm::gc::table_weak_values(t) {
        vm.gc.has_weak_tables = true;
    }
    Ok(vec![args[0].clone()])
}

/// `debug.sethook(hook, mask?, count?)`, or `debug.sethook()` to remove it.
/// The mask holds `c` (calls, including tail calls), `r` (returns) and `l`
/// (each new line, and each jump back into a loop); with a count the hook
/// also gets a "count" event every `count` instructions. The hook receives
/// the event name, and the line number for line events. Hooks never trigger
/// hooks.
fn debug_sethook(vm: &mut VM, args: &[Value]) -> Result<Vec<Value>, String> {
    let func = args.first().cloned().unwrap_or(Value::Nil);
    if matches!(func, Value::Nil) {
        vm.hook = None;
        vm.update_trap();
        return Ok(Vec::new());
    }
    if !matches!(func, Value::Closure(_) | Value::Native(_)) {
        return Err(format!("hook must be a function, got {}", func.type_name()));
    }
    let mask = match args.get(1) {
        // Without a mask or count, report calls and returns.
        None | Some(Value::Nil) if args.get(2).is_none() => "cr",
        None | Some(Value::Nil) => "",
        Some(Value::String(s)) => s,
        Some(other) => {
            return Err(format!("mask must be a string, got {}", other.type_name()));
        }
    };
    let (mut on_call, mut on_return, mut on_line) = (false, false, false);
    for ch in mask.chars() {
        match ch {
            'c' => on_call = true,
            'r' => on_return = true,
            'l' => on_line = true,
            _ => return Err(format!("invalid hook mask character '{}'", ch)),
        }
    }
    let count = count_arg(args, 2, "count", 0)?.clamp(0, u32::MAX as i64) as u32;
    vm.hook = Some(crate::vm::machine::DebugHook {
        func,
        on_call,
        on_return,
        on_line,
        count,
    });
    vm.hook_countdown = count;
    // The line that called sethook has already started.
    if let Some(frame) = vm.frames.last_mut() {
        let pc = current_pc(frame);
        frame.hook_line = frame.closure.proto.lines.get(pc).copied().unwrap_or(0);
        frame.hook_ip = pc;
    }
    vm.update_trap();
    Ok(Vec::new())
}

/// `debug.gethook()`: the hook function, its mask and its count.
fn debug_gethook(vm: &mut VM, _args: &[Value]) -> Result<Vec<Value>, String> {
    let Some(hook) = &vm.hook else {
        return Ok(vec![Value::Nil]);
    };
    let mut mask = String::new();
    if hook.on_call {
        mask.push('c');
    }
    if hook.on_return {
        mask.push('r');
    }
    if hook.on_line {
        mask.push('l');
    }
    Ok(vec![
        hook.func.clone(),
        Value::string(mask),
        Value::Int(hook.count as i64),
    ])
}