lua

    A complete Lua 5.4 interpreter written in MoonBit

    lua
    interpreter
    vm
    script
    Download zip
    Version
    0.1.0
    License
    Apache-2.0
    Last updated
    last month
    Downloads
    64

    #hongweifei/lua

    简体中文 | English

    用 MoonBit 实现的 Lua 5.4 解释器。词法分析、语法分析、单遍代码生成、寄存器式虚拟机和全部标准库都在本仓库内实现;宿主只提供语言运行时无法自己提供的东西——流、文件、时钟、环境变量、进程控制、与 printf 兼容的数字格式化和随机数发生器。这条边界就是 stub.c,它扮演的正是参考实现里 C 标准库的角色。

    #快速开始

    moon build --target native --release

    解释器会被构建到 _build/native/release/build/cmd/main/main.exe,它同时就是 lua 命令行界面。运行脚本、执行一段代码,或进入交互式循环:

    moon run cmd/main -- script.lua arg1 arg2 moon run cmd/main -- -e 'print("hello")' moon run cmd/main # 从 stdin 读取;终端下会显示提示符

    跑测试:

    moon test

    这个移植还支持用中文(以及任何 UTF-8)命名变量、函数和字段:

    $ moon run cmd/main -- -e 'local 名字 = "世界"; print("你好," .. 名字)' 你好,世界

    细节与限制见下面与参考实现的差异里的标识符那一条。

    #示例

    examples/ 里是可运行的程序。每个示例都用 assert 校验自己的结果,而不是打印一份期望输出,所以跑一遍就是测试;它们都是普通的 Lua 5.4 代码,因此用参考版 lua 二进制跑也同样通过。

    示例展示了什么
    examples/basics.lua整数与浮点两种数字子类型、字节串、表、闭包、变长参数、尾调用、pcall/xpcall
    examples/coroutines.luacoroutine.wrap 生成器、在元方法中让出(yield)、coroutine.close 触发待处理的 <close> 变量
    examples/metatables.lua运算符重载、__index 表链、只读代理、to-be-closed 变量

    moon run cmd/main -- examples/basics.lua

    examples/embed/ 是把解释器嵌进 MoonBit 程序的示例:运行 chunk、通过全局变量双向传值、调用 Lua 函数、读取失败 chunk 的错误对象。

    moon run examples/embed

    #目录结构

    每个含 moon.pkg 的目录就是一个包。模块根目录既是元数据,也是面向 MoonBit 嵌入者的公开包(hongweifei/lua);可执行程序在 cmd/main,实现分布在 src 下的十七个包里。

    包内容
    hongweifei/lua(根包)嵌入用的公开接口:Lua 句柄、Value/Table 别名、ToLua、host_function、LuaError(embed.mbt、values.mbt、host_functions.mbt、errors.mbt)
    src/host宿主边界:ffi.mbt 里的 extern "c" 声明,以及实现它们的 stub.c
    src/core值模型与状态:value、objects、table、table_hash、thread、userdata、state;数字(number、number_format)、opcode、bytes、core 直接调用的宿主服务、names(错误消息从运行中的代码借用的名字)以及 binop / load_outcome
    src/vm解释器循环及其派发:vm、vm_frame、vm_call、vm_instr、vm_index、vm_arith、vm_compare、vm_convert、vm_hook
    src/compiler扫描器(token、lexer、lexer_string)、语法分析(ast、parser、parser_expr、parser_stat)与代码生成(funcstate、funcstate_regs、compiler_entry、compiler_expr、compiler_call、compiler_stat、compiler_scope)
    src/chunkstring.dump(chunk_dump)以及加载其产物的 chunk_undump
    src/patternLua 模式匹配,以及建立在它之上的库函数
    src/load把源码或二进制 chunk 变成可调用的原型:state_load、base_load
    src/lib/base、string、math、io、os、table、utf8、coroutine、debug每个标准库一个包
    src/lua对外入口:lua、api、stdlib、lib_package,以及 Lua 测试套件(*_test.mbt)
    cmd/main命令行界面
    examples/embed嵌入解释器的示例程序;与它并列的 Lua 示例是数据文件,不是包

    依赖图无环:

    host └ core ─┬─ vm ├─ compiler ├─ chunk ├─ pattern ├─ load ← chunk, compiler, vm ├─ lib/* ← load, vm, pattern, chunk └─ lua ← lib/*, load, vm └ (根包) ← core, lua

    宿主边界只有 host 一个包,直接依赖它的只有五处:core(解释器自己要用到的宿主服务,其余包经它的包装使用)、src/lua(启动器与 package 的搜索路径)、以及三个本身就是宿主服务包装的标准库——lib/io、lib/os,和 lib/math 的随机数(参考实现里 liolib.c/loslib.c/lmathlib.c 同样是直接调 C 库的薄包装)。

    值会跨包边界传递,所以共享声明导出得很宽:类型、struct、enum、trait 与 suberror 都是 pub(all);其他包依赖的 trait 实现是 pub impl。方法留在声明其类型的包里。少数包在 moon.pkg 中设了 warnings = "-24",因为每个标准库入口都带 raise LuaRaised 以匹配内建函数的类型,无论该函数是否真的会抛。

    tests/ 放 moon test 会通过解释器执行的 Lua 套件,examples/ 放上面提到的可运行程序。

    #作为库使用

    从 MoonBit 程序里嵌入它只需要 import { "hongweifei/lua" }:不必 import 解释器的内部包,也不必碰 Bytes 或 C 风格的签名。

    let lua = Lua::new()
    lua.set("上限", 100) // MoonBit 的值直接写进 globals
    lua.set_function("平方", fn(args) { // MoonBit 闭包就是 Lua 函数
    match args[0].as_integer() {
    Some(x) => Ok([Value::VInt(x * x)])
    None => Err(Value::text("integer expected"))
    }
    })
    let total = lua.eval_int("return 平方(3) + 上限") // Ok(109)

    Lua::new 打开全部标准库。run、run_file、call 都返回 Result[Array[Value], LuaError]:脚本失败不会抛 MoonBit 异常,LuaError 同时带着错误对象本身(error({code=42}) 里那个表可以逐字段读)和按语言规则渲染出的文本。Value 是解释器自己的值的别名,所以它的读法与语言用的是同一套规则——as_integer 就是 math.tointeger,raw_equal 就是 ==,as_bytes 给的是字符串的原始字节。

    数据两个方向都成对:ToLua 把 MoonBit 数据搬进 Lua(标量、Array(1 起的序列)、Map、Option(None 就是 nil)),FromLua 搬回来——表可以整个读成 Map[String, T] 或 Array[T](序列读到第一个空位为止)。读取时类型写在注解上,因为这门语言没有「在调用处写出类型参数」的语法;下面这几个 eval_* 的近路不必写,它们就是常用类型的 FromLua:

    let size : Map[String, Int]? = read_lua(lua.get("配置")) // 表 → Map
    let items : Array[Int64]? = read_lua(lua.get("清单")) // 表 → 序列
    let limit : Result[Int64, LuaError] = lua.get_as("上限") // Err 里是语言那种话
    let vs = lua.run("return '一', '二'").unwrap()
    let words : Result[Array[String], LuaError] = lua.values_as(vs)

    读法的失败说得和库函数一样具体,而且指向真正出错的那个值:把 {7, 'x'} 读成 Array[Int64] 会说 number expected, got string(说的是那一项,不是那个表)。反过来一个 MoonBit 模块可以直接交给脚本:lua.preload("设置", fn(_) { ... }) 之后脚本里的 require("设置") 就能拿到它,宿主这边 lua.require("设置") 也拿得到同一个值(package.loaded 的缓存照常生效)。表的自身字段与序列也可以不经过转换直接取:table_entries / table_sequence。

    再下面一层(src/lua 与 src/core)也直接可用:命令行界面就是用它们搭起来的。

    可运行的完整版本是 examples/embed/main.mbt(moon run examples/embed,它自己用 assert 校验结果);上面那段代码也在根包的 embed_test.mbt 里跑着,那个文件只用公开接口——这正是它要验证的事。

    #实现要点

    • 数字。 整数为 64 位并环绕;浮点是 IEEE 双精度。两种子类型在任何地方都区分对待,包括作为表键时——整数值的浮点会归一化为整数,因此 t[1] 与 t[1.0] 指向同一格。十六进制整数环绕,装不下的十进制整数变为浮点,与语言规范一致。
    • 字符串。 Lua 字符串是字节序列,所以内部一律用 Bytes 承载,绝不经过 MoonBit 的 UTF-16 String 往返。长度、切片、模式匹配和比较都以字节为单位。
    • UTF-8 无处不在,标识符也可以是中文。 字符串按字节处理,所以源码里的中文注释、中文字符串字面量和 utf8 库都按 Lua 的语义工作;在此之上本实现还允许标识符写成 UTF-8:ASCII 之外的一个合法码点就是一个名字字符,于是 local 中 = 1、function 打招呼(谁)、表.键、对象:加一()、::再来:: 都能用,混写(字母A、café)也可以。这是相对参考实现的扩展(它的字符表只覆盖 ASCII,见下方差异),不是移植行为。从文件读入的 chunk 还允许带 UTF-8 BOM 和以 # 开头的首行(可执行的 #! 脚本),两者都会被丢掉,而那一行用一个换行代替——行号因此不动,这正是 luaL_loadfilex 的 skipBOM/skipcomment;作为字符串交给 load 的 chunk 不做这件事(那里的 # 是长度运算符)。os.date 也按参考实现那样逐个转换说明符交给宿主 strftime、其余字节原样穿过,所以 os.date("%Y年") 得到 1970年——整串交给 strftime 会把多字节字符旁边那段文字吞掉。文件名同样是字节:能按 UTF-8 读的名字就按 UTF-8 交给宿主,因此中文文件名在 Windows 上可用(见下方差异);不是 UTF-8 的名字原样传递,宿主自己的单字节编码照旧。
    • 执行。 解释器循环是迭代式的:运行中函数的全部可变状态都放在一个 frame 记录里,因此协程的挂起就是从循环返回,恢复就是重新进入循环。原生函数也是 frame,这正是 pcall 与 coroutine.yield 无论守护的调用写在 Lua 里还是宿主语言里都表现一致的原因。
    • 代码生成 是对语法树的一遍扫描,带表达式描述符和空闲寄存器窗口,沿用参考编译器的形态。比较和短路运算符编译为一个值加一条显式条件跳转;调用和 ... 保持开放,直到消费它们的构造决定要几个结果。
    • 错误 以 MoonBit 异常传递,在解释器安装的保护锚点被捕获:一个被恢复的协程,或一个带 pcall 延续的 frame。因为保护放在 frame 而不是宿主栈上,从 pcall 里让出(yield)可以工作,嵌套协程也可以。
    • 内存。 对象由宿主运行时管理,它使用引用计数,因此循环垃圾在进程退出时被回收。collectgarbage 报告真实的分配数字并遵守常用选项,但它的 "collect" 无法释放环。

    #状态

    tools/run_official_tests.mbtx 把官方 5.4.9 套件的每个文件都通过本解释器跑一遍:30 个中 28 个通过。未通过的两个,其失败点与本平台构建的参考实现完全相同(用同一个文件跑参考实现验证过):

    • files 停在 files.lua:84,断言的是 io.stdin 上的 seek。C 库允许对标准输入句柄 fseek 成功,而测试期望它被拒绝。
    • attrib 停在 attrib.lua:154,是 try('B', 'B.lua', true, "libs/B.lua") 里的 assert(ext == x)。期望的 loader 数据写死了正斜杠,而 Windows 上 package.config 给出的是反斜杠,搜索器构造的每条路径都用它。

    两者都是环境差异,而非两种实现之间的差异;套件为此提供了 _port 开关:跑不了非可移植测试的移植版会打开它,相应代码块被跳过。本 harness 故意不开,所以那些块确实在跑——除了上面两行之外全部通过。

    files 停在第 84 行,它后面的内容(含 files.lua:537–550 那组 BOM 与 # 首行的用例)在这条路径上跑不到。把那一段单独拿出来、两种实现各跑一遍,两边都通过;tests/language.lua 里也钉了同样四组用例。同一份 files.lua 若把 stdin 关掉(exec 0<&-),本实现会一直跑到 files.lua:202:那里要求从 dofile 内部让出协程(coroutine.wrap(dofile)),而本实现报 "attempt to yield across a C-call boundary"——参考实现能过。这是已知的缺口,不在本轮改动范围内。

    套件的最后两个文件需要说明一下。cstack 的实质工作会真正运行(只有末尾 if T then 段需要参考实现的 C 测试库)并且通过。api 测的是 C API,用别的语言实现的解释器无法暴露:它整个主体被 if T==nil then ... return end 保护,所以两种实现都会跳过它并报告成功。把它列进 harness 是为了让文件清单完整,它不是独立证据。

    套件压得最狠的几个方面,本解释器的表现:

    • 真正的收集器。 collectgarbage 从根开始标记,处理需要可达性的规则——弱表、ephemeron、按参考实现顺序执行的 __gc 终结——并随程序分配自行运行。内存属于宿主运行时,靠引用计数回收,所以收集器判定的是可达性而不是释放什么;一个环仍然随进程结束。collectgarbage("count") 报告活集占用的字节(含字符串),由遍历测出。
    • 可恢复的宿主调用。 当宿主函数仍在栈上时发生的 coroutine.yield——在 __pairs 里、在 __close 处理器里、在元方法里——沿着错误通道出去再回来,发起该调用的指令在恢复时是完成而不是重跑。
    • debug 保真。 行事件、层数计算、尾调用、回溯的命名与省略、debug.getinfo 的各字段,都与参考构建逐指令一致。
    • 两个预算。 未捕获错误带回溯报告;无休止分配的程序会被以参考实现的 "not enough memory" 拒绝,而不是把进程拖垮;经宿主回调的递归在宿主栈快用完时被以 "C stack overflow" 拒绝,而不是把真实栈耗尽(两者都见下方差异)。

    #与参考实现的差异

    • 活数据超过 1 GB 的程序会被拒绝,消息是参考实现的 "not enough memory"(src/core/state.mbt 的 MEMORY_LIMIT)。参考实现没有这个数字:它的分配器在宿主给不出更多内存时失败,在大机器上那是好几 GB 之后。这里的内存归宿主运行时所有,它无法优雅地拒绝,所以解释器保留自己的预算。它是一个常量。
    • collectgarbage("setstepmul", m) 现在真的影响步进,但账本仍是本实现自己的。 它按参考实现的方向缩放"一步值多少工作"(incstep 用乘数缩放债务):乘数越大,一轮需要的调用越少,越小则越多(实测 5000 → 2 次、50 → 200 次;默认 100 时一切不变)。参考实现自身的 stepmul 效果只有约 1%,因为它由债务与信用主导;这里的绝对次数因此与它不同。它还像参考实现一样把参数按 4 的倍数存储(GCPARAM_ADJ),所以 setstepmul(50) 下次回报 48;而参考实现存参数的字节会让极大的值回绕,这里保持原值并夹紧。

    • collectgarbage("step") 的账本现在是照参考实现的债务算的,但数字仍是本实现自己的。 它模拟参考实现的 incstep:有尺寸的一步只经由 luaC_checkGC 进入收集器,而后者只在债务为正时才步进——所以上一轮回收留下的信用未还清之前,一步什么都不做;还清之后,一步能支付"债务 + 粒度"的工作量,因此 size == 0 在空堆上有余量跑完一轮(答 true),在大堆上答 false(此前一律答 true)。dosteps(2/10/100/20000) 实测 883/176/18/1,参考实现 968/194/20/1(差约 9%),顺序与 dosteps(20000) == 1 一致;setstepmul 的方向也一致(5000 → 875、50 → 893),只是像参考实现一样影响很小(约 1%)。剩余差异来自我们的"一轮工作量"估计(对象 + 字节/16)与参考的逐对象代价不完全同尺度,因此某些 step 布尔序列(大堆上连续两次 step 0 之后是否已跑完)与它不同。count 报告收集器测出的活集字节,并计入自上一轮以来库函数创建的对象,因此随分配上升、随回收下降;绝对数字不同,因为参考的数字是分配器自己的账。

    • 二进制 chunk 与参考实现不通用。 头部逐字节相同——签名、版本、格式、机器字长和两个测试常量——因为那决定了 chunk 是源码还是预编译、以及损坏时如何报错。其后的原型编码是本实现自己的,所以这里写出的 chunk 不能被 lua 读取,反之亦然。
    • 特殊浮点值的拼写 在 tostring 中固定为 nan、inf 和 -inf,而不跟随宿主 printf(各 C 库拼写不同)。string.format 的 %f、%g、%e、%a、%A 原样交给宿主格式化器,所以它们长成 C 库打印的样子:参考实现的 Windows 构建会打印与本实现相同的结果(-nan(ind)、0x1.0000000000000p+0),而链接另一个 C 库的构建会打印 nan 和 0x1p+0。
    • 有洞的表的长度可以是另一个边界。 手册把 #t 定义为任意满足 t[b] ~= nil 且 t[b+1] == nil 的 b,本解释器给出的数永远是其中之一。参考实现选哪一个,是其数组/散列划分的副产品(它的 rehash 会在两部分之间搬移整数键),所以 {1, nil, 3} 在那边是 3、这里是 1。建立在 # 之上的一切都会继承这点。真正的序列——手册所定义的情形——两者一致。
    • 无法取名的参数错误说 ?,与参考实现一致:名字来自调用点或对 package.loaded 的查找,绝不来自函数注册时用的名字。所以以值的形式拿到的文件方法 pcall(f.read, f, "x") 报 bad argument #2 to '?' (invalid format)。
    • 版本横幅是本实现自己的。 lua -v 打印 Lua 5.4 (MoonBit implementation),参考实现打印它的版权行。_VERSION 是 "Lua 5.4",只有读取横幅文本的程序才会看到区别。
    • 没有共享库加载器,所以 package.loadlib 的行为等同于一个未启用动态加载的 Lua 构建,原生搜索器在找到文件后会报告自己没有加载器。
    • 标识符接受非 ASCII 码点,这是本实现独有的扩展。 参考实现的 lislalpha 只认 ASCII(luai_ctype_ 表覆盖 0x00–0x7F),源码里任何 ≥0x80 的字节都进不了标识符,报 <name> expected near '<\228>'(utf8 库、字符串、注释与 os.setlocale 都改不了这一点:它不用 C 库的 isalpha)。这里一个合法且可见的 UTF-8 码点就算一个名字字符,所以 local 中 = 1、function 打招呼(谁) end、表.键、对象:加一()、::再来:: 都能写,名字可以是二字节(café)、三字节(汉字)、四字节(emoji)。约束有四条:只认 UTF-8(GBK 的 你 是 C4 E3,两个前导字节,仍然报 <name> expected);码点必须合法(截断序列、overlong、代理区、超过 U+10FFFF 都不算,退回 ASCII 读法);不可见的码点不算——BOM(U+FEFF)、零宽连接符与零宽空格、双向控制符、行分隔符、C1 控制符、U+_FFFE/U+_FFFF 这类非字符都不进名字,所以作为字符串交给 load 的 chunk 里那个 BOM 仍旧按参考实现报 unexpected symbol near '<\239>'(只有从文件读入的 chunk 才由 luaL_loadfile* 剥掉它);数字后面紧跟的非 ASCII 字符也会被数字吸收,报参考实现那种 malformed number near '100万',而不是把 100 和一个游离的名字拼在一起(ASCII 字母的旧行为逐字节不变)。合法程序的含义不受影响:真 Lua 里 ASCII 之外的字节出现在字符串/注释之外本来就是语法错误,因此这只把「原来报错的输入」变得可用(而且不会把原来报错的 BOM 悄悄变成合法标识符),load/require/文件名的行为不变。要参考实现那种严格性(比如做移植性检查),跑参考实现自己的 lua 即可——本实现没有关掉它的开关。词法热路径上 ASCII 名字只多一次比较,进程内 A/B(同一进程内用无名字的对照用例除以自身漂移)测得比值 0.431 → 0.429,在噪声之内。
    • 文件名按 UTF-8 交给宿主,因此能打开参考实现打不开的名字。 Windows 的文件名是 UTF-16,而 Lua 字符串是字节。这里在文件名是合法 UTF-8 时把它转成宽字符再调 _wfopen/_wremove/_wrename,于是源码里写 io.open("中文.txt")、dofile("脚本.lua")、require("模块") 都能打开真正的中文文件名;参考实现的 Windows 构建用窄字符 API,同样的代码会报 "No such file or directory"。不是合法 UTF-8 的名字原样交给窄字符 API(宿主自己的编码照旧可用——用 io.open 建出来的名字,loadfile 能用同一个名字找到它),所以这只会让原先打不开的名字能打开,不会让原先能打开的失效。名字一律以字节在内部传递、不再经过 MoonBit 的 String,因此不会被有损解码换成另一个名字。非 Windows 平台没有这层转换(那里的文件名本来就是字节)。
    • 性能比参考实现慢,倍数取决于在做什么。 tools/run_bench.mbtx 在本机度量:两边跑同一批用例、校验和必须一致,--repeat=N 决定每个用例重复几次(默认 3)并取最快一次——同一份二进制在两次运行之间的绝对值能差到 2 倍,所以只有比值可信,绝对值只能给区间。下面这组数字取 --repeat=5。现在的比值:协程与纯模式搜索约 1x(0.9–1.2x),分配密集的负载(table-small、string-build)3–7x,表操作 7–13x,字符串、算术与派发 12–30x(calls 最差)。与上一版背靠背(同一轮、同一台机器、取最快一次)相比,这一轮把算术循环加快了 2.2–4.7x(arith-float 4.7x)、calls 2.5x、表操作 1.1–1.6x,办法是把每次运算与每次调用里的堆分配去掉:Value 现在是 #valtype(宿主后端把它编成真正的 C 带标签联合,16 字节、不装箱,槽位读写不再分配),算术与比较直接读操作数而不再经过返回 Option 的辅助函数(Option 的载荷在原生后端会被装箱),一次普通返回不再为结果建临时数组(Results 把"值就在寄存器里"也表达出来),帧也不再为自己不会用到的两张表(保护与待关闭变量)分配空数组。随后一轮把 string.gsub 从最差的一项(25–36x)拉到 16x:替换文本直接写进结果缓冲(参考实现的 add_s 就是这个形状),不再为每次匹配建一个中间字符串,也不再在替换文本用不到捕获时先攒一个捕获数组——背靠背 A/B 是 2x;取子串则改成一次分配加一次 memcpy(此前经 Buffer 往返,要分配三次、拷贝两遍)。再往前一轮给表访问加了快速路径(参考实现 luaV_fastget/luaV_fastset 的形状):整数与字符串键按原样读写、不再先归一化成一个 Key,无元表的表直接写入(同一笔里不再先查一次键、也不再每次为表的大小记账)。数组部分的存与取因此快 1.6–3x(bench 的 table-array 从 ~16x 降到 7.5x),table.insert/remove 的搬移段快约 3.5x。最近一轮把内建调用的 ABI 换掉了——前面说的"参数数组"和"结果数组"两次分配就是它的形状:参数不再复制成一个数组(交给内建体的是寄存器窗口的 ArrayView,Frame 只多记一个参数个数),结果也不再为每次调用建数组(BuiltinResult 的 Nothing/One/Two 直接写回该帧自己的寄存器——参数原来占的地方,参考实现的 C 函数也是这么压结果的——只有多值才带列表)。一次内建调用因此快 39%(math.abs)、44%(next,两个结果)、14%(string.sub,三个参数),端到端在这些 bench 里是 0–10%(大半时间花在循环与字节码上,不在这类调用里)。剩下的差距仍然是结构性的,而且不在分配器上:后端是一次性 C 编译器,不内联也不做寄存器分配,所以每个辅助函数调用、每次槽位搬移都是真调用。
    • 宿主递归的深度上限由宿主还剩多少栈决定,而不是一个固定层数。 参考实现用固定层数(LUAI_MAXCCALLS = 200)挡住"经宿主回调的递归"(string.gsub 的替换函数、__index 里再调回来),它假设一层 C 层只花几百字节。这里一层要花约 5 KB——同样的后端原因——于是那个层数在 1 MB 的默认栈上刚好卡在边缘:cstack.lua 的元表用例会真把栈耗尽(不是报错,是段错误)。所以 call_value 在参考实现的层数(190)之外还检查宿主剩多少栈(MIN_HOST_STACK = 256 KB,由 stub.c 的 lua_mbt_stack_left 给出,Windows 读线程栈边界、POSIX 读 pthread_getattr_np/pthread_get_stackaddr_np),拒绝时给参考实现的消息 "C stack overflow"。代价是能递归的深度比参考实现浅(本机 1 MB 栈上约 140–190 层,参考实现约 197 层),并且随宿主栈与调用处的环境深度变化;参考实现自己的测试文件也说这个数字取决于 LUAI_MAXCCALLS 与为程序保留的栈。
    • 环不会被释放。 内存由宿主运行时的引用计数回收;收集器判定可达性(这正是弱表、ephemeron 和 __gc 需要的),但它不做清扫。因此一个环会留到进程结束。

    #测试

    moon test

    • tests/language.lua、tests/stdlib.lua、tests/require_test.lua、tests/examples.lua 和 tests/utf8_identifiers.lua 是由 src/lua/suite_test.mbt 通过解释器执行的 Lua 程序——和嵌入者使用的方式同形(黑盒),所以失败会带着出错的 Lua 行号报出来。前四个在参考实现下也通过;最后一个不会,它跑的正是上面那条标识符扩展(第 26 行 local 中 = 1 参考实现就拒绝),把它单独放一个文件就是为了让「一致性套件」与「扩展套件」互不污染。
    • 其余测试就放在它们所钉住的代码旁边:代码生成器产出的寄存器布局(src/compiler/codegen_wbtest.mbt)、printf 各转换、数字解析与名字字符的码点判定(src/core/number_wbtest.mbt)、chunk 前缀(BOM 与 # 首行)的剥离(src/load/load_test.mbt)、命令行的选项表、-l name=module 拆分与脚本 varargs(cmd/main/main_wbtest.mbt)、被启动的脚本看到的报错形态(src/lua/launcher_test.mbt)、以及宿主边界(src/host/ffi_wbtest.mbt)。
    • 官方 Lua 5.4 测试套件是一致性的裁判。它不在本仓库分发——tools/run_official_tests.mbtx 需要 lua-5.4.9-tests/ 下有一份拷贝;当前数字见上面 ## 状态。
    • 性能由 bench/ 与 tools/run_bench.mbtx 度量:每个用例自带断言,打印一行 bench <名字> <秒> <校验和>;传入第二个解释器即可得到比值,--repeat=N 决定每个用例重复几次(默认 3,取最快一次)。改动前后要背靠背跑、比较比值,不要与上一轮的旧数字比较。

    moon run --target native tools/run_bench.mbtx /path/to/reference/lua

    #许可证与来源

    Apache-2.0,见 LICENSE。NOTICE 载有随之而来的署名,因为这里实现的行为是 Lua 的,是在其 MIT 许可下从参考实现移植的(NOTICE 中的许可原文保持英文原样)。

    移植是依照以下来源写成的:

    • Lua 5.4.9(参考实现),一切可观察行为都以它为准:lparser.c/lcode.c(单遍编译器的形态与语法错误消息)、lvm.c/ldo.c(指令语义、保护调用与 yield 的排布、展开时关闭变量的顺序)、lgc.c(收集规则及其执行顺序)、lauxlib.c 与 l*baselib.c/lstrlib.c/ltablib.c/lmathlib.c/loslib.c/liolib.c/lcorolib.c/ldblib.c/lutf8lib.c(参数检查与消息),以及 lua.c/loadlib.c/luaconf.h(启动器、搜索路径与 package)。
    • Lua 5.4 参考手册,用于明确语言承诺——当手册与实现不一致时,以实现为准。
    • 官方测试套件,作为裁判(见 ## 测试)。
    • 在本机用上述源码构建的 Lua 5.4.9 二进制,用作差分对照:每一条被移植的行为,都是把同一个文件在两种实现下各跑一遍、比对整份日志得出的,而不是只读源码。

    HostFunction

    A function the host writes and Lua calls: the arguments in order, the values to answer with, or the error object to raise.

    Table

    using @hongweifei/lua/src/core { type LTable as Table }

    A Lua table, with the interpreter's own accessors (get_str, set_str, get_int, set_int, length, ...).

    Value

    A Lua value. Its cases are the interpreter's own (Value::VInt, Value::VStr, ...), and reading one with a coercion rule is what the methods below are for.

    FromLua

    pub trait FromLua {
    fn from_lua(
    Value
    ) -> Self?
    fn expected_and_got(
    Value
    ) -> (String,
    Value
    )
    }

    A value Lua has that a host wants as a MoonBit one. Implemented for the scalars, for Bytes, for Table and Value, for Option (a nil is None), for Array (a table read as a sequence) and for Map[String, T].
    impl FromLua for Bool
    impl FromLua for Int
    impl FromLua for Double
    impl FromLua for String
    impl FromLua for Option[T]
    impl FromLua for Bytes
    impl FromLua for Array[T]
    impl FromLua for Map[String, V]

    ToLua

    pub trait ToLua {
    fn to_lua(Self) ->
    Value

    }

    A value a host can hand to Lua. Implemented for the MoonBit scalars, for Bytes, for Table and Value themselves, for Option (None becomes nil), for Array (a sequence numbered from 1) and for Map.
    impl ToLua for Bool
    impl ToLua for Int
    impl ToLua for Int64
    impl ToLua for Double
    impl ToLua for String
    impl ToLua for Option[T]
    impl ToLua for Bytes
    impl ToLua for Array[T]
    impl ToLua for Map[K, V]

    Lua

    pub struct Lua {
    // private fields
    }

    A Lua state: the globals, the standard libraries and the threads a script makes. Two states share nothing.

    Lua::call

    Calls a value with arguments and answers with its results. Anything callable works: a function a chunk defined, a host function this layer installed, or a table with a __call.

    Lua::call_global

    fn Lua::call_global(self : Lua, name : String, args? : Array[
    Value
    ]) -> Result[Array[
    Value
    ], LuaError]

    Calls a global by name, which is how a script exports an entry point.

    test "calling a function a chunk defined" {
    let lua = Lua::new()
    let _ = lua.run("function double(x) return x * 2 end")
    let vs = lua.call_global("double", args=[Value::VInt(21L)]).unwrap()
    assert_eq(vs[0].as_integer(), Some(42L))
    }

    Lua::eval

    fn Lua::eval(self : Lua, source : String, args? : Array[
    Value
    ]) -> Result[
    Value
    , LuaError]

    Runs a chunk and answers with its first result, or nil when it answers with nothing at all.

    Lua::eval_as

    fn[T : FromLua] Lua::eval_as(self : Lua, source : String, args? : Array[
    Value
    ]) -> Result[T, LuaError]

    Runs a chunk and reads its first result as the type the host asked for. Shorthands for the common ones are eval_int, eval_number, eval_text, eval_bytes and eval_bool, which need no annotation.

    test "a chunk's first result, typed" {
    let lua = Lua::new()
    let rows : Result[Array[Int64], LuaError] = lua.eval_as("return {1, 2, 3}")
    assert_eq(rows.unwrap(), [1L, 2L, 3L])
    let not_a_number : Result[Int64, LuaError] = lua.eval_as("return nil")
    assert_eq(not_a_number.unwrap_err().message, "number expected, got nil")
    // `{}` is an empty table, not a missing value.
    let empty_table : Result[Int64, LuaError] = lua.eval_as("return {}")
    assert_eq(empty_table.unwrap_err().message, "number expected, got table")
    }

    Lua::eval_bool

    fn Lua::eval_bool(self : Lua, source : String, args? : Array[
    Value
    ]) -> Result[Bool, LuaError]

    Runs a chunk and answers with the truthiness of its first result, which is Lua's: only nil and false are not true, so 0 and "" are. Reading a boolean value is the strict one (Bool::from_lua); this is the question Lua itself asks of a condition.

    Lua::eval_bytes

    fn Lua::eval_bytes(self : Lua, source : String, args? : Array[
    Value
    ]) -> Result[Bytes, LuaError]

    Runs a chunk answering with a string. The bytes come back exactly, so a string holding non-UTF-8 data survives the trip.

    Lua::eval_int

    fn Lua::eval_int(self : Lua, source : String, args? : Array[
    Value
    ]) -> Result[Int64, LuaError]

    Runs a chunk answering with a number and reads the integer in it: an integer, a float holding one, or a string spelling one -- the rule math.tointeger uses, so a config file's "42" and its 42 both work. A name for eval_as[Int64], which a call site cannot write.

    Lua::eval_number

    fn Lua::eval_number(self : Lua, source : String, args? : Array[
    Value
    ]) -> Result[Double, LuaError]

    Runs a chunk answering with a number, as a float.

    Lua::eval_text

    fn Lua::eval_text(self : Lua, source : String, args? : Array[
    Value
    ]) -> Result[String, LuaError]

    Runs a chunk answering with text.

    Lua::get

    fn Lua::get(self : Lua, name : String) ->
    Value

    Reads a global. A name the script never set is Value::VNil, as in Lua.

    Lua::get_as

    fn[T : FromLua] Lua::get_as(self : Lua, name : String) -> Result[T, LuaError]

    Reads a global as the type the host asked for. The type comes from an annotation, since a call site cannot name it:

    test "reading a global as a MoonBit type" {
    let lua = Lua::new()
    let missing : Result[String, LuaError] = lua.get_as("非")
    assert_true(missing is Err(_))
    lua.set("问候", "你好")
    let got : Result[String, LuaError] = lua.get_as("问候")
    assert_eq(got.unwrap(), "你好")
    }

    Lua::globals

    The globals as a table: lua.globals().get_str("x") reads x, and writing to it is writing to the script's environment.

    Lua::load

    fn Lua::load(self : Lua, source : String, name? : String) -> Result[
    Value
    , LuaError]

    Compiles a chunk without running it, giving the value Lua::call takes. Nothing about it runs, which is what makes this the check-a-script-first entry point; a chunk that does not compile answers with the message load gives.

    Lua::load_file

    fn Lua::load_file(self : Lua, path : String) -> Result[
    Value
    , LuaError]

    Compiles a file as a chunk without running it, as loadfile does. A file that cannot be read answers Err, because loadfile answers nil, message rather than raising and that pair becomes the error here.

    Lua::new

    fn Lua::new(ignore_env? : Bool) -> Lua

    A state with every standard library open. ignore_env~ is the interpreter's own -E: package.path and package.cpath then come from the built-in defaults rather than from LUA_PATH and LUA_CPATH.

    Lua::preload

    Registers a host function as a module, so a script's require("名字") finds it: the function runs as the loader and answers with the module's value. This is package.preload under the name -- which also means a script can overwrite it, and package.loaded keeps the usual cache.

    test "a MoonBit module a script can require" {
    let lua = Lua::new()
    lua.preload("配置", fn(args) {
    let _ = args
    let t = new_table()
    t.set_str("上限", Value::VInt(42L))
    Ok([t.as_value()])
    })
    assert_eq(lua.eval_int("return require('配置').上限").unwrap(), 42L)
    }

    Lua::require

    fn Lua::require(self : Lua, name : String) -> Result[
    Value
    , LuaError]

    Loads a module the way require does, and answers with what it returned -- the table a module file ends with, or the value a loader handed back. The name goes through the searchers, so package.path, package.preload and package.loaded all apply, and a second call gets the cached module.

    test "require from the host" {
    let lua = Lua::new()
    lua.preload("配置", fn(args) {
    let _ = args
    let t = new_table()
    t.set_str("上限", Value::VInt(42L))
    Ok([t.as_value()])
    })
    let m = lua.require("配置").unwrap()
    assert_eq(m.type_name(), "table")
    // The loader ran once: `require` caches, so the two handles are one table.
    assert_true(m.raw_equal(lua.require("配置").unwrap()))
    }

    Lua::run

    fn Lua::run(self : Lua, source : String, name? : String, args? : Array[
    Value
    ]) -> Result[Array[
    Value
    ], LuaError]

    Runs a chunk and answers with its results, or with the error that escaped. A chunk is a vararg function, so args~ is what its ... sees.

    test "a chunk's results" {
    let lua = Lua::new()
    let vs = lua.run("return 1 + 2, 'x'").unwrap()
    assert_eq(vs[0].as_integer(), Some(3L))
    assert_eq(vs[1].as_text(), Some("x"))
    }

    Lua::run_file

    fn Lua::run_file(self : Lua, path : String, args? : Array[
    Value
    ]) -> Result[Array[
    Value
    ], LuaError]

    Runs a file as a chunk: the chunk is named after the file, and a UTF-8 byte order mark or a leading #! line is dropped the way the language drops them for a file. args~ are the chunk's varargs, which is what a script run as lua file.lua a b sees in ...; dofile itself passes none, so this loads first and then calls, as the interpreter's own launcher does.

    Lua::set

    fn[T : ToLua] Lua::set(self : Lua, name : String, v : T) -> Unit

    Writes a global, converting whatever the host has: set("limit", 3), set("name", "hi"), set("items", [1, 2, 3]), set("on", true).

    Lua::set_function

    Installs a host function as a global, which is how a script finds it: lua.set_function("load_config", ...) makes load_config() callable.

    Lua::show

    fn Lua::show(self : Lua, v :
    Value
    ) -> String

    The text of a value as Lua's tostring gives it, honouring a __tostring and reporting the reference's "(error object is a table value)" when the metamethod is missing or fails.

    Lua::state

    The state this handle drives, for the lower-level interface.

    Lua::value_as

    fn[T : FromLua] Lua::value_as(self : Lua, v :
    Value
    ) -> Result[T, LuaError]

    The kind of conversion FromLua does, with a failure reported as a LuaError naming what was asked for ("number expected, got string", the wording the libraries use in an argument error).

    test "reading one value" {
    let lua = Lua::new()
    let items : Result[Array[Int64], LuaError] = lua.value_as(
    lua.eval("return {7, 8, 9}").unwrap(),
    )
    assert_eq(items.unwrap(), [7L, 8L, 9L])
    let wrong : Result[Array[Int64], LuaError] = lua.value_as(
    lua.eval("return {7, 'x'}").unwrap(),
    )
    // A failure inside a table names the *entry*, not the table that held it.
    assert_eq(wrong.unwrap_err().message, "number expected, got string")
    }

    Lua::values_as

    fn[T : FromLua] Lua::values_as(self : Lua, vs : Array[
    Value
    ]) -> Result[Array[T], LuaError]

    Converts a whole result list, each value to the same type -- a chunk that answers return "a", "b", "c". This reads the list of results, not a Lua table; Array[T] in FromLua is the one that reads a table as a sequence.

    LuaError

    pub struct LuaError {
    value :
    Value

    message : String
    }

    Why a call did not succeed: a chunk that failed to compile, a Lua error that escaped, or a result that is not the kind the host asked for. The error object is kept as Lua made it, so a program that raises a table can be inspected field by field.
    impl Show for LuaError

    host_function

    A value holding a host function, which can go anywhere a Lua function can: a global, a table field, an argument to a call.

    test "a host closure called from Lua" {
    let lua = Lua::new()
    lua.set_function("长度", fn(args) {
    match args[0].as_bytes() {
    Some(b) => Ok([Value::VInt(b.length().to_int64())])
    None => Err(Value::text("string expected"))
    }
    })
    let vs = lua.run("return 长度('你好'), 长度('abc')").unwrap()
    assert_eq(vs[0].as_integer(), Some(6L))
    assert_eq(vs[1].as_integer(), Some(3L))
    // An `Err` raises, so the script sees an ordinary Lua error it can catch.
    let caught = lua.run("return select(2, pcall(长度, 1))").unwrap()
    assert_true(caught[0].as_text().unwrap_or("").contains("string expected"))
    }

    new_table

    A fresh, empty table for filling in from the host.

    read_lua

    fn[T : FromLua] read_lua(v :
    Value
    ) -> T?

    A value of a type the host picks, written so the type comes from the annotation: let items : Array[String]? = read_lua(v). The rules are the language's own, which is what this test is pinning.

    test "reading rules, in both directions" {
    let lua = Lua::new()
    // A string spelling a number reads as one, because `math.tointeger` does.
    let from_text : Int64? = read_lua(lua.eval("return '42'").unwrap())
    assert_eq(from_text, Some(42L))
    // A number does not read as text, though Lua's `tostring` would make one.
    let number_as_text : String? = read_lua(lua.eval("return 42").unwrap())
    assert_eq(number_as_text, None)
    assert_eq(lua.show(lua.eval("return 42").unwrap()), "42")
    // An integer too wide for MoonBit's `Int` is nothing rather than a wrap.
    let too_wide : Int? = read_lua(lua.eval("return math.maxinteger").unwrap())
    assert_eq(too_wide, None)
    let fits : Int? = read_lua(lua.eval("return 42").unwrap())
    assert_eq(fits, Some(42))
    // A `boolean` reads strictly; Lua's *truth* is `Lua::eval_bool`'s question.
    let zero_as_bool : Bool? = read_lua(lua.eval("return 0").unwrap())
    assert_eq(zero_as_bool, None)
    assert_eq(lua.eval_bool("return 0").unwrap(), true)
    // Compound types name themselves the same way.
    let items : Array[Int64]? = read_lua(lua.eval("return {7, 8}").unwrap())
    assert_eq(items, Some([7L, 8L]))
    let cfg : Map[String, Int64]? = read_lua(
    lua.eval("return {a = 1, b = 2}").unwrap(),
    )
    assert_eq(cfg, Some(Map([("a", 1L), ("b", 2L)])))
    // A table is a sequence only up to its first absent field.
    let holed : Array[Int64]? = read_lua(lua.eval("return {1, nil, 3}").unwrap())
    assert_eq(holed, Some([1L]))
    // A `nil` is `None`, and so is a wrong type -- `is_nil` tells them apart.
    let maybe : Int64? = read_lua(lua.eval("return nil").unwrap())
    assert_eq(maybe, None)
    }

    table_entries

    The fields of a table, in the order next gives them -- the same walk pairs makes over the table's own entries, without consulting a metatable.

    table_sequence

    A table read as a sequence of values, t[1] up to the first absent field. This is the Array[Value] of FromLua without the conversion, for a host that wants to look at each item itself.