neyuki 0.6.3

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
//! The global functions: print, assert, type, tostring, tonumber, error,
//! pcall, require and friends.

use num_bigint::BigInt;
use num_traits::{FromPrimitive, ToPrimitive};
use std::str::FromStr;

use crate::vm::machine::VM;
use crate::vm::value::Value;

pub fn builtin_print(vm: &mut VM, args: &[Value]) -> Result<Vec<Value>, String> {
    use std::io::Write;
    let mut out = String::new();
    for (i, arg) in args.iter().enumerate() {
        if i > 0 {
            out.push('\t');
        }
        match arg {
            Value::String(s) => out.push_str(s),
            other => out.push_str(&tostring(vm, other)?),
        }
    }
    out.push('\n');
    if vm.dap.is_some() {
        crate::dap::output(vm, "stdout", &out);
    } else {
        // A closed pipe (`neyuki run x | head`) is not the script's error.
        let _ = std::io::stdout().lock().write_all(out.as_bytes());
    }
    Ok(Vec::new())
}

pub fn builtin_assert(_vm: &mut VM, args: &[Value]) -> Result<Vec<Value>, String> {
    let cond = args.first().cloned().unwrap_or(Value::Nil);
    if !cond.is_truthy() {
        let msg = args
            .get(1)
            .map(|v| v.to_string())
            .unwrap_or_else(|| "assertion failed".to_string());
        return Err(msg);
    }
    Ok(vec![cond])
}

pub fn builtin_type(_vm: &mut VM, args: &[Value]) -> Result<Vec<Value>, String> {
    let val = args.first().unwrap_or(&Value::Nil);
    Ok(vec![Value::String((val.type_name().to_string()).into())])
}

pub fn builtin_typeof(_vm: &mut VM, args: &[Value]) -> Result<Vec<Value>, String> {
    let val = args.first().unwrap_or(&Value::Nil);
    Ok(vec![Value::String((val.typeof_name().to_string()).into())])
}

pub fn builtin_checktype(_vm: &mut VM, args: &[Value]) -> Result<Vec<Value>, String> {
    let val = args.first().unwrap_or(&Value::Nil);
    let ty_str = match args.get(1) {
        Some(Value::String(s)) => &**s,
        _ => return Err("checktype expects a type string as argument #2".to_string()),
    };
    let ty = crate::ast::ty::TypeExpr::parse(ty_str);
    Ok(vec![Value::Bool(val.matches_type_expr(&ty))])
}

pub fn builtin_asserttype(_vm: &mut VM, args: &[Value]) -> Result<Vec<Value>, String> {
    let val = args.first().unwrap_or(&Value::Nil);
    let ty_str = match args.get(1) {
        Some(Value::String(s)) => &**s,
        _ => return Err("asserttype expects a type string as argument #2".to_string()),
    };
    let ty = crate::ast::ty::TypeExpr::parse(ty_str);
    if !val.matches_type_expr(&ty) {
        let msg = args.get(2).map(|v| v.to_string()).unwrap_or_else(|| {
            format!(
                "type assertion failed: expected '{}', got '{}'",
                ty_str,
                val.typeof_name()
            )
        });
        return Err(msg);
    }
    Ok(vec![val.clone()])
}

/// A value as `tostring` prints it, honoring `__tostring`.
pub fn tostring(vm: &mut VM, val: &Value) -> Result<String, String> {
    if let Value::Table(t) = val {
        let handler = t.borrow().metamethod("__tostring");
        if let Some(h) = handler {
            let res = vm.call_function(h, std::slice::from_ref(val))?;
            return Ok(res.into_iter().next().unwrap_or(Value::Nil).to_string());
        }
    }
    Ok(val.to_string())
}

pub fn builtin_tostring(vm: &mut VM, args: &[Value]) -> Result<Vec<Value>, String> {
    let val = args.first().unwrap_or(&Value::Nil);
    if let Value::String(_) = val {
        return Ok(vec![val.clone()]);
    }
    Ok(vec![Value::string(tostring(vm, val)?)])
}

pub fn builtin_tonumber(_vm: &mut VM, args: &[Value]) -> Result<Vec<Value>, String> {
    let val = args.first().unwrap_or(&Value::Nil);
    let base_opt = args.get(1);

    if let Some(base_val) = base_opt
        && !matches!(base_val, Value::Nil)
    {
        let base = match base_val {
            Value::Int(i) => i.to_i64().unwrap_or(0),
            Value::Float(f) => *f as i64,
            _ => return Err("bad argument #2 to 'tonumber' (base out of range)".to_string()),
        };
        if !(2..=36).contains(&base) {
            return Err("bad argument #2 to 'tonumber' (base out of range)".to_string());
        }
        let s = match val {
            Value::String(s) => &**s,
            _ => return Ok(vec![Value::Nil]),
        };
        if s.len() > 65_536 {
            return Ok(vec![Value::Nil]);
        }
        let s_trimmed = s.trim();
        let (sign, s_digits) = if let Some(stripped) = s_trimmed.strip_prefix('-') {
            (-1, stripped.trim_start())
        } else if let Some(stripped) = s_trimmed.strip_prefix('+') {
            (1, stripped.trim_start())
        } else {
            (1, s_trimmed)
        };
        let s_digits = if base == 16 {
            if let Some(stripped) = s_digits
                .strip_prefix("0x")
                .or_else(|| s_digits.strip_prefix("0X"))
            {
                stripped
            } else {
                s_digits
            }
        } else {
            s_digits
        };
        if s_digits.is_empty() {
            return Ok(vec![Value::Nil]);
        }
        return match BigInt::parse_bytes(s_digits.as_bytes(), base as u32) {
            Some(bi) => {
                let bi = if sign < 0 { -bi } else { bi };
                Ok(vec![Value::from_bigint(bi)])
            }
            None => Ok(vec![Value::Nil]),
        };
    }

    match val {
        Value::Int(i) => Ok(vec![Value::Int(*i)]),
        Value::BigInt(_) => Ok(vec![val.clone()]),
        Value::Float(f) => Ok(vec![Value::Float(*f)]),
        Value::String(s) => {
            if s.len() > 65_536 {
                return Ok(vec![Value::Nil]);
            }
            let s_trimmed = s.trim();
            let (sign, s_rest) = if let Some(stripped) = s_trimmed.strip_prefix('-') {
                (-1, stripped.trim_start())
            } else if let Some(stripped) = s_trimmed.strip_prefix('+') {
                (1, stripped.trim_start())
            } else {
                (1, s_trimmed)
            };
            if let Some(stripped_hex) = s_rest
                .strip_prefix("0x")
                .or_else(|| s_rest.strip_prefix("0X"))
                && !stripped_hex.is_empty()
                && let Some(bi) = BigInt::parse_bytes(stripped_hex.as_bytes(), 16)
            {
                let bi = if sign < 0 { -bi } else { bi };
                return Ok(vec![Value::from_bigint(bi)]);
            }
            if let Ok(i) = s_trimmed.parse::<i64>() {
                Ok(vec![Value::from_bigint(BigInt::from(i))])
            } else if let Ok(bi) = BigInt::from_str(s_trimmed) {
                Ok(vec![Value::from_bigint(bi)])
            } else if let Ok(f) = s_trimmed.parse::<f64>() {
                Ok(vec![Value::Float(f)])
            } else {
                Ok(vec![Value::Nil])
            }
        }
        _ => Ok(vec![Value::Nil]),
    }
}

pub fn builtin_int(_vm: &mut VM, args: &[Value]) -> Result<Vec<Value>, String> {
    let val = args.first().unwrap_or(&Value::Nil);
    match val {
        Value::Int(i) => Ok(vec![Value::Int(*i)]),
        Value::BigInt(_) => Ok(vec![val.clone()]),
        Value::Float(f) => Ok(vec![Value::from_bigint(
            BigInt::from_f64(f.trunc()).unwrap_or_default(),
        )]),
        Value::String(s) => {
            if s.len() > 65_536 {
                return Err("integer string exceeds maximum length limit (65536 bytes)".to_string());
            }
            let bi = BigInt::parse_bytes(s.as_bytes(), 10)
                .ok_or_else(|| "invalid integer string".to_string())?;
            Ok(vec![Value::from_bigint(bi)])
        }
        _ => Err("int expects number or string".to_string()),
    }
}

pub fn builtin_float(_vm: &mut VM, args: &[Value]) -> Result<Vec<Value>, String> {
    let val = args.first().unwrap_or(&Value::Nil);
    match val {
        Value::Float(f) => Ok(vec![Value::Float(*f)]),
        Value::Int(i) => Ok(vec![Value::Float(i.to_f64().unwrap_or(0.0))]),
        Value::String(s) => {
            let f = s
                .parse::<f64>()
                .map_err(|_| "invalid float string".to_string())?;
            Ok(vec![Value::Float(f)])
        }
        _ => Err("float expects number or string".to_string()),
    }
}

pub fn builtin_error(_vm: &mut VM, args: &[Value]) -> Result<Vec<Value>, String> {
    let msg = args
        .first()
        .map(|v| v.to_string())
        .unwrap_or_else(|| "error".to_string());
    Err(msg)
}

pub fn builtin_pcall(vm: &mut VM, args: &[Value]) -> Result<Vec<Value>, String> {
    let func = args
        .first()
        .ok_or_else(|| "pcall expects at least 1 argument".to_string())?;
    match vm.call_function(func.clone(), &args[1..]) {
        Ok(mut res) => {
            res.insert(0, Value::Bool(true));
            Ok(res)
        }
        Err(err) => {
            vm.error_trace = None;
            Ok(vec![Value::Bool(false), Value::string(err)])
        }
    }
}

/// `try(f, ...)` is `pcall` under the name the bundled libraries use: it
/// returns `true` followed by the results, or `false` and the error message.
pub fn builtin_try(vm: &mut VM, args: &[Value]) -> Result<Vec<Value>, String> {
    let func = args
        .first()
        .ok_or_else(|| "try expects a function".to_string())?;
    match vm.call_function(func.clone(), &args[1..]) {
        Ok(mut res) => {
            res.insert(0, Value::Bool(true));
            Ok(res)
        }
        Err(err) => {
            vm.error_trace = None;
            Ok(vec![Value::Bool(false), Value::string(err)])
        }
    }
}

pub fn builtin_xpcall(vm: &mut VM, args: &[Value]) -> Result<Vec<Value>, String> {
    let func = args
        .first()
        .ok_or_else(|| "xpcall expects at least 2 arguments".to_string())?;
    let err_handler = args
        .get(1)
        .ok_or_else(|| "xpcall expects at least 2 arguments".to_string())?;
    let call_args = if args.len() > 2 { &args[2..] } else { &[] };
    match vm.call_function(func.clone(), call_args) {
        Ok(mut res) => {
            res.insert(0, Value::Bool(true));
            Ok(res)
        }
        Err(err) => {
            vm.error_trace = None;
            let err_val = Value::string(err);
            match vm.call_function(err_handler.clone(), std::slice::from_ref(&err_val)) {
                Ok(h_res) => {
                    let ret = h_res.into_iter().next().unwrap_or(err_val);
                    Ok(vec![Value::Bool(false), ret])
                }
                Err(h_err) => Ok(vec![
                    Value::Bool(false),
                    Value::String((format!("error in error handling: {}", h_err)).into()),
                ]),
            }
        }
    }
}

/// Resolves a standard or bundled `@neyuki/...` module (the prefix is
/// optional), or returns `None` when `name` is neither. Bundled sources run
/// once; every later `require` gets the same table.
fn load_bundled_module(vm: &mut VM, name: &str) -> Result<Option<Value>, String> {
    let bare = name.strip_prefix("@neyuki/").unwrap_or(name);
    if let Some(cached) = vm.modules.get(bare).cloned() {
        return Ok(Some(cached));
    }
    let Some((_, source)) = crate::vm::libs::BUNDLED_LIBRARIES
        .iter()
        .find(|(bundled, _)| bundled.strip_prefix("@neyuki/") == Some(bare))
    else {
        return Ok(None);
    };
    let proto = crate::compiler::compile_program(source, name, crate::compiler::Options::UNCHECKED)
        .map_err(|err| format!("error in module '{}': {}", name, err))?;
    let value = vm.execute_module(proto)?;
    vm.modules.insert(bare.to_string(), value.clone());
    Ok(Some(value))
}

pub fn builtin_require(vm: &mut VM, args: &[Value]) -> Result<Vec<Value>, String> {
    let pkg = match args
        .first()
        .ok_or_else(|| "require expects a module path".to_string())?
    {
        Value::String(s) => &**s,
        _ => return Err("require expects string argument".to_string()),
    };
    if let Some(val) = load_bundled_module(vm, pkg)? {
        return Ok(vec![val]);
    }
    let path_obj = std::path::Path::new(pkg);
    if pkg.contains('\0')
        || pkg.contains("..")
        || pkg.starts_with('/')
        || pkg.starts_with('\\')
        || path_obj.is_absolute()
        || path_obj.components().any(|c| {
            matches!(
                c,
                std::path::Component::ParentDir
                    | std::path::Component::RootDir
                    | std::path::Component::Prefix(_)
            )
        })
    {
        return Err(format!(
            "security error: path traversal forbidden in require: '{}'",
            pkg
        ));
    }

    let mut loader = crate::module_loader::ModuleLoader::new();
    if let Some(dir) = &vm.script_dir {
        loader = loader.with_base_dir(dir.clone());
    }
    let located = loader
        .locate_module(pkg)
        .map_err(|_| format!("cannot find module '{}'", pkg))?;
    let key = located.cache_key();
    if let Some(cached) = vm.modules.get(&key).cloned() {
        return Ok(vec![cached]);
    }
    let (resolved_path, bytes) = loader.read_located(&located)?;
    let proto = loader.compile_bytes(&resolved_path, &bytes, pkg)?;
    // While the module runs, a `require` cycle back into it gets an empty
    // table instead of running it again (docs/modules.md, ยง3.2).
    let pending = Value::Table(std::rc::Rc::new(std::cell::RefCell::new(
        crate::vm::value::VmTable::new(),
    )));
    vm.modules.insert(key.clone(), pending);
    // Run on top of the current frames: `execute` would reset the
    // stack out from under whatever called `require`.
    match vm.execute_module((*proto).clone()) {
        Ok(val) => {
            vm.modules.insert(key, val.clone());
            Ok(vec![val])
        }
        Err(err) => {
            // A failed load is not cached: the next `require` tries again.
            vm.modules.remove(&key);
            Err(err)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_checktype_and_asserttype() {
        let mut vm = VM::new();

        // checktype
        let res = builtin_checktype(&mut vm, &[Value::Int(42), Value::str("int")]).unwrap();
        assert_eq!(res, vec![Value::Bool(true)]);

        let res = builtin_checktype(&mut vm, &[Value::str("hello"), Value::str("int")]).unwrap();
        assert_eq!(res, vec![Value::Bool(false)]);

        let res =
            builtin_checktype(&mut vm, &[Value::str("hello"), Value::str("int | string")]).unwrap();
        assert_eq!(res, vec![Value::Bool(true)]);

        // void maps to Never, so it never matches
        let res = builtin_checktype(&mut vm, &[Value::Nil, Value::str("void")]).unwrap();
        assert_eq!(res, vec![Value::Bool(false)]);

        // unknown named type must return false, not true
        let res = builtin_checktype(&mut vm, &[Value::Int(42), Value::str("UnknownType")]).unwrap();
        assert_eq!(res, vec![Value::Bool(false)]);

        // asserttype success
        let res = builtin_asserttype(&mut vm, &[Value::Int(42), Value::str("int")]).unwrap();
        assert_eq!(res, vec![Value::Int(42)]);

        // asserttype failure
        let err =
            builtin_asserttype(&mut vm, &[Value::str("hello"), Value::str("int")]).unwrap_err();
        assert!(err.contains("type assertion failed"));
    }
}