diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..9d8feeb --- /dev/null +++ b/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 1994-2012 Lua.org, PUC-Rio (Lua 5.1, whose pattern matching and +table.sort algorithms this package follows) +Copyright (c) 2026, Waozi (Ziran implementation) + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +- The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. +- The Software is provided "as is", without warranty of any kind, express or + implied, including but not limited to the warranties of merchantability, + fitness for a particular purpose and noninfringement. In no event shall the + authors or copyright holders be liable for any claim, damages or other + liability, whether in an action of contract, tort or otherwise, arising from, + out of or in connection with the Software or the use or other dealings in the + Software. diff --git a/README.md b/README.md new file mode 100644 index 0000000..cae3946 --- /dev/null +++ b/README.md @@ -0,0 +1,62 @@ +# Lua + +Lua is a [Ziran](https://github.com/ziranlang/ziran) package that runs Lua +5.1 code in the LuaJIT dialect. Everything is written in Ziran, with no C +code and no native libraries: the lexer and parser, a compiler to register +bytecode, the interpreter, a mark-and-sweep collector with weak tables and +`__gc`, and the standard libraries. It was written so that +[Katalis](https://github.com/waozixyz/katalis) can run Luanti mods from +ContentDB. + +The embedding API follows the Lua C API: a stack, natives as plain Ziran +procedures, userdata with metatables, registry references, coroutines a +native can yield from, and limits on memory, call depth and instruction +count for running untrusted mods. File and environment access is off until +the host grants it. + +## Use it + +```sh +ziran add https://github.com/ziranlang/lua.git +``` + +```zi +#import "lua/vm" + +state: LuaState; + +Add :: (L: *LuaState) -> s32 { + a, ok1 := LuaCheckNumber(L, 1) + if !ok1 { return LUA_NATIVE_ERROR } + b, ok2 := LuaCheckNumber(L, 2) + if !ok2 { return LUA_NATIVE_ERROR } + LuaPushNumber(L, a + b) + return 1 +} + +Run :: () -> bool { + L := *state + LuaOpen(L) + LuaRegister(L, "add", Add) + status := LuaDoString(L, "print(add(1, 2))", "=example") + if status != LUA_OK { + message, ok := LuaToString(L, -1) + print("%\n", message) + } + LuaClose(L) + return status == LUA_OK +} +``` + +[docs/API.md](docs/API.md) describes the whole API and what each library +supports. + +## Check it + +```sh +make test +``` + +This runs the API unit tests, the Lua scripts in `tests/lua`, and loads +every `.lua` file of the Katalis mods (set `KATALIS_MODS` to another +folder; it is skipped when missing). diff --git a/docs/API.md b/docs/API.md new file mode 100644 index 0000000..9c7005e --- /dev/null +++ b/docs/API.md @@ -0,0 +1,269 @@ +# Lua VM embedding API + +`#import "lua/vm"` gives a Lua 5.1 virtual machine (LuaJIT dialect) written +in Ziran. The API follows the shape of the Lua C API: a host owns a +`LuaState` record, values move through a stack, and natives are plain Ziran +procedures. Names below are stable; records not listed here (`LuaTable`, +`LuaClosure` and the other object records exported with `LuaState`) are +internal and may change. + +## State + +```zi +state: LuaState +L := *state +LuaOpen(L) // false when the record was already open +status := LuaDoString(L, "print('hi')", "=demo") +if status != LUA_OK { message, ok := LuaToString(L, -1) } +LuaClose(L) // runs pending __gc and host finalizers, frees all +``` + +`LuaState` is large; keep it in a global or on the heap. One state is one +Lua universe and is not thread-safe. `LuaOpen` loads every standard library +(base, coroutine, string, table, math, os, io, bit, debug). + +| Procedure | Meaning | +| --- | --- | +| `LuaSetHost(L, host: *void)`, `LuaHost(L) -> *void` | A host pointer for natives and hooks. | +| `LuaSetPrintSink(L, sink: LuaPrintSink, context: *void)` | `print`, `io.write` and `io.stdout:write` go to `sink(context, text)` instead of standard output. | +| `LuaSetFileRoot(L, path)` | Lets `dofile`, `loadfile`, `io.open` and `io.lines` read files below `path`. Empty (the default) disables Lua-side file access. | +| `LuaAllowEnvironment(L, prefix)` | Lets `os.getenv` read variables whose names start with `prefix`; repeatable. Otherwise `os.getenv` returns nil. | +| `LuaCollectGarbage(L)` | A full collection, from the host or a native (skipped inside a hook). | +| `LuaMemoryUsed(L) -> s64` | Estimated live heap bytes. | + +## Status codes and constants + +`LUA_OK`, `LUA_YIELD`, `LUA_ERRRUN`, `LUA_ERRSYNTAX`, `LUA_ERRMEM`, +`LUA_ERRERR`, `LUA_ERRFILE`. `LUA_MULTRET` (-1) asks for all results. + +Pseudo-indices: `LUA_REGISTRYINDEX`, `LUA_GLOBALSINDEX` (the running +thread's globals), `LUA_ENVIRONINDEX` (the running native's environment) and +`LuaUpvalueIndex(i)` for native closure upvalues. + +Type codes from `LuaType`: `LUA_TYPE_NONE` (-1, invalid index), `LUA_TYPE_NIL`, +`LUA_TYPE_BOOLEAN`, `LUA_TYPE_LIGHTUSERDATA`, `LUA_TYPE_NUMBER`, +`LUA_TYPE_STRING`, `LUA_TYPE_TABLE`, `LUA_TYPE_FUNCTION`, `LUA_TYPE_USERDATA`, +`LUA_TYPE_THREAD`. `LuaTypeName(L, type)` gives the Lua name. + +## The stack + +Index 1 is the first argument of the running native (or the first value the +host pushed), -1 the top. Reading an index past the top gives nil. + +| Procedure | Meaning | +| --- | --- | +| `LuaGetTop(L) -> s32` | Number of values. | +| `LuaSetTop(L, index)` | Grow with nils or drop values; `LuaSetTop(L, 0)` clears. | +| `LuaPop(L, n)` | Drop `n` values. | +| `LuaPushValue(L, index)` | Push a copy. | +| `LuaInsert(L, index)` | Move the top value into `index`, shifting up. | +| `LuaRemove(L, index)` | Remove, shifting down. | +| `LuaReplace(L, index)` | Pop the top value into `index`; works with upvalue and global pseudo-indices. | +| `LuaAbsIndex(L, index) -> s32` | A positive index for a relative one. | +| `LuaCheckStack(L, extra) -> bool` | Ensure room for `extra` more values. | + +## Values + +Push: `LuaPushNil`, `LuaPushBoolean(L, bool)`, `LuaPushNumber(L, float64)`, +`LuaPushInteger(L, s64)`, `LuaPushString(L, string)` (copied and interned), +`LuaPushLightUserdata(L, *void)`, `LuaPushNative(L, fn, name)`, +`LuaPushNativeClosure(L, fn, count, name)`, `LuaPushThreadValue(L) -> bool` +(true on the main thread). + +Read: `LuaToNumber -> float64` (0 when not convertible), +`LuaToNumberChecked -> (value, ok)`, `LuaToInteger -> s64` (truncated, +saturated), `LuaToBoolean`, `LuaToString -> (text, ok)`, `LuaToUserdata -> +*void`, `LuaUserdataTag -> s64`, `LuaObjLen -> s64` (raw table +length, string length, the length of a number as text, else 0). + +`LuaToString` converts a number in place to a string, as `lua_tolstring` +does. The returned text views interned VM memory: copy it before the value +can be collected (after it leaves the stack and Lua code runs). + +Tests: `LuaIsNone`, `LuaIsNil`, `LuaIsNoneOrNil`, `LuaIsBoolean`, +`LuaIsNumber` (numbers and numeric strings), `LuaIsString` (strings and +numbers), `LuaIsTable`, `LuaIsFunction`, `LuaIsNative`, `LuaIsUserdata` +(full or light). Comparison: `LuaRawEqual(L, a, b) -> bool`, +`LuaEqual(L, a, b) -> (equal, ok)` and `LuaLessThan(L, a, b) -> (less, ok)` +run metamethods. + +## Tables + +| Procedure | Meaning | +| --- | --- | +| `LuaNewTable(L)`, `LuaCreateTable(L, narr, nrec)` | Push a new table, optionally presized. | +| `LuaGetField(L, index, name) -> bool` | Push `t[name]` (metamethods). | +| `LuaSetField(L, index, name) -> bool` | `t[name] = pop()` (metamethods). | +| `LuaGetTable(L, index) -> bool` | Pop a key, push `t[key]`. | +| `LuaSetTable(L, index) -> bool` | Pop value and key, `t[key] = value`. | +| `LuaGetGlobal(L, name)`, `LuaSetGlobal(L, name)` | The same on the globals. | +| `LuaRawGet(L, index)`, `LuaRawSet(L, index) -> bool` | Without metamethods; `LuaRawSet` is false for a nil or NaN key. | +| `LuaRawGetI(L, index, n)`, `LuaRawSetI(L, index, n)` | Integer keys, raw. | +| `LuaNext(L, index) -> s32` | Pop a key, push the next key and value: 1, or 0 at the end, or -1 for an invalid key. | + +Iterate like the C API: + +```zi +LuaPushNil(L) +while LuaNext(L, table) == 1 { + // key at -2, value at -1 + LuaPop(L, 1) +} +``` + +The bool results are false when a metamethod raised an error. Inside a +native, return `LUA_NATIVE_ERROR` then; from the host, wrap the work in a +native and call it with `LuaPCall` when metamethods can fail. + +## Metatables, userdata and environments + +| Procedure | Meaning | +| --- | --- | +| `LuaGetMetatable(L, index) -> bool` | Push the metatable; false (nothing pushed) without one. | +| `LuaSetMetatable(L, index) -> bool` | Pop a table or nil into the value's metatable (tables, userdata, or the shared one of a basic type). | +| `LuaNewMetatable(L, name) -> bool` | Push `registry[name]`, creating it; false when it existed. | +| `LuaGetRegistryMetatable(L, name)` | Push `registry[name]`. | +| `LuaNewUserdata(L, data: *void, tag: s64)` | Push a full userdata wrapping host data; `tag` names the host type. | +| `LuaNewUserdataFinalized(L, data, tag, finalizer: LuaFinalizer)` | The same; `finalizer(L, data, tag)` runs when it is collected or the state closes, after any `__gc`. | +| `LuaTestUserdata(L, index, name) -> *void` | The data of a userdata whose metatable is `registry[name]`, else null. | +| `LuaGetFenv(L, index)`, `LuaSetFenv(L, index) -> bool` | A function's, userdata's or thread's environment table. | + +The VM never owns host data: a userdata holds the pointer, and the host +frees it in the finalizer. + +## Natives + +```zi +LuaNative :: #type (L: *LuaState) -> s32; +``` + +A native reads its arguments at 1..`LuaGetTop(L)`, pushes results and +returns how many (the top values are taken). It returns `LUA_NATIVE_ERROR` +to raise the pending error, or `LuaYield(L, n)` to yield. + +```zi +Add :: (L: *LuaState) -> s32 { + a, ok1 := LuaCheckNumber(L, 1) + if !ok1 { return LUA_NATIVE_ERROR } + b, ok2 := LuaCheckNumber(L, 2) + if !ok2 { return LUA_NATIVE_ERROR } + LuaPushNumber(L, a + b) + return 1 +} + +LuaRegister(L, "add", Add) // globals.add +LuaNewTable(L) +LuaSetNative(L, -1, "add", Add) // t.add +LuaSetGlobal(L, "host") +``` + +Argument checks set the standard error and return `ok = false`: +`LuaCheckNumber`, `LuaCheckInteger`, `LuaCheckString` (numbers convert), +`LuaCheckTable -> bool`, `LuaCheckAny -> bool`, and `LuaOptNumber`, +`LuaOptInteger`, `LuaOptString` with a fallback for nil or missing. + +Raising errors (each returns `LUA_NATIVE_ERROR`): + +- `LuaErrorText(L, message)`: "chunk:line: message" at the Lua caller. +- `LuaArgError(L, n, message)`: "bad argument #n to 'name' (message)". +- `LuaTypeError(L, n, expected)`: "... (expected expected, got type)". +- `LuaRaiseError(L)`: raise the value on top of the stack as is. + +`LuaPushNativeClosure(L, fn, count, name)` takes the top `count` values as +upvalues; read them with `LuaPushValue(L, LuaUpvalueIndex(i))` and write them +with `LuaReplace(L, LuaUpvalueIndex(i))`. + +## Loading and calling + +| Procedure | Meaning | +| --- | --- | +| `LuaLoadBuffer(L, text, chunkname) -> s32` | Compile and push a function, or push the message (`LUA_ERRSYNTAX`). | +| `LuaLoadString(L, text) -> s32` | `LuaLoadBuffer` with the text as its name. | +| `LuaLoadFile(L, path) -> s32` | Load a host file (not limited by the file root); `LUA_ERRFILE` when unreadable. | +| `LuaDoString(L, text, chunkname) -> s32` | Load and run with a traceback handler; results stay on the stack. | +| `LuaDoFile(L, path) -> s32` | The same for a host file. | +| `LuaCall(L, nargs, want) -> bool` | Unprotected call of the function below `nargs` arguments. Inside a native, return `LUA_NATIVE_ERROR` when false. | +| `LuaPCall(L, nargs, want, handler) -> s32` | Protected call; `handler` is a stack index of a message handler or 0. On error the message replaces the function and arguments. | +| `LuaTraceback(L, message, level)` | Push "message\nstack traceback:\n...". | + +Chunk names follow Lua: "@file.lua" prints as `file.lua:3:`, "=name" as +`name:3:`, anything else as `[string "..."]:3:`. Lua errors carry a +position; `error(value)` with a non-string keeps the value as is. + +Call `LuaPCall` or `LuaDoString` from the host. A host call outside any +protected call leaves its error pending with no handler to receive it. + +## Registry references + +`LuaRef(L) -> s32` pops a value into the registry and returns a handle +(`LUA_REFNIL` for nil); `LuaPushRef(L, ref)` pushes it back; `LuaUnref(L, +ref)` releases it. A referenced value stays alive. + +## Coroutines + +`LuaNewThread(L)` pops a function and pushes a coroutine running it. +`LuaResume(L, index, nargs) -> (status, count)` resumes the coroutine at +`index` with the top `nargs` values; its yielded or returned values (or the +error message) replace them. The status is `LUA_YIELD`, `LUA_OK` (finished) +or an error. + +A native yields with `return LuaYield(L, n)`, yielding its top `n` values; +the values passed to the next resume become that native call's results. + +```zi +Wait :: (L: *LuaState) -> s32 { return LuaYield(L, LuaGetTop(L)) } +``` + +As in Lua 5.1, yielding across a `pcall`, a metamethod or a native that +called back into Lua raises "attempt to yield across metamethod/C-call +boundary". + +## Limits and hooks + +```zi +LuaLimits :: struct { + max_memory: s64 // estimated live bytes; 0 = unlimited + max_native_depth: s32 // nested native re-entry (default 190) + max_frames: s32 // Lua call frames per thread (default 200000) +} +limits := LuaGetLimits(L) +limits.max_memory = 64 * 1048576 +LuaSetLimits(L, limits) +``` + +Going over `max_memory` raises "not enough memory" in the running Lua code +after a collection fails to free enough. Deep recursion raises "stack +overflow". + +`LuaSetHook(L, hook: LuaHook, count)` calls `hook(L) -> bool` every `count` +checkpoints (Lua calls and loop back-edges). Returning false raises an error +in the running Lua code: "instruction limit exceeded", or the message set +with `LuaSetHookMessage(L, message)` inside the hook. `LuaClearHook(L)` +removes it. Use it to stop runaway mod code. + +## Supported Lua + +Lua 5.1 semantics with LuaJIT's extensions: `goto` and labels, `\x`, `\z` +and `\u{...}` escapes, `bit`, `math.log(x, base)`, `string.format("%a")`, `load` with a +reader function, `newproxy`. + +- Base: `assert collectgarbage dofile error gcinfo getfenv getmetatable ipairs + load loadfile loadstring newproxy next pairs pcall print rawequal rawget + rawset require select setfenv setmetatable tonumber tostring type unpack + xpcall _G _VERSION`. `require` resolves through `package.loaded` and + `package.preload` only. +- `coroutine`: `create resume yield status running wrap`. +- `string`: `byte char dump find format gfind gmatch gsub len lower match rep + reverse sub upper`, with Lua patterns, and strings indexable as + `("x"):upper()`. `string.dump` raises an error. +- `table`: `concat foreach foreachi getn insert maxn remove setn sort`. +- `math`: all of Lua 5.1, plus `math.mod`. +- `bit`: `tobit tohex bnot band bor bxor lshift rshift arshift rol ror bswap`. +- `os`: `clock date difftime getenv time`. No `execute`, `exit`, `remove`, + `rename` or `tmpname`. +- `io`: `write`, `read` (always nil), `open` and `lines` (read-only below the + file root), `type`, `stdout`, `stderr`. Files support `read lines seek + close`. +- `debug`: `traceback getinfo getlocal setlocal getupvalue setupvalue + getmetatable setmetatable getregistry getfenv setfenv`; `sethook` and + `gethook` accept calls but install nothing. diff --git a/src/api.zi b/src/api.zi index 3f78f1f..80744ae 100644 --- a/src/api.zi +++ b/src/api.zi @@ -424,7 +424,10 @@ LuaClose :: (L: *LuaState) { L.open = false } -LuaSetLimits :: (L: *LuaState, limits: LuaLimits) { L.limits = limits } +LuaSetLimits :: (L: *LuaState, limits: LuaLimits) { + L.limits = limits + ClampThreshold(L) +} LuaGetLimits :: (L: *LuaState) -> LuaLimits { return L.limits } // Call `hook` every `count` checkpoints (Lua calls and loop back-edges). @@ -539,9 +542,10 @@ LuaInsert :: (L: *LuaState, index: s32) { L.threads[th].stack[position] = v } +// Move the top value into `index` (resolved before the pop, as in C). LuaReplace :: (L: *LuaState, index: s32) { - v := PopValue(L) - SetIndexValue(L, index, v) + SetIndexValue(L, index, IndexValue(L, -1)) + L.threads[L.cur].top -= 1 } // ---------------------------------------------------------------- reading diff --git a/src/gc.zi b/src/gc.zi index 851908b..a83ab01 100644 --- a/src/gc.zi +++ b/src/gc.zi @@ -401,6 +401,7 @@ CollectGarbage :: (L: *LuaState) { L.allocated = size L.threshold = size * 2 if L.threshold < 1048576 { L.threshold = 1048576 } + ClampThreshold(L) L.collecting = false RunFinalizers(L) } @@ -431,3 +432,9 @@ RunFinalizers :: (L: *LuaState) { } L.collecting = false } + +// With a memory limit, collect no later than at the limit so the check in +// GCStep sees every overshoot. +ClampThreshold :: (L: *LuaState) #inline { + if L.limits.max_memory > 0 && L.threshold > L.limits.max_memory { L.threshold = L.limits.max_memory } +} diff --git a/src/lexer.zi b/src/lexer.zi index 469ffe0..359555a 100644 --- a/src/lexer.zi +++ b/src/lexer.zi @@ -216,6 +216,9 @@ ReadString :: (lx: *Lexer, quote: u8) -> bool { LexError(lx, "invalid escape sequence", false) return false } + } else if e == #char "u" { + // LuaJIT 2.1: \u{XXX} as UTF-8. + if !ReadUnicodeEscape(lx) { LexError(lx, "invalid escape sequence", false); return false } } else if e == #char "z" { // LuaJIT: skip following whitespace. lx.pos += 1 @@ -245,6 +248,38 @@ ReadString :: (lx: *Lexer, quote: u8) -> bool { return false } +// At the "u" of \u{XXX}: append the code point (below 0x110000) as UTF-8. +ReadUnicodeEscape :: (lx: *Lexer) -> bool { + if lx.pos + 1 >= lx.src.count || lx.src[lx.pos + 1] != #char "{" { return false } + lx.pos += 2 + code: s64 = 0 + digits := 0 + while !AtEnd(lx) && IsXDigit(lx.src[lx.pos]) { + code = code * 16 + cast(s64) HexDigitValue(lx.src[lx.pos]) + if code >= 0x110000 { return false } + lx.pos += 1 + digits += 1 + } + if digits == 0 || AtEnd(lx) || lx.src[lx.pos] != #char "}" { return false } + lx.pos += 1 + if code < 0x80 { + VecPush(lx.buf, cast(u8) code) + } else if code < 0x800 { + VecPush(lx.buf, cast(u8)(0xC0 | (code >> 6))) + VecPush(lx.buf, cast(u8)(0x80 | (code & 0x3F))) + } else if code < 0x10000 { + VecPush(lx.buf, cast(u8)(0xE0 | (code >> 12))) + VecPush(lx.buf, cast(u8)(0x80 | ((code >> 6) & 0x3F))) + VecPush(lx.buf, cast(u8)(0x80 | (code & 0x3F))) + } else { + VecPush(lx.buf, cast(u8)(0xF0 | (code >> 18))) + VecPush(lx.buf, cast(u8)(0x80 | ((code >> 12) & 0x3F))) + VecPush(lx.buf, cast(u8)(0x80 | ((code >> 6) & 0x3F))) + VecPush(lx.buf, cast(u8)(0x80 | (code & 0x3F))) + } + return true +} + HexDigitValue :: (c: u8) -> s32 { if c >= #char "0" && c <= #char "9" { return cast(s32)(c - #char "0") } if c >= #char "a" && c <= #char "f" { return cast(s32)(c - #char "a") + 10 } diff --git a/tests/lua/strings.lua b/tests/lua/strings.lua index 0f14a4d..4d7b49e 100644 --- a/tests/lua/strings.lua +++ b/tests/lua/strings.lua @@ -108,4 +108,7 @@ assert(#tostring(12345.678) == 9) local z = "a\0b" assert(#z == 3 and z:byte(2) == 0 and z:sub(3) == "b" and z .. "c" == "a\0bc") assert(("x\0y"):find("\0", 1, true) == 2 and ("x\0y"):gsub("%z", "-") == "x-y") +-- LuaJIT 2.1 \u{XXX} escapes encode UTF-8. +assert("\u{41}\u{e9}\u{20AC}\u{1F600}" == "A\195\169\226\130\172\240\159\152\128") +assert(not loadstring("return \"\\u{110000}\"") and not loadstring("return \"\\u41\"")) print("strings ok") diff --git a/tests/vm_test.zi b/tests/vm_test.zi index aadb762..f6c9fcc 100644 --- a/tests/vm_test.zi +++ b/tests/vm_test.zi @@ -1,26 +1,419 @@ -// Runs Lua snippets through the embedding API; each must finish without error. +// Unit tests of the embedding API: values, tables, natives, userdata, +// errors, refs, limits and coroutines driven from the host. #import "vec" #import "vm" -Check :: (L: *LuaState, name: string, source: string) -> bool { +TestContext :: struct { + finalized: s64 + hook_calls: s64 + output: Vec(u8) +} + +Point :: struct { + x: float64 + y: float64 +} + +POINT_TAG :: 7; + +failures: s64 = 0; + +Expect :: (condition: bool, what: string) { + if condition { return } + print("FAIL %\n", what) + failures += 1 +} + +Contains :: (text: string, part: string) -> bool { + if part.count == 0 { return true } + i: s64 = 0 + while i + part.count <= text.count { + j: s64 = 0 + while j < part.count && text[i + j] == part[j] { j += 1 } + if j == part.count { return true } + i += 1 + } + return false +} + +TopText :: (L: *LuaState) -> string { + text, ok := LuaToString(L, -1) + if !ok { return "" } + return text +} + +// Run a chunk that must succeed; leaves nothing on the stack. +Run :: (L: *LuaState, name: string, source: string) { status := LuaDoString(L, source, name) - if status != LUA_OK { - message, ok := LuaToString(L, -1) - print("FAIL %: %\n", name, message) - LuaSetTop(L, 0) - return false + if status != LUA_OK { print("FAIL %: %\n", name, TopText(L)); failures += 1 } + LuaSetTop(L, 0) +} + +// Run a chunk that must fail with a message containing `part`. +RunFails :: (L: *LuaState, name: string, source: string, part: string) { + status := LuaDoString(L, source, name) + message := ifx status == LUA_OK then "" else TopText(L) + if status == LUA_OK || !Contains(message, part) { + print("FAIL %: expected an error containing '%', got status % '%'\n", name, part, status, message) + failures += 1 } LuaSetTop(L, 0) - return true +} + +// ---------------------------------------------------------------- natives + +Add :: (L: *LuaState) -> s32 { + a, ok1 := LuaCheckNumber(L, 1) + if !ok1 { return LUA_NATIVE_ERROR } + b, ok2 := LuaCheckNumber(L, 2) + if !ok2 { return LUA_NATIVE_ERROR } + LuaPushNumber(L, a + b) + return 1 +} + +// Returns its arguments in reverse order. +Reverse :: (L: *LuaState) -> s32 { + n := LuaGetTop(L) + i := n + while i >= 1 { LuaPushValue(L, i); i -= 1 } + return n +} + +// A native closure counting its calls in upvalue 1. +Counter :: (L: *LuaState) -> s32 { + n := LuaToInteger(L, LuaUpvalueIndex(1)) + 1 + LuaPushInteger(L, n) + LuaPushValue(L, -1) + LuaReplace(L, LuaUpvalueIndex(1)) + return 1 +} + +Fail :: (L: *LuaState) -> s32 { + return LuaErrorText(L, "host refused") +} + +// Calls its first argument in protected mode and returns status, message. +Protect :: (L: *LuaState) -> s32 { + LuaPushValue(L, 1) + status := LuaPCall(L, 0, 1, 0) + LuaPushBoolean(L, status == LUA_OK) + LuaInsert(L, -2) + return 2 +} + +Wait :: (L: *LuaState) -> s32 { + return LuaYield(L, LuaGetTop(L)) +} + +Handler :: (L: *LuaState) -> s32 { + message, ok := LuaToString(L, 1) + text: Vec(u8) + BuilderAppend(text, "handled: ") + BuilderAppend(text, message) + LuaPushString(L, TextView(VecSlice(text, 0, text.count))) + VecFree(text) + return 1 +} + +Capture :: (context: *void, text: string) { + test := cast(*TestContext) context + BuilderAppend(test.output, text) +} + +PointCoordinate :: (L: *LuaState, axis: s32) -> s32 { + data := LuaTestUserdata(L, 1, "Point") + if data == null { return LuaTypeError(L, 1, "Point") } + p := cast(*Point) data + LuaPushNumber(L, ifx axis == 0 then p.x else p.y) + return 1 +} + +PointX :: (L: *LuaState) -> s32 { return PointCoordinate(L, 0) } +PointY :: (L: *LuaState) -> s32 { return PointCoordinate(L, 1) } + +FinalizePoint :: (L: *LuaState, data: *void, tag: s64) { + test := cast(*TestContext) LuaHost(L) + if tag == POINT_TAG { test.finalized += 1 } +} + +StopAfterFive :: (L: *LuaState) -> bool { + test := cast(*TestContext) LuaHost(L) + test.hook_calls += 1 + if test.hook_calls < 5 { return true } + LuaSetHookMessage(L, "time is up") + return false +} + +StopNow :: (L: *LuaState) -> bool { return false } + +// ---------------------------------------------------------------- tests + +TestValues :: (L: *LuaState) { + LuaPushNil(L) + LuaPushBoolean(L, true) + LuaPushNumber(L, 2.5) + LuaPushInteger(L, 42) + LuaPushString(L, "hi") + Expect(LuaGetTop(L) == 5, "five values pushed") + Expect(LuaType(L, 1) == LUA_TYPE_NIL && LuaType(L, 2) == LUA_TYPE_BOOLEAN, "nil and boolean types") + Expect(LuaType(L, 3) == LUA_TYPE_NUMBER && LuaType(L, -1) == LUA_TYPE_STRING, "number and string types") + Expect(LuaType(L, 9) == LUA_TYPE_NONE && LuaIsNoneOrNil(L, 9), "missing index is none") + Expect(LuaTypeName(L, LuaType(L, -1)) == "string", "type name") + Expect(LuaToBoolean(L, 2) && !LuaToBoolean(L, 1), "truthiness") + Expect(LuaToNumber(L, 3) == 2.5 && LuaToInteger(L, 4) == 42, "numbers read back") + Expect(TopText(L) == "hi", "string reads back") + text, ok := LuaToString(L, 4) + Expect(ok && text == "42", "number converts to string") + Expect(!LuaIsString(L, 2) && LuaIsNumber(L, 4) && LuaIsString(L, 4), "string and number checks") + + // Stack shuffling: [nil true 2.5 42 "hi"]. + LuaInsert(L, 1) + Expect(LuaToInteger(L, -1) == 42 && TopText(L) == "42", "insert moves the top down (ToString converted it in place)") + Expect(LuaType(L, 1) == LUA_TYPE_STRING, "inserted at the bottom") + LuaRemove(L, 1) + LuaPushString(L, "x") + LuaReplace(L, -2) + Expect(LuaGetTop(L) == 4 && TopText(L) == "x", "replace overwrites below the top") + Expect(LuaToNumber(L, 3) == 2.5, "replace leaves other slots") + LuaPop(L, 2) + Expect(LuaGetTop(L) == 2, "pop") + LuaSetTop(L, 0) + + LuaPushString(L, "from host") + LuaSetGlobal(L, "greeting") + Run(L, "=values", "assert(greeting == 'from host') answer = 6 * 7") + LuaGetGlobal(L, "answer") + Expect(LuaToInteger(L, -1) == 42, "global set from Lua") + LuaSetTop(L, 0) +} + +TestTables :: (L: *LuaState) { + LuaNewTable(L) + LuaPushNumber(L, 5) + LuaSetField(L, -2, "five") + LuaPushString(L, "one") + LuaRawSetI(L, -2, 1) + LuaPushString(L, "two") + LuaRawSetI(L, -2, 2) + LuaPushString(L, "key") + LuaPushBoolean(L, true) + LuaSetTable(L, -3) + Expect(LuaObjLen(L, -1) == 2, "table length") + LuaGetField(L, -1, "five") + Expect(LuaToNumber(L, -1) == 5.0, "get field") + LuaPop(L, 1) + LuaRawGetI(L, -1, 2) + Expect(TopText(L) == "two", "raw get index") + LuaPop(L, 1) + LuaPushString(L, "key") + LuaRawGet(L, -2) + Expect(LuaToBoolean(L, -1), "raw get key") + LuaPop(L, 1) + pairs := 0 + LuaPushNil(L) + while LuaNext(L, -2) == 1 { + pairs += 1 + LuaPop(L, 1) + } + Expect(pairs == 4, "next visits every pair") + LuaSetGlobal(L, "config") + Run(L, "=tables", "assert(config.five == 5 and config[1] == 'one' and config.key == true)") + + // __index through the API. + Run(L, "=meta", "proxy = setmetatable({}, {__index = function(t, k) return k .. '!' end})") + LuaGetGlobal(L, "proxy") + LuaGetField(L, -1, "hey") + Expect(TopText(L) == "hey!", "get field honours __index") + LuaSetTop(L, 0) +} + +TestNatives :: (L: *LuaState) { + LuaRegister(L, "add", Add) + LuaRegister(L, "reverse", Reverse) + LuaRegister(L, "fail", Fail) + LuaRegister(L, "protect", Protect) + LuaPushInteger(L, 0) + LuaPushNativeClosure(L, Counter, 1, "counter") + LuaSetGlobal(L, "counter") + LuaNewTable(L) + LuaSetNative(L, -1, "add", Add) + LuaSetGlobal(L, "host") + Run(L, "=natives", "assert(add(2, 3) == 5 and host.add('1', 1) == 2) local a, b, c = reverse(1, 2, 3) assert(a == 3 and b == 2 and c == 1)") + Run(L, "=closure", "counter() counter() assert(counter() == 3)") + RunFails(L, "=argerror", "return add(1, {})", "bad argument #2 to 'add' (number expected, got table)") + RunFails(L, "=errortext", "fail()", "errortext:1: host refused") + Run(L, "=protect", "local ok, message = protect(function() error('inner') end) assert(not ok and message:find('inner'))") + + // LuaPCall with a handler, from the host. + LuaPushNative(L, Handler, "handler") + LuaGetGlobal(L, "fail") + status := LuaPCall(L, 0, 0, 1) + Expect(status == LUA_ERRRUN && Contains(TopText(L), "handled: ") && Contains(TopText(L), "host refused"), "pcall handler sees the error") + LuaSetTop(L, 0) + + // LuaCall from the host leaves results. + LuaGetGlobal(L, "add") + LuaPushNumber(L, 40) + LuaPushNumber(L, 2) + Expect(LuaCall(L, 2, 1) && LuaToNumber(L, -1) == 42.0, "call returns a result") + LuaSetTop(L, 0) +} + +TestErrors :: (L: *LuaState) { + RunFails(L, "=boom", "local function f() error('boom') end f()", "boom:1: boom") + RunFails(L, "=boom", "local function f() error('boom') end f()", "stack traceback:") + RunFails(L, "=syntax", "local = 1", "syntax:1:") + RunFails(L, "=index", "local t = nil; return t.x", "attempt to index local 't' (a nil value)") + status := LuaLoadBuffer(L, "return ...", "=load") + Expect(status == LUA_OK && LuaIsFunction(L, -1), "load pushes a function") + LuaPushInteger(L, 9) + Expect(LuaPCall(L, 1, 1, 0) == LUA_OK && LuaToInteger(L, -1) == 9, "chunk receives varargs") + LuaSetTop(L, 0) + status = LuaLoadBuffer(L, "return +", "=bad") + Expect(status == LUA_ERRSYNTAX && Contains(TopText(L), "bad:1:"), "syntax error status") + LuaSetTop(L, 0) +} + +TestUserdata :: (L: *LuaState, test: *TestContext) { + Expect(LuaNewMetatable(L, "Point"), "new metatable") + LuaNewTable(L) + LuaSetNative(L, -1, "x", PointX) + LuaSetNative(L, -1, "y", PointY) + LuaSetField(L, -2, "__index") + LuaPop(L, 1) + Expect(!LuaNewMetatable(L, "Point"), "metatable exists") + LuaPop(L, 1) + + p: Point + p.x = 3.0 + p.y = 4.0 + LuaNewUserdataFinalized(L, cast(*void) *p, POINT_TAG, FinalizePoint) + LuaGetRegistryMetatable(L, "Point") + Expect(LuaSetMetatable(L, -2), "set metatable") + Expect(LuaIsUserdata(L, -1) && LuaUserdataTag(L, -1) == POINT_TAG, "userdata tag") + Expect(LuaToUserdata(L, -1) == cast(*void) *p, "userdata data") + Expect(LuaTestUserdata(L, -1, "Point") == cast(*void) *p, "test userdata") + LuaSetGlobal(L, "p") + Run(L, "=point", "assert(p:x() == 3 and p:y() == 4 and type(p) == 'userdata')") + RunFails(L, "=point", "return p.x({})", "Point expected, got table") + Run(L, "=point", "p = nil collectgarbage()") + Expect(test.finalized == 1, "finalizer ran on collection") + + // A second one is finalized when the state closes (checked by Main). + q: Point + LuaNewUserdataFinalized(L, cast(*void) *q, POINT_TAG, FinalizePoint) + LuaSetGlobal(L, "q") +} + +TestRefs :: (L: *LuaState) { + Run(L, "=ref", "function double(a) return a * 2 end") + LuaGetGlobal(L, "double") + ref := LuaRef(L) + Expect(ref > 0 && LuaGetTop(L) == 0, "ref pops the value") + Run(L, "=ref", "double = nil collectgarbage()") + LuaPushRef(L, ref) + LuaPushNumber(L, 21) + Expect(LuaPCall(L, 1, 1, 0) == LUA_OK && LuaToNumber(L, -1) == 42.0, "ref keeps the function alive") + LuaSetTop(L, 0) + LuaUnref(L, ref) + LuaPushNil(L) + Expect(LuaRef(L) == LUA_REFNIL, "nil ref") +} + +TestEnvironment :: (L: *LuaState) { + Expect(LuaLoadBuffer(L, "leak = 5 return secret", "=sandbox") == LUA_OK, "load sandbox chunk") + LuaNewTable(L) + LuaPushString(L, "inside") + LuaSetField(L, -2, "secret") + Expect(LuaSetFenv(L, -2), "set function environment") + Expect(LuaPCall(L, 0, 1, 0) == LUA_OK && TopText(L) == "inside", "chunk reads its environment") + LuaSetTop(L, 0) + LuaGetGlobal(L, "leak") + Expect(LuaIsNil(L, -1), "sandbox globals stay inside") + LuaSetTop(L, 0) + Run(L, "=env", "assert(os.getenv('HOME') == nil and io.open('/etc/hostname') == nil)") +} + +TestPrintSink :: (L: *LuaState, test: *TestContext) { + LuaSetPrintSink(L, Capture, cast(*void) test) + Run(L, "=print", "print('a', 1, nil, true) io.write('b', 2, '\\n')") + Expect(TextView(VecSlice(test.output, 0, test.output.count)) == "a\t1\tnil\ttrue\nb2\n", "print goes to the sink") +} + +TestHooks :: (L: *LuaState, test: *TestContext) { + LuaSetHook(L, StopAfterFive, 1000) + RunFails(L, "=spin", "while true do end", "time is up") + Expect(test.hook_calls == 5, "hook called until it stops") + LuaSetHook(L, StopNow, 1) + RunFails(L, "=spin", "local function f() return f() end f()", "instruction limit exceeded") + LuaClearHook(L) + Run(L, "=after", "local s = 0 for i = 1, 100000 do s = s + i end assert(s == 5000050000)") +} + +TestMemoryLimit :: (L: *LuaState) { + LuaCollectGarbage(L) + limits := LuaGetLimits(L) + limits.max_memory = LuaMemoryUsed(L) + 2097152 + LuaSetLimits(L, limits) + RunFails(L, "=hog", "local t = {} for i = 1, 1e7 do t[i] = {i} end", "not enough memory") + Expect(LuaMemoryUsed(L) < limits.max_memory + 1048576, "limit not overshot by much") + limits.max_memory = 0 + LuaSetLimits(L, limits) + Run(L, "=after", "local t = {} for i = 1, 1000 do t[i] = {i} end assert(#t == 1000)") +} + +TestCoroutines :: (L: *LuaState) { + LuaRegister(L, "wait", Wait) + Expect(LuaLoadBuffer(L, "local a = ... local b = wait(a + 1) local c = wait(b * 2) return 'done', c", "=co") == LUA_OK, "load coroutine body") + LuaNewThread(L) + Expect(LuaType(L, 1) == LUA_TYPE_THREAD, "new thread") + LuaPushNumber(L, 1) + status, count := LuaResume(L, 1, 1) + Expect(status == LUA_YIELD && count == 1 && LuaToNumber(L, -1) == 2.0, "first yield") + LuaPop(L, count) + LuaPushNumber(L, 10) + status, count = LuaResume(L, 1, 1) + Expect(status == LUA_YIELD && count == 1 && LuaToNumber(L, -1) == 20.0, "second yield") + LuaPop(L, count) + LuaPushNumber(L, 7) + status, count = LuaResume(L, 1, 1) + Expect(status == LUA_OK && count == 2 && LuaToNumber(L, -1) == 7.0, "coroutine returns") + LuaPop(L, 1) + Expect(TopText(L) == "done", "first result") + LuaPop(L, 1) + status, count = LuaResume(L, 1, 0) + Expect(status == LUA_ERRRUN && Contains(TopText(L), "dead coroutine"), "dead coroutine") + LuaSetTop(L, 0) + Run(L, "=wrap", "local f = coroutine.wrap(function() wait(1) wait(2) return 3 end) assert(f() == 1 and f() == 2 and f() == 3)") + RunFails(L, "=main", "wait()", "outside a coroutine") } Main :: () -> s32 { - L: LuaState - LuaOpen(*L) - failures := 0 - if !Check(*L, "=smoke", "local x = 1 + 2 assert(x == 3) print('smoke ok', x)") { failures += 1 } - LuaClose(*L) - if failures > 0 { return 1 } + test: TestContext + state: LuaState + L := *state + Expect(LuaOpen(L), "open") + Expect(!LuaOpen(L), "open twice") + LuaSetHost(L, cast(*void) *test) + TestValues(L) + TestTables(L) + TestNatives(L) + TestErrors(L) + TestUserdata(L, *test) + TestRefs(L) + TestEnvironment(L) + TestPrintSink(L, *test) + TestHooks(L, *test) + TestMemoryLimit(L) + TestCoroutines(L) + Expect(LuaGetTop(L) == 0, "stack balanced") + LuaClose(L) + Expect(test.finalized == 2, "close runs the remaining finalizer") + VecFree(test.output) + if failures > 0 { + print("vm tests: % failed\n", failures) + return 1 + } print("vm tests passed\n") return 0 }