commit e3223e466dc60d192ab1d977bbac15e49820e9cc Author: Waozi Date: Sat Nov 7 01:37:42 2026 -0300 Add a Lua 5.1 virtual machine written in Ziran Lexer, parser and register compiler for the LuaJIT dialect of Lua 5.1 (goto, hex and \z escapes), an interpreter with tail calls, varargs, coroutines and metatables, a mark-and-sweep collector with weak tables and __gc, the base, coroutine, string, table, math, bit, debug and sandboxed os/io libraries, and an embedding API modeled on the C API. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..807447d --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +build/ +backup/ +ziran.local.toml diff --git a/src/api.zi b/src/api.zi new file mode 100644 index 0000000..3f78f1f --- /dev/null +++ b/src/api.zi @@ -0,0 +1,1161 @@ +// The embedding API. A host owns one LuaState record per Lua universe and +// passes its address everywhere: +// +// state: LuaState; +// L := *state +// LuaOpen(L) +// status := LuaDoString(L, "print('hi')", "=demo") +// LuaClose(L) +// +// Values live on a stack, as in the C API: index 1 is the first argument of +// the running native (or the first host value), -1 the top. Calls that can +// run Lua code return a status or a bool; on failure the error object is on +// the stack (protected calls) or pending (inside natives, which then return +// LuaRaiseError(L)). + +#scope_export + +// Type codes returned by LuaType, matching the C API. +LUA_TYPE_NONE :: -1; +LUA_TYPE_NIL :: 0; +LUA_TYPE_BOOLEAN :: 1; +LUA_TYPE_LIGHTUSERDATA :: 2; +LUA_TYPE_NUMBER :: 3; +LUA_TYPE_STRING :: 4; +LUA_TYPE_TABLE :: 5; +LUA_TYPE_FUNCTION :: 6; +LUA_TYPE_USERDATA :: 7; +LUA_TYPE_THREAD :: 8; + +// Pseudo-indices. +LUA_REGISTRYINDEX :: -10000; +LUA_ENVIRONINDEX :: -10001; +LUA_GLOBALSINDEX :: -10002; + +// LuaRef result for nil. +LUA_REFNIL :: -1; +LUA_NOREF :: -2; + +LuaUpvalueIndex :: (i: s32) -> s32 { return LUA_GLOBALSINDEX - i } + +#scope_module + +// ---------------------------------------------------------------- internals + +StackBase :: (L: *LuaState) -> s64 #inline { + th := L.cur + n := L.threads[th].frames.count + if n == 0 { return 0 } + return L.threads[th].frames[n - 1].base +} + +Top :: (L: *LuaState) -> s64 #inline { return L.threads[L.cur].top } + +// Absolute stack slot of a stack index, or -1 for pseudo/invalid ones. +Slot :: (L: *LuaState, index: s32) -> s64 { + if index > 0 { + position := StackBase(L) + index - 1 + if position >= Top(L) { return -1 } + return position + } + if index > LUA_REGISTRYINDEX { + position := Top(L) + index + if position < StackBase(L) { return -1 } + return position + } + return -1 +} + +CurrentClosure :: (L: *LuaState) -> s32 { + th := L.cur + n := L.threads[th].frames.count + if n == 0 { return -1 } + return L.threads[th].frames[n - 1].closure +} + +IndexValue :: (L: *LuaState, index: s32) -> LuaValue { + if index > LUA_REGISTRYINDEX { + position := Slot(L, index) + if position < 0 { return NilValue() } + return L.threads[L.cur].stack[position] + } + if index == LUA_REGISTRYINDEX { return TableValue(L.registry) } + if index == LUA_GLOBALSINDEX { return TableValue(L.threads[L.cur].env) } + cl := CurrentClosure(L) + if index == LUA_ENVIRONINDEX { + if cl < 0 { return TableValue(L.globals) } + return TableValue(L.closures[cl].env) + } + n := cast(s64)(LUA_GLOBALSINDEX - index) + if cl < 0 || n < 1 || n > L.closures[cl].native_upvals.count { return NilValue() } + return L.closures[cl].native_upvals[n - 1] +} + +SetIndexValue :: (L: *LuaState, index: s32, v: LuaValue) { + if index > LUA_REGISTRYINDEX { + position := Slot(L, index) + if position >= 0 { L.threads[L.cur].stack[position] = v } + return + } + cl := CurrentClosure(L) + if index == LUA_ENVIRONINDEX || index == LUA_GLOBALSINDEX { + if v.t != LUA_TTABLE { return } + if index == LUA_GLOBALSINDEX { L.threads[L.cur].env = v.h } + else if cl >= 0 { L.closures[cl].env = v.h } + return + } + n := cast(s64)(LUA_GLOBALSINDEX - index) + if cl >= 0 && n >= 1 && n <= L.closures[cl].native_upvals.count { + L.closures[cl].native_upvals[n - 1] = v + } +} + +Push :: (L: *LuaState, v: LuaValue) #inline { + th := L.cur + top := L.threads[th].top + if top >= L.threads[th].stack.count { GrowStack(L, th, top + 1) } + L.threads[th].stack[top] = v + L.threads[th].top = top + 1 +} + +PopValue :: (L: *LuaState) -> LuaValue #inline { + th := L.cur + L.threads[th].top -= 1 + return L.threads[th].stack[L.threads[th].top] +} + +ArgCount :: (L: *LuaState) -> s32 #inline { return cast(s32)(Top(L) - StackBase(L)) } + +Arg :: (L: *LuaState, i: s32) -> LuaValue #inline { + position := StackBase(L) + i - 1 + if i < 1 || position >= Top(L) { return NilValue() } + return L.threads[L.cur].stack[position] +} + +PublicType :: (v: LuaValue) -> s32 { + t := v.t + if t == LUA_TNIL { return LUA_TYPE_NIL } + if t == LUA_TFALSE || t == LUA_TTRUE { return LUA_TYPE_BOOLEAN } + if t == LUA_TNUMBER { return LUA_TYPE_NUMBER } + if t == LUA_TSTRING { return LUA_TYPE_STRING } + if t == LUA_TTABLE { return LUA_TYPE_TABLE } + if t == LUA_TFUNCTION { return LUA_TYPE_FUNCTION } + if t == LUA_TUSERDATA { return LUA_TYPE_USERDATA } + if t == LUA_TTHREAD { return LUA_TYPE_THREAD } + if t == LUA_TLIGHTUSERDATA { return LUA_TYPE_LIGHTUSERDATA } + return LUA_TYPE_NONE +} + +NewNative :: (L: *LuaState, fn: LuaNative, name: string) -> s32 { + h := NewClosureObject(L) + L.closures[h].native = fn + if name.count > 0 { L.closures[h].name = Intern(L, name) } + return h +} + +// Name of the running native for argument errors. +NativeName :: (L: *LuaState) -> string { + th := L.cur + frame := L.threads[th].frames.count - 1 + if frame < 0 { return "?" } + kind, name := FrameFunctionName(L, th, frame) + if kind == NAME_NONE || name < 0 { return "?" } + return StrView(L, name) +} + +// Protected call of stack[func] with nargs arguments. Results land at func; +// on error the frames above the caller are dropped and L.error holds the +// error object. `handler` (non-nil) runs at the error point like xpcall's. +ProtectedCall :: (L: *LuaState, func: s64, nargs: s32, want: s32, handler: LuaValue) -> s32 { + th := L.cur + frames := L.threads[th].frames.count + handlers := L.threads[th].handlers.count + entry: LuaHandler + entry.handler = handler + entry.frame_level = frames + VecPush(L.threads[th].handlers, entry) + ok := CallValue(L, func, nargs, want) + VecResize(L.threads[th].handlers, handlers) + if ok { return LUA_OK } + VecResize(L.threads[th].frames, frames) + L.error_traced = false + return LUA_ERRRUN +} + +// Compile text into a closure on top of the stack; status and message on failure. +LoadChunk :: (L: *LuaState, text: string, chunkname: string, env: s32) -> s32 { + error: Vec(u8) + proto := CompileChunk(L, text, chunkname, *error) + if proto < 0 { + Push(L, StringValue(InternBytes(L, *error))) + VecFree(error) + return LUA_ERRSYNTAX + } + VecFree(error) + h := NewClosureObject(L) + L.closures[h].proto = proto + L.closures[h].env = ifx env >= 0 then env else L.globals + Push(L, FunctionValue(h)) + return LUA_OK +} + +// Resume `co` with `nargs` values from the top of the running stack. The +// results (or the error object) replace them; returns the status and the +// number of values pushed. +ResumeThread :: (L: *LuaState, co: s32, nargs: s32) -> (status: s32, count: s32) { + caller := L.cur + if L.threads[co].status != THREAD_SUSPENDED { + L.threads[caller].top -= nargs + message := ifx L.threads[co].status == THREAD_DEAD then "cannot resume dead coroutine" else "cannot resume non-suspended coroutine" + Push(L, StringValue(Intern(L, message))) + return LUA_ERRRUN, 1 + } + if L.native_depth >= L.limits.max_native_depth { + L.threads[caller].top -= nargs + Push(L, StringValue(Intern(L, "C stack overflow"))) + return LUA_ERRRUN, 1 + } + source := L.threads[caller].top - nargs + started := L.threads[co].started + position: s64 = 1 + if started { position = L.threads[co].yield_func } + if !EnsureStackOf(L, co, position + nargs + 64) { + L.threads[caller].top -= nargs + Push(L, StringValue(Intern(L, "stack overflow"))) + return LUA_ERRRUN, 1 + } + i: s64 = 0 + while i < nargs { + L.threads[co].stack[position + i] = L.threads[caller].stack[source + i] + i += 1 + } + L.threads[caller].top = source + L.threads[co].status = THREAD_RUNNING + L.threads[caller].status = THREAD_NORMAL + VecPush(L.resumers, caller) + L.cur = co + L.native_depth += 1 + status: s32 = LUA_OK + body_returned := false + if !started { + L.threads[co].started = true + L.threads[co].top = 1 + nargs + r := Precall(L, 0, nargs, LUA_MULTRET) + if r == CALL_LUA { + status = Execute(L, 0) + } else if r == CALL_YIELD { + status = LUA_YIELD + } else if r == CALL_NOT_FUNCTION { + TypeError(L, L.threads[co].stack[0], "call", -1) + status = LUA_ERRRUN + } else if r == CALL_ERROR { + status = LUA_ERRRUN + } + } else { + func := position + want := L.threads[co].yield_want + MoveResults(L, func, func, nargs, want) + n := L.threads[co].frames.count + if n == 0 { + // The body itself was coroutine.yield: it returns the values. + status = LUA_OK + body_returned = true + } else { + if want >= 0 { + cl := L.threads[co].frames[n - 1].closure + L.threads[co].top = L.threads[co].frames[n - 1].base + L.protos[L.closures[cl].proto].max_stack + } + status = Execute(L, 0) + } + } + L.native_depth -= 1 + L.cur = caller + VecResize(L.resumers, L.resumers.count - 1) + L.threads[caller].status = THREAD_RUNNING + if status == LUA_OK || status == LUA_YIELD { + first: s64 = 0 + last := L.threads[co].top + if status == LUA_YIELD { + first = L.threads[co].yield_func + 1 + L.threads[co].status = THREAD_SUSPENDED + } else { + first = 0 + if body_returned { first = position } + L.threads[co].status = THREAD_DEAD + } + count := last - first + if count < 0 { count = 0 } + if !EnsureStackOf(L, caller, L.threads[caller].top + count + 1) { + L.threads[co].status = THREAD_DEAD + Push(L, StringValue(Intern(L, "stack overflow"))) + return LUA_ERRRUN, 1 + } + i = 0 + while i < count { + Push(L, L.threads[co].stack[first + i]) + i += 1 + } + if status == LUA_OK { L.threads[co].top = 0 } else { L.threads[co].top = first - 1 } + return status, cast(s32) count + } + L.threads[co].status = THREAD_DEAD + VecResize(L.threads[co].frames, 0) + L.threads[co].top = 0 + Push(L, L.error) + L.error = NilValue() + L.error_traced = false + return LUA_ERRRUN, 1 +} + +// ---------------------------------------------------------------- state + +#scope_export + +// Initialize a state with the standard libraries. Returns false when the +// record was already open. +LuaOpen :: (L: *LuaState) -> bool { + if L.open { return false } + L.limits = LuaDefaultLimits() + L.threshold = 4194304 + L.hook_left = 1000000000 + L.random_state = 0x2545F4914F6CDD1D + L.next_fn = -1 + L.inext_fn = -1 + L.file_meta = -1 + i: s64 = 0 + while i < 11 { L.type_meta[i] = -1; i += 1 } + L.globals = -1 + L.globals = NewTable(L, 0, 64) + L.registry = NewTable(L, 0, 8) + L.main = NewThreadObject(L) + L.cur = L.main + L.threads[L.main].status = THREAD_RUNNING + L.threads[L.main].started = true + L.threads[L.main].env = L.globals + names := TagMethodNames() + i = 0 + while i < TM_COUNT { L.tm_names[i] = Intern(L, names[i]); i += 1 } + L.name_n = Intern(L, "n") + L.name_goto = Intern(L, "goto") + L.name_self = Intern(L, "self") + L.name_loaded = Intern(L, "_LOADED") + InternReserved(L) + L.open = true + OpenBase(L) + OpenString(L) + OpenTable(L) + OpenMath(L) + OpenOs(L) + OpenBit(L) + OpenCoroutine(L) + OpenDebug(L) + return true +} + +TagMethodNames :: () -> [20]string { + names: [20]string + names[0] = "__index" + names[1] = "__newindex" + names[2] = "__gc" + names[3] = "__mode" + names[4] = "__eq" + names[5] = "__add" + names[6] = "__sub" + names[7] = "__mul" + names[8] = "__div" + names[9] = "__mod" + names[10] = "__pow" + names[11] = "__unm" + names[12] = "__len" + names[13] = "__lt" + names[14] = "__le" + names[15] = "__concat" + names[16] = "__call" + names[17] = "__tostring" + names[18] = "__metatable" + names[19] = "__name" + return names +} + +// Run pending __gc finalizers and host finalizers, then free everything. +LuaClose :: (L: *LuaState) { + if !L.open { return } + i: s64 = 0 + while i < L.userdata.count { + if L.userdata[i].live && !L.userdata[i].finalized && L.userdata[i].meta >= 0 { + if FastTM(L, L.userdata[i].meta, TM_GC).t != LUA_TNIL { VecPush(L.pending_finalize, cast(s32) i) } + } + i += 1 + } + VecResize(L.threads[L.main].frames, 0) + L.cur = L.main + RunFinalizers(L) + i = 0 + while i < L.userdata.count { + if L.userdata[i].live { FreeUserdata(L, cast(s32) i) } + i += 1 + } + VecFree(L.strings) + VecFree(L.string_free) + VecFree(L.intern) + VecFree(L.tables) + VecFree(L.table_free) + VecFree(L.closures) + VecFree(L.closure_free) + VecFree(L.protos) + VecFree(L.proto_free) + VecFree(L.boxes) + VecFree(L.box_free) + VecFree(L.userdata) + VecFree(L.userdata_free) + VecFree(L.threads) + VecFree(L.thread_free) + VecFree(L.ref_free) + VecFree(L.gray) + VecFree(L.weak) + VecFree(L.pending_finalize) + VecFree(L.resumers) + VecFree(L.file_root) + VecFree(L.env_allow) + VecFree(L.scratch) + VecFree(L.scratch2) + L.intern_used = 0 + L.allocated = 0 + L.open = false +} + +LuaSetLimits :: (L: *LuaState, limits: LuaLimits) { L.limits = limits } +LuaGetLimits :: (L: *LuaState) -> LuaLimits { return L.limits } + +// Call `hook` every `count` checkpoints (Lua calls and loop back-edges). +// A hook returning false raises an error in the running Lua code; set its +// message with LuaSetHookMessage first. +LuaSetHook :: (L: *LuaState, hook: LuaHook, count: s64) { + L.hook = hook + L.hook_set = true + L.hook_count = count + L.hook_left = ifx count > 0 then count else 1000000000 +} + +LuaClearHook :: (L: *LuaState) { + L.hook_set = false + L.hook_left = 1000000000 +} + +LuaSetHookMessage :: (L: *LuaState, message: string) { + L.error = StringValue(Intern(L, message)) +} + +LuaSetPrintSink :: (L: *LuaState, sink: LuaPrintSink, context: *void) { + L.print_sink = sink + L.print_sink_set = true + L.print_context = context +} + +// Let os.getenv read variables whose names start with `prefix` (none by +// default, so os.getenv returns nil). +LuaAllowEnvironment :: (L: *LuaState, prefix: string) { + if prefix.count == 0 { return } + if L.env_allow.count > 0 { VecPush(L.env_allow, 0) } + BuilderAppend(L.env_allow, prefix) +} + +// Directory that dofile/loadfile/io.open may read below; empty (the +// default) disables Lua-side file access. +LuaSetFileRoot :: (L: *LuaState, path: string) { + VecClear(L.file_root) + BuilderAppend(L.file_root, path) +} + +LuaSetHost :: (L: *LuaState, host: *void) { L.host = host } +LuaHost :: (L: *LuaState) -> *void { return L.host } + +LuaCollectGarbage :: (L: *LuaState) { + th := L.cur + if L.threads[th].frames.count > 0 && !L.threads[th].frames[L.threads[th].frames.count - 1].native { return } + CollectGarbage(L) +} + +// Estimated live heap bytes. +LuaMemoryUsed :: (L: *LuaState) -> s64 { return L.allocated } + +// ---------------------------------------------------------------- stack + +LuaGetTop :: (L: *LuaState) -> s32 { return ArgCount(L) } + +LuaSetTop :: (L: *LuaState, index: s32) { + th := L.cur + base := StackBase(L) + if index >= 0 { + target := base + index + if target > L.threads[th].stack.count { GrowStack(L, th, target + 1) } + while L.threads[th].top < target { + L.threads[th].stack[L.threads[th].top] = NilValue() + L.threads[th].top += 1 + } + L.threads[th].top = target + } else { + target := L.threads[th].top + index + 1 + if target < base { target = base } + L.threads[th].top = target + } +} + +LuaPop :: (L: *LuaState, n: s32) { LuaSetTop(L, -n - 1) } + +LuaCheckStack :: (L: *LuaState, extra: s32) -> bool { + return EnsureStack(L, Top(L) + extra + 1) +} + +// A positive index for `index`, the same pseudo-index otherwise. +LuaAbsIndex :: (L: *LuaState, index: s32) -> s32 { + if index > 0 || index <= LUA_REGISTRYINDEX { return index } + return cast(s32)(Top(L) - StackBase(L)) + index + 1 +} + +LuaPushValue :: (L: *LuaState, index: s32) { Push(L, IndexValue(L, index)) } + +LuaRemove :: (L: *LuaState, index: s32) { + position := Slot(L, index) + if position < 0 { return } + th := L.cur + while position + 1 < L.threads[th].top { + L.threads[th].stack[position] = L.threads[th].stack[position + 1] + position += 1 + } + L.threads[th].top -= 1 +} + +LuaInsert :: (L: *LuaState, index: s32) { + position := Slot(L, index) + if position < 0 { return } + th := L.cur + v := L.threads[th].stack[L.threads[th].top - 1] + i := L.threads[th].top - 1 + while i > position { + L.threads[th].stack[i] = L.threads[th].stack[i - 1] + i -= 1 + } + L.threads[th].stack[position] = v +} + +LuaReplace :: (L: *LuaState, index: s32) { + v := PopValue(L) + SetIndexValue(L, index, v) +} + +// ---------------------------------------------------------------- reading + +LuaType :: (L: *LuaState, index: s32) -> s32 { + if index > LUA_REGISTRYINDEX && Slot(L, index) < 0 { return LUA_TYPE_NONE } + return PublicType(IndexValue(L, index)) +} + +LuaTypeName :: (L: *LuaState, type: s32) -> string { + if type == LUA_TYPE_NONE { return "no value" } + if type == LUA_TYPE_NIL { return "nil" } + if type == LUA_TYPE_BOOLEAN { return "boolean" } + if type == LUA_TYPE_NUMBER { return "number" } + if type == LUA_TYPE_STRING { return "string" } + if type == LUA_TYPE_TABLE { return "table" } + if type == LUA_TYPE_FUNCTION { return "function" } + if type == LUA_TYPE_THREAD { return "thread" } + return "userdata" +} + +LuaIsNone :: (L: *LuaState, index: s32) -> bool { return LuaType(L, index) == LUA_TYPE_NONE } +LuaIsNil :: (L: *LuaState, index: s32) -> bool { return IndexValue(L, index).t == LUA_TNIL } +LuaIsNoneOrNil :: (L: *LuaState, index: s32) -> bool { return LuaType(L, index) <= LUA_TYPE_NIL } +LuaIsBoolean :: (L: *LuaState, index: s32) -> bool { t := IndexValue(L, index).t; return t == LUA_TFALSE || t == LUA_TTRUE } +LuaIsTable :: (L: *LuaState, index: s32) -> bool { return IndexValue(L, index).t == LUA_TTABLE } +LuaIsFunction :: (L: *LuaState, index: s32) -> bool { return IndexValue(L, index).t == LUA_TFUNCTION } +LuaIsUserdata :: (L: *LuaState, index: s32) -> bool { t := IndexValue(L, index).t; return t == LUA_TUSERDATA || t == LUA_TLIGHTUSERDATA } + +LuaIsNative :: (L: *LuaState, index: s32) -> bool { + v := IndexValue(L, index) + return v.t == LUA_TFUNCTION && L.closures[v.h].proto < 0 +} + +// Numbers and strings convertible to numbers. +LuaIsNumber :: (L: *LuaState, index: s32) -> bool { + n, ok := ToNumber(L, IndexValue(L, index)) + return ok +} + +// Strings and numbers. +LuaIsString :: (L: *LuaState, index: s32) -> bool { return IsStringLike(IndexValue(L, index)) } + +LuaToNumber :: (L: *LuaState, index: s32) -> float64 { + n, ok := ToNumber(L, IndexValue(L, index)) + return ifx ok then n else 0.0 +} + +LuaToNumberChecked :: (L: *LuaState, index: s32) -> (value: float64, ok: bool) { + return ToNumber(L, IndexValue(L, index)) +} + +// The number truncated toward zero; 0 when it is not a number. +LuaToInteger :: (L: *LuaState, index: s32) -> s64 { + n, ok := ToNumber(L, IndexValue(L, index)) + if !ok || n != n { return 0 } + if n >= 9223372036854775807.0 { return 9223372036854775807 } + if n <= -9223372036854775808.0 { return -9223372036854775807 - 1 } + return SafeInteger(n) +} + +LuaToBoolean :: (L: *LuaState, index: s32) -> bool { return Truthy(IndexValue(L, index)) } + +// String bytes of a string or number value (numbers are converted in place, +// as lua_tolstring does). The view lasts while the value stays reachable. +LuaToString :: (L: *LuaState, index: s32) -> (text: string, ok: bool) { + v := IndexValue(L, index) + if v.t == LUA_TSTRING { return StrView(L, v.h), true } + if v.t == LUA_TNUMBER { + h, ok := ToStringHandle(L, v) + SetIndexValue(L, index, StringValue(h)) + return StrView(L, h), true + } + return "", false +} + +// Raw length: string bytes, table border, 0 otherwise. +LuaObjLen :: (L: *LuaState, index: s32) -> s64 { + v := IndexValue(L, index) + if v.t == LUA_TSTRING { return StrLen(L, v.h) } + if v.t == LUA_TTABLE { return TableLength(L, v.h) } + if v.t == LUA_TNUMBER { + buffer: Vec(u8) + AppendNumber(*buffer, v.n) + n := buffer.count + VecFree(buffer) + return n + } + return 0 +} + +LuaToUserdata :: (L: *LuaState, index: s32) -> *void { + v := IndexValue(L, index) + if v.t == LUA_TUSERDATA { return L.userdata[v.h].data } + if v.t == LUA_TLIGHTUSERDATA { + bits: NumberBits + bits.f = v.n + return cast(*void) bits.u + } + return null +} + +LuaUserdataTag :: (L: *LuaState, index: s32) -> s64 { + v := IndexValue(L, index) + if v.t == LUA_TUSERDATA { return L.userdata[v.h].tag } + return 0 +} + +LuaRawEqual :: (L: *LuaState, a: s32, b: s32) -> bool { + return RawEqual(IndexValue(L, a), IndexValue(L, b)) +} + +// a == b with __eq; ok=false when a metamethod raised an error. +LuaEqual :: (L: *LuaState, a: s32, b: s32) -> (equal: bool, ok: bool) { + result := false + ok := EqualValues(L, IndexValue(L, a), IndexValue(L, b), *result) + return result, ok +} + +LuaLessThan :: (L: *LuaState, a: s32, b: s32) -> (less: bool, ok: bool) { + result := false + ok := LessThan(L, IndexValue(L, a), IndexValue(L, b), *result) + return result, ok +} + +// ---------------------------------------------------------------- pushing + +LuaPushNil :: (L: *LuaState) { Push(L, NilValue()) } +LuaPushNumber :: (L: *LuaState, n: float64) { Push(L, NumberValue(n)) } +LuaPushInteger :: (L: *LuaState, n: s64) { Push(L, NumberValue(cast(float64) n)) } +LuaPushBoolean :: (L: *LuaState, b: bool) { Push(L, BoolValue(b)) } +LuaPushString :: (L: *LuaState, text: string) { Push(L, StringValue(Intern(L, text))) } + +LuaPushLightUserdata :: (L: *LuaState, data: *void) { + bits: NumberBits + bits.u = cast(u64) data + v: LuaValue + v.t = LUA_TLIGHTUSERDATA + v.n = bits.f + Push(L, v) +} + +// Push a native function; `name` appears in error messages and tracebacks. +LuaPushNative :: (L: *LuaState, fn: LuaNative, name: string) { + Push(L, FunctionValue(NewNative(L, fn, name))) +} + +// Push a native closure taking the top `count` values as upvalues, read +// back with LuaUpvalueIndex(1..count). +LuaPushNativeClosure :: (L: *LuaState, fn: LuaNative, count: s32, name: string) { + h := NewNative(L, fn, name) + th := L.cur + first := L.threads[th].top - count + i: s64 = 0 + while i < count { + VecPush(L.closures[h].native_upvals, L.threads[th].stack[first + i]) + i += 1 + } + L.threads[th].top = first + Push(L, FunctionValue(h)) +} + +// Push a full userdata wrapping host data. `tag` identifies the host type. +LuaNewUserdata :: (L: *LuaState, data: *void, tag: s64) { + h := NewUserdataObject(L) + L.userdata[h].data = data + L.userdata[h].tag = tag + Push(L, ObjectValue(LUA_TUSERDATA, h)) +} + +// LuaNewUserdata with `finalizer` run when the userdata is collected or the +// state closes (after any __gc metamethod). +LuaNewUserdataFinalized :: (L: *LuaState, data: *void, tag: s64, finalizer: LuaFinalizer) { + h := NewUserdataObject(L) + L.userdata[h].data = data + L.userdata[h].tag = tag + L.userdata[h].finalizer = finalizer + L.userdata[h].has_finalizer = true + Push(L, ObjectValue(LUA_TUSERDATA, h)) +} + +LuaPushThreadValue :: (L: *LuaState) -> bool { + Push(L, ObjectValue(LUA_TTHREAD, L.cur)) + return L.cur == L.main +} + +// ---------------------------------------------------------------- tables + +LuaCreateTable :: (L: *LuaState, narr: s32, nrec: s32) { Push(L, TableValue(NewTable(L, narr, nrec))) } +LuaNewTable :: (L: *LuaState) { Push(L, TableValue(NewTable(L, 0, 0))) } + +// t[k] with metamethods: pops the key, pushes the value. +LuaGetTable :: (L: *LuaState, index: s32) -> bool { + t := IndexValue(L, index) + key := PopValue(L) + result: LuaValue + if !GetIndex(L, t, key, *result, -1) { return false } + Push(L, result) + return true +} + +LuaGetField :: (L: *LuaState, index: s32, name: string) -> bool { + t := IndexValue(L, index) + result: LuaValue + if !GetIndex(L, t, StringValue(Intern(L, name)), *result, -1) { return false } + Push(L, result) + return true +} + +LuaGetGlobal :: (L: *LuaState, name: string) -> bool { return LuaGetField(L, LUA_GLOBALSINDEX, name) } + +// t[k] = v with metamethods: pops the value and the key. +LuaSetTable :: (L: *LuaState, index: s32) -> bool { + t := IndexValue(L, index) + value := PopValue(L) + key := PopValue(L) + return SetIndex(L, t, key, value, -1) +} + +// t[name] = v: pops the value. +LuaSetField :: (L: *LuaState, index: s32, name: string) -> bool { + t := IndexValue(L, index) + value := PopValue(L) + return SetIndex(L, t, StringValue(Intern(L, name)), value, -1) +} + +LuaSetGlobal :: (L: *LuaState, name: string) -> bool { return LuaSetField(L, LUA_GLOBALSINDEX, name) } + +LuaRawGet :: (L: *LuaState, index: s32) { + t := IndexValue(L, index) + key := PopValue(L) + if t.t != LUA_TTABLE { Push(L, NilValue()); return } + Push(L, RawGet(L, t.h, key)) +} + +LuaRawGetI :: (L: *LuaState, index: s32, n: s64) { + t := IndexValue(L, index) + if t.t != LUA_TTABLE { Push(L, NilValue()); return } + Push(L, GetInt(L, t.h, n)) +} + +// Raw t[k] = v: pops value and key; false for a nil/NaN key or non-table. +LuaRawSet :: (L: *LuaState, index: s32) -> bool { + t := IndexValue(L, index) + value := PopValue(L) + key := PopValue(L) + if t.t != LUA_TTABLE { return RuntimeError(L, "table expected") } + if !ValidKey(L, key) { return false } + RawSet(L, t.h, key, value) + return true +} + +LuaRawSetI :: (L: *LuaState, index: s32, n: s64) { + t := IndexValue(L, index) + value := PopValue(L) + if t.t != LUA_TTABLE { return } + SetInt(L, t.h, n, value) +} + +// lua_next: pops a key and pushes the next key and value. Returns 1 for a +// pair, 0 at the end, -1 for an invalid key (error pending). +LuaNext :: (L: *LuaState, index: s32) -> s32 { + t := IndexValue(L, index) + key := PopValue(L) + if t.t != LUA_TTABLE { return 0 } + k: LuaValue + v: LuaValue + found, ok := TableNext(L, t.h, key, *k, *v) + if !ok { ErrorText(L, "invalid key to 'next'"); return -1 } + if !found { return 0 } + Push(L, k) + Push(L, v) + return 1 +} + +// Push the metatable of a value; false (nothing pushed) when it has none. +LuaGetMetatable :: (L: *LuaState, index: s32) -> bool { + mt := MetatableOf(L, IndexValue(L, index)) + if mt < 0 { return false } + Push(L, TableValue(mt)) + return true +} + +// Pop a table (or nil) and make it the value's metatable. +LuaSetMetatable :: (L: *LuaState, index: s32) -> bool { + v := IndexValue(L, index) + mt := PopValue(L) + h: s32 = -1 + if mt.t == LUA_TTABLE { h = mt.h } else if mt.t != LUA_TNIL { return false } + if v.t == LUA_TTABLE { L.tables[v.h].meta = h; return true } + if v.t == LUA_TUSERDATA { L.userdata[v.h].meta = h; return true } + if v.t <= LUA_TLIGHTUSERDATA { L.type_meta[v.t] = h; if v.t == LUA_TFALSE { L.type_meta[LUA_TTRUE] = h } if v.t == LUA_TTRUE { L.type_meta[LUA_TFALSE] = h } return true } + return false +} + +// luaL_newmetatable: registry[name] = new table (pushed); false when it +// already existed (the existing one is pushed). +LuaNewMetatable :: (L: *LuaState, name: string) -> bool { + key := Intern(L, name) + existing := GetStr(L, L.registry, key) + if existing.t != LUA_TNIL { Push(L, existing); return false } + t := NewTable(L, 0, 4) + SetStr(L, L.registry, key, TableValue(t)) + Push(L, TableValue(t)) + return true +} + +LuaGetRegistryMetatable :: (L: *LuaState, name: string) { + Push(L, GetStr(L, L.registry, Intern(L, name))) +} + +// The data of a userdata whose metatable is registry[name], else null. +LuaTestUserdata :: (L: *LuaState, index: s32, name: string) -> *void { + v := IndexValue(L, index) + if v.t != LUA_TUSERDATA { return null } + expected := GetStr(L, L.registry, Intern(L, name)) + if expected.t != LUA_TTABLE || L.userdata[v.h].meta != expected.h { return null } + return L.userdata[v.h].data +} + +// Push the environment table of a function, userdata or thread. +LuaGetFenv :: (L: *LuaState, index: s32) { + v := IndexValue(L, index) + if v.t == LUA_TFUNCTION { Push(L, TableValue(L.closures[v.h].env)); return } + if v.t == LUA_TUSERDATA && L.userdata[v.h].env >= 0 { Push(L, TableValue(L.userdata[v.h].env)); return } + if v.t == LUA_TTHREAD { Push(L, TableValue(L.threads[v.h].env)); return } + Push(L, NilValue()) +} + +// Pop a table and make it the environment of the value at index. +LuaSetFenv :: (L: *LuaState, index: s32) -> bool { + v := IndexValue(L, index) + env := PopValue(L) + if env.t != LUA_TTABLE { return false } + if v.t == LUA_TFUNCTION { L.closures[v.h].env = env.h; return true } + if v.t == LUA_TUSERDATA { L.userdata[v.h].env = env.h; return true } + if v.t == LUA_TTHREAD { L.threads[v.h].env = env.h; return true } + return false +} + +// ---------------------------------------------------------------- calls + +// Call the function below `nargs` arguments, leaving `want` results +// (LUA_MULTRET for all). Unprotected: inside a native, return +// LUA_NATIVE_ERROR when this fails. +LuaCall :: (L: *LuaState, nargs: s32, want: s32) -> bool { + func := Top(L) - nargs - 1 + return CallValue(L, func, nargs, want) +} + +// Protected call. `handler` is a stack index of an error function (0 for +// none). On error the message replaces the function and arguments. +LuaPCall :: (L: *LuaState, nargs: s32, want: s32, handler: s32) -> s32 { + func := Top(L) - nargs - 1 + h := NilValue() + if handler != 0 { h = IndexValue(L, handler) } + status := ProtectedCall(L, func, nargs, want, h) + if status != LUA_OK { + th := L.cur + L.threads[th].top = func + Push(L, L.error) + L.error = NilValue() + } + return status +} + +// Compile a chunk and push it as a function (or push the error message). +LuaLoadBuffer :: (L: *LuaState, text: string, chunkname: string) -> s32 { + return LoadChunk(L, text, chunkname, -1) +} + +LuaLoadString :: (L: *LuaState, text: string) -> s32 { return LoadChunk(L, text, text, -1) } + +// Load and run a chunk; errors carry a traceback. The message stays on the +// stack when the status is not LUA_OK. +LuaDoString :: (L: *LuaState, text: string, chunkname: string) -> s32 { + status := LoadChunk(L, text, chunkname, -1) + if status != LUA_OK { return status } + return CallWithTraceback(L, 0, LUA_MULTRET) +} + +// LuaPCall with debug.traceback as the error handler. +CallWithTraceback :: (L: *LuaState, nargs: s32, want: s32) -> s32 { + func := Top(L) - nargs - 1 + handler := FunctionValue(NewNative(L, TracebackHandler, "traceback")) + status := ProtectedCall(L, func, nargs, want, handler) + if status != LUA_OK { + L.threads[L.cur].top = func + Push(L, L.error) + L.error = NilValue() + } + return status +} + +// Read and run a file from the host file system (not limited by the file +// root, which only applies to Lua's dofile/loadfile). +LuaDoFile :: (L: *LuaState, path: string) -> s32 { + status := LuaLoadFile(L, path) + if status != LUA_OK { return status } + return CallWithTraceback(L, 0, LUA_MULTRET) +} + +LuaLoadFile :: (L: *LuaState, path: string) -> s32 { + bytes: Vec(u8) + if !ReadFileInto(path, *bytes) { + VecFree(bytes) + message: Vec(u8) + BuilderAppend(message, "cannot open ") + BuilderAppend(message, path) + Push(L, StringValue(InternBytes(L, *message))) + VecFree(message) + return LUA_ERRFILE + } + name: Vec(u8) + VecPush(name, #char "@") + BuilderAppend(name, path) + status := LoadChunk(L, BytesView(*bytes), BytesView(*name), -1) + VecFree(name) + VecFree(bytes) + return status +} + +// ---------------------------------------------------------------- errors + +// Raise the value on top of the stack. Return this from a native. +LuaRaiseError :: (L: *LuaState) -> s32 { + SetError(L, PopValue(L)) + return LUA_NATIVE_ERROR +} + +// Raise "chunk:line: message" positioned at the Lua caller of the native. +LuaErrorText :: (L: *LuaState, message: string) -> s32 { + text: Vec(u8) + AppendWhere(L, *text, 1) + BuilderAppend(text, message) + SetError(L, StringValue(InternBytes(L, *text))) + VecFree(text) + return LUA_NATIVE_ERROR +} + +// "bad argument #n to 'name' (message)". +LuaArgError :: (L: *LuaState, n: s32, message: string) -> s32 { + text: Vec(u8) + BuilderAppend(text, "bad argument #") + Append(*text, cast(s64) n) + BuilderAppend(text, " to '") + BuilderAppend(text, NativeName(L)) + BuilderAppend(text, "' (") + BuilderAppend(text, message) + VecPush(text, #char ")") + result := LuaErrorText(L, BytesView(*text)) + VecFree(text) + return result +} + +// "bad argument #n to 'name' (expected expected, got actual)". +LuaTypeError :: (L: *LuaState, n: s32, expected: string) -> s32 { + text: Vec(u8) + BuilderAppend(text, expected) + BuilderAppend(text, " expected, got ") + v := Arg(L, n) + BuilderAppend(text, ifx n > ArgCount(L) then "no value" else TypeNameOf(v.t)) + result := LuaArgError(L, n, BytesView(*text)) + VecFree(text) + return result +} + +// Argument checks for natives: ok=false means an error is pending and the +// native should return LUA_NATIVE_ERROR. +LuaCheckNumber :: (L: *LuaState, n: s32) -> (value: float64, ok: bool) { + value, ok := ToNumber(L, Arg(L, n)) + if !ok { LuaTypeError(L, n, "number"); return 0.0, false } + return value, true +} + +LuaCheckInteger :: (L: *LuaState, n: s32) -> (value: s64, ok: bool) { + value, ok := ToNumber(L, Arg(L, n)) + if !ok { LuaTypeError(L, n, "number"); return 0, false } + return SafeInteger(value), true +} + +LuaOptNumber :: (L: *LuaState, n: s32, fallback: float64) -> (value: float64, ok: bool) { + if Arg(L, n).t == LUA_TNIL { return fallback, true } + return LuaCheckNumber(L, n) +} + +LuaOptInteger :: (L: *LuaState, n: s32, fallback: s64) -> (value: s64, ok: bool) { + if Arg(L, n).t == LUA_TNIL { return fallback, true } + return LuaCheckInteger(L, n) +} + +LuaCheckString :: (L: *LuaState, n: s32) -> (text: string, ok: bool) { + v := Arg(L, n) + if v.t == LUA_TSTRING { return StrView(L, v.h), true } + if v.t == LUA_TNUMBER { + h, converted := ToStringHandle(L, v) + L.threads[L.cur].stack[StackBase(L) + n - 1] = StringValue(h) + return StrView(L, h), true + } + LuaTypeError(L, n, "string") + return "", false +} + +LuaOptString :: (L: *LuaState, n: s32, fallback: string) -> (text: string, ok: bool) { + if Arg(L, n).t == LUA_TNIL { return fallback, true } + return LuaCheckString(L, n) +} + +LuaCheckTable :: (L: *LuaState, n: s32) -> bool { + if Arg(L, n).t == LUA_TTABLE { return true } + LuaTypeError(L, n, "table") + return false +} + +LuaCheckAny :: (L: *LuaState, n: s32) -> bool { + if n <= ArgCount(L) { return true } + LuaArgError(L, n, "value expected") + return false +} + +// Push "message\nstack traceback:..." for the running thread. +LuaTraceback :: (L: *LuaState, message: string, level: s32) { + text: Vec(u8) + if message.count > 0 { + BuilderAppend(text, message) + VecPush(text, 10) + } + AppendTraceback(L, *text, L.cur, level) + Push(L, StringValue(InternBytes(L, *text))) + VecFree(text) +} + +// ---------------------------------------------------------------- refs + +// Pop the top value into the registry and return a handle for it. +LuaRef :: (L: *LuaState) -> s32 { + v := PopValue(L) + if v.t == LUA_TNIL { return LUA_REFNIL } + ref: s32 = 0 + if L.ref_free.count > 0 { + ref = L.ref_free[L.ref_free.count - 1] + VecResize(L.ref_free, L.ref_free.count - 1) + } else { + ref = cast(s32)(L.tables[L.registry].arr.count + 1) + } + SetInt(L, L.registry, ref, v) + return ref +} + +LuaUnref :: (L: *LuaState, ref: s32) { + if ref <= 0 { return } + SetInt(L, L.registry, ref, BoolValue(false)) + VecPush(L.ref_free, ref) +} + +LuaPushRef :: (L: *LuaState, ref: s32) { + if ref <= 0 { Push(L, NilValue()); return } + Push(L, GetInt(L, L.registry, ref)) +} + +// ---------------------------------------------------------------- registration + +// globals[name] = native. +LuaRegister :: (L: *LuaState, name: string, fn: LuaNative) { + SetStr(L, L.threads[L.cur].env, Intern(L, name), FunctionValue(NewNative(L, fn, name))) +} + +// t[name] = native for the table at index. +LuaSetNative :: (L: *LuaState, index: s32, name: string, fn: LuaNative) { + t := IndexValue(L, index) + if t.t != LUA_TTABLE { return } + SetStr(L, t.h, Intern(L, name), FunctionValue(NewNative(L, fn, name))) +} + +// ---------------------------------------------------------------- threads + +// Push a new coroutine running the function on top of the stack (popped). +LuaNewThread :: (L: *LuaState) { + f := PopValue(L) + co := NewThreadObject(L) + L.threads[co].stack[0] = f + L.threads[co].top = 1 + L.threads[co].env = L.threads[L.cur].env + Push(L, ObjectValue(LUA_TTHREAD, co)) +} + +// Resume the coroutine at `index` with the top `nargs` values; its results +// (or error message) replace them. Returns LUA_OK when it finished, +// LUA_YIELD when it yielded, an error status otherwise. +LuaResume :: (L: *LuaState, index: s32, nargs: s32) -> (status: s32, count: s32) { + v := IndexValue(L, index) + if v.t != LUA_TTHREAD { + L.threads[L.cur].top -= nargs + Push(L, StringValue(Intern(L, "not a coroutine"))) + return LUA_ERRRUN, 1 + } + return ResumeThread(L, v.h, nargs) +} + +// Yield the top `n` values from a native: `return LuaYield(L, n)`. The +// resume arguments become the native call's results. +LuaYield :: (L: *LuaState, n: s32) -> s32 { + th := L.cur + if th == L.main { return LuaErrorText(L, "attempt to yield from outside a coroutine") } + if L.threads[th].nesting > 0 { return LuaErrorText(L, "attempt to yield across metamethod/C-call boundary") } + base := StackBase(L) + top := L.threads[th].top + count := cast(s64) n + if count > top - base { count = top - base } + i: s64 = 0 + while i < count { + L.threads[th].stack[base + i] = L.threads[th].stack[top - count + i] + i += 1 + } + L.threads[th].top = base + count + return LUA_NATIVE_YIELD +} diff --git a/src/compiler.zi b/src/compiler.zi new file mode 100644 index 0000000..6cd0335 --- /dev/null +++ b/src/compiler.zi @@ -0,0 +1,1397 @@ +// Scope resolution and register-based code generation from the AST. +// Locals captured by inner functions live in boxes created at declaration, +// so each loop iteration's fresh local gets its own box. + +#scope_module + +OP_MOVE :: 0; +OP_LOADK :: 1; +OP_LOADNIL :: 2; +OP_LOADBOOL :: 3; +OP_GETUPVAL :: 4; +OP_SETUPVAL :: 5; +OP_GETBOX :: 6; +OP_SETBOX :: 7; +OP_NEWBOX :: 8; +OP_GETGLOBAL :: 9; +OP_SETGLOBAL :: 10; +OP_GETTABLE :: 11; +OP_SETTABLE :: 12; +OP_NEWTABLE :: 13; +OP_SELF :: 14; +OP_ADD :: 15; +OP_SUB :: 16; +OP_MUL :: 17; +OP_DIV :: 18; +OP_MOD :: 19; +OP_POW :: 20; +OP_UNM :: 21; +OP_NOT :: 22; +OP_LEN :: 23; +OP_CONCAT :: 24; +OP_JMP :: 25; +OP_JT :: 26; +OP_JF :: 27; +OP_JEQ :: 28; +OP_JNE :: 29; +OP_JLT :: 30; +OP_JNLT :: 31; +OP_JLE :: 32; +OP_JNLE :: 33; +OP_EQ :: 34; +OP_NE :: 35; +OP_LT :: 36; +OP_LE :: 37; +OP_CALL :: 38; +OP_TAILCALL :: 39; +OP_RETURN :: 40; +OP_FORPREP :: 41; +OP_FORLOOP :: 42; +OP_TFORCALL :: 43; +OP_TFORLOOP :: 44; +OP_SETLIST :: 45; +OP_CLOSURE :: 46; +OP_VARARG :: 47; +// Field access with a constant string key: R[A] = R[B][K[C]]. +OP_GETFIELD :: 48; +// R[A][K[B]] = RK(C). +OP_SETFIELD :: 49; +OP_COUNT :: 50; + +LFIELDS_PER_FLUSH :: 50; + +LocalInfo :: struct { + name: s32 + captured: bool + reg: s32 + locvar: s32 +} + +UpvalInfo :: struct { + name: s32 + from_local: bool + index: s32 +} + +FuncInfo :: struct { + parent: s32 + locals: Vec(LocalInfo) + upvals: Vec(UpvalInfo) + active: Vec(s32) + is_vararg: bool +} + +GotoInfo :: struct { + name: s32 + pc: s32 + line: s32 + depth: s32 +} + +LabelInfo :: struct { + name: s32 + pc: s32 + depth: s32 +} + +FuncState :: struct { + info: s32 + code: Vec(LuaInstr) + lines: Vec(s32) + constants: Vec(LuaValue) + protos: Vec(s32) + upvals: Vec(LuaUpvalDesc) + upval_names: Vec(s32) + locvars: Vec(LuaLocVar) + max_stack: s32 + freereg: s32 + nactive: s32 + line: s32 + depth: s32 + breaks: Vec(s32) + loop_breaks: Vec(s32) + gotos: Vec(GotoInfo) + labels: Vec(LabelInfo) + active_locals: Vec(s32) +} + +Compiler :: struct { + p: *Parser + L: *LuaState + funcs: Vec(FuncInfo) + source: s32 +} + +// ---------------------------------------------------------------- resolve + +AddFunc :: (c: *Compiler, parent: s32) -> s32 { + at := c.funcs.count + VecResize(c.funcs, at + 1) + c.funcs[at].parent = parent + return cast(s32) at +} + +DeclareLocal :: (c: *Compiler, f: s32, decl: s32) { + at := c.funcs[f].locals.count + VecResize(c.funcs[f].locals, at + 1) + c.funcs[f].locals[at].name = c.p.nodes[decl].str + c.funcs[f].locals[at].reg = -1 + c.p.nodes[decl].d = cast(s32) at + VecPush(c.funcs[f].active, cast(s32) at) +} + +FindActive :: (c: *Compiler, f: s32, name: s32) -> s32 { + i := c.funcs[f].active.count - 1 + while i >= 0 { + local := c.funcs[f].active[i] + if c.funcs[f].locals[local].name == name { return local } + i -= 1 + } + return -1 +} + +// Find or add an upvalue for `name` in function f; -1 when it is a global. +FindUpval :: (c: *Compiler, f: s32, name: s32) -> s32 { + i: s64 = 0 + while i < c.funcs[f].upvals.count { + if c.funcs[f].upvals[i].name == name { return cast(s32) i } + i += 1 + } + parent := c.funcs[f].parent + if parent < 0 { return -1 } + local := FindActive(c, parent, name) + from_local := false + index: s32 = -1 + if local >= 0 { + c.funcs[parent].locals[local].captured = true + from_local = true + index = local + } else { + index = FindUpval(c, parent, name) + if index < 0 { return -1 } + } + at := c.funcs[f].upvals.count + VecResize(c.funcs[f].upvals, at + 1) + c.funcs[f].upvals[at].name = name + c.funcs[f].upvals[at].from_local = from_local + c.funcs[f].upvals[at].index = index + return cast(s32) at +} + +ResolveList :: (c: *Compiler, f: s32, first: s32) -> bool { + e := first + while e >= 0 { + if !ResolveExpr(c, f, e) { return false } + e = c.p.nodes[e].next + } + return true +} + +ResolveError :: (c: *Compiler, line: s32, message: string) -> bool { + c.p.lx.line = line + c.p.lx.failed = false + LexError(*c.p.lx, message, false) + return false +} + +ResolveFunction :: (c: *Compiler, parent: s32, node: s32) -> bool { + f := AddFunc(c, parent) + c.p.nodes[node].d = f + c.funcs[f].is_vararg = c.p.nodes[node].c == 1 + param := c.p.nodes[node].a + while param >= 0 { + DeclareLocal(c, f, param) + param = c.p.nodes[param].next + } + return ResolveBlock(c, f, c.p.nodes[node].b) +} + +ResolveExpr :: (c: *Compiler, f: s32, e: s32) -> bool { + if e < 0 { return true } + kind := c.p.nodes[e].kind + if kind == E_NAME { + name := c.p.nodes[e].str + local := FindActive(c, f, name) + if local >= 0 { + c.p.nodes[e].c = 1 + c.p.nodes[e].d = local + return true + } + up := FindUpval(c, f, name) + if up >= 0 { + c.p.nodes[e].c = 2 + c.p.nodes[e].d = up + return true + } + c.p.nodes[e].c = 0 + return true + } + if kind == E_VARARG { + if !c.funcs[f].is_vararg { return ResolveError(c, c.p.nodes[e].line, "cannot use '...' outside a vararg function") } + return true + } + if kind == E_FUNCTION { return ResolveFunction(c, f, e) } + if kind == E_TABLE { + field := c.p.nodes[e].a + while field >= 0 { + if !ResolveExpr(c, f, c.p.nodes[field].a) { return false } + if !ResolveExpr(c, f, c.p.nodes[field].b) { return false } + field = c.p.nodes[field].next + } + return true + } + if kind == E_CALL || kind == E_METHOD { + if !ResolveExpr(c, f, c.p.nodes[e].a) { return false } + return ResolveList(c, f, c.p.nodes[e].b) + } + if kind == E_BINOP || kind == E_AND || kind == E_OR || kind == E_INDEX { + if !ResolveExpr(c, f, c.p.nodes[e].a) { return false } + return ResolveExpr(c, f, c.p.nodes[e].b) + } + if kind == E_UNOP || kind == E_PAREN { return ResolveExpr(c, f, c.p.nodes[e].a) } + return true +} + +ResolveBlock :: (c: *Compiler, f: s32, first: s32) -> bool { + mark := c.funcs[f].active.count + s := first + while s >= 0 { + if !ResolveStatement(c, f, s) { return false } + s = c.p.nodes[s].next + } + VecResize(c.funcs[f].active, mark) + return true +} + +ResolveStatement :: (c: *Compiler, f: s32, s: s32) -> bool { + kind := c.p.nodes[s].kind + if kind == S_LOCAL { + if !ResolveList(c, f, c.p.nodes[s].b) { return false } + decl := c.p.nodes[s].a + while decl >= 0 { DeclareLocal(c, f, decl); decl = c.p.nodes[decl].next } + return true + } + if kind == S_LOCALFUNC { + DeclareLocal(c, f, c.p.nodes[s].a) + return ResolveExpr(c, f, c.p.nodes[s].b) + } + if kind == S_ASSIGN { + if !ResolveList(c, f, c.p.nodes[s].a) { return false } + return ResolveList(c, f, c.p.nodes[s].b) + } + if kind == S_CALL { return ResolveExpr(c, f, c.p.nodes[s].a) } + if kind == S_DO { return ResolveBlock(c, f, c.p.nodes[s].a) } + if kind == S_WHILE { + if !ResolveExpr(c, f, c.p.nodes[s].a) { return false } + return ResolveBlock(c, f, c.p.nodes[s].b) + } + if kind == S_REPEAT { + // The condition sees the body's locals. + mark := c.funcs[f].active.count + body := c.p.nodes[s].a + while body >= 0 { + if !ResolveStatement(c, f, body) { return false } + body = c.p.nodes[body].next + } + ok := ResolveExpr(c, f, c.p.nodes[s].b) + VecResize(c.funcs[f].active, mark) + return ok + } + if kind == S_IF { + if !ResolveExpr(c, f, c.p.nodes[s].a) { return false } + if !ResolveBlock(c, f, c.p.nodes[s].b) { return false } + other := c.p.nodes[s].c + if other >= 0 { + if c.p.nodes[other].kind == S_IF { return ResolveStatement(c, f, other) } + return ResolveBlock(c, f, c.p.nodes[other].a) + } + return true + } + if kind == S_NUMFOR { + if !ResolveExpr(c, f, c.p.nodes[s].b) { return false } + if !ResolveExpr(c, f, c.p.nodes[s].c) { return false } + if !ResolveExpr(c, f, c.p.nodes[s].d) { return false } + mark := c.funcs[f].active.count + DeclareLocal(c, f, c.p.nodes[s].a) + ok := ResolveBlock(c, f, c.p.nodes[s].e) + VecResize(c.funcs[f].active, mark) + return ok + } + if kind == S_GENFOR { + if !ResolveList(c, f, c.p.nodes[s].b) { return false } + mark := c.funcs[f].active.count + decl := c.p.nodes[s].a + while decl >= 0 { DeclareLocal(c, f, decl); decl = c.p.nodes[decl].next } + ok := ResolveBlock(c, f, c.p.nodes[s].c) + VecResize(c.funcs[f].active, mark) + return ok + } + if kind == S_FUNCTION { + if !ResolveExpr(c, f, c.p.nodes[s].a) { return false } + return ResolveExpr(c, f, c.p.nodes[s].b) + } + if kind == S_RETURN { return ResolveList(c, f, c.p.nodes[s].a) } + return true +} + +// ---------------------------------------------------------------- emit + +Emit :: (fs: *FuncState, op: s32, a: s32, b: s32, c: s32) -> s32 { + pc := fs.code.count + instr: LuaInstr + instr.op = cast(u8) op + instr.a = a + instr.b = b + instr.c = c + VecPush(fs.code, instr) + VecPush(fs.lines, fs.line) + return cast(s32) pc +} + +PC :: (fs: *FuncState) -> s32 #inline { return cast(s32) fs.code.count } + +Reserve :: (fs: *FuncState, n: s32) -> s32 { + r := fs.freereg + fs.freereg += n + if fs.freereg > fs.max_stack { fs.max_stack = fs.freereg } + return r +} + +IsJumpOp :: (op: u8) -> bool { return op >= OP_JMP && op <= OP_JNLE } + +// Jump lists are chained through the jump target field (A); -1 ends. +Concat :: (fs: *FuncState, list: s32, other: s32) -> s32 { + if list < 0 { return other } + if other < 0 { return list } + at := list + while fs.code[at].a >= 0 { at = fs.code[at].a } + fs.code[at].a = other + return list +} + +PatchList :: (fs: *FuncState, list: s32, target: s32) { + at := list + while at >= 0 { + next := fs.code[at].a + fs.code[at].a = target + at = next + } +} + +PatchHere :: (fs: *FuncState, list: s32) { PatchList(fs, list, PC(fs)) } + +EmitJump :: (fs: *FuncState) -> s32 { return Emit(fs, OP_JMP, -1, 0, 0) } + +AddConstant :: (fs: *FuncState, value: LuaValue) -> s32 { + i: s64 = 0 + count := fs.constants.count + // Search recent constants; long tables of literals stay linear-time. + if count > 512 { i = count - 512 } + while i < count { + k := fs.constants[i] + if k.t == value.t { + if value.t == LUA_TNUMBER { + if k.n == value.n && (k.n != 0.0 || IsNegativeZero(k.n) == IsNegativeZero(value.n)) { return cast(s32) i } + } else if k.h == value.h { + return cast(s32) i + } + } + i += 1 + } + VecPush(fs.constants, value) + return cast(s32) count +} + +IsNegativeZero :: (x: float64) -> bool { + if x != 0.0 { return false } + return 1.0 / x < 0.0 +} + +StringK :: (fs: *FuncState, h: s32) -> s32 { return AddConstant(fs, StringValue(h)) } +NumberK :: (fs: *FuncState, n: float64) -> s32 { return AddConstant(fs, NumberValue(n)) } + +// RK operand for constant index k. +KOperand :: (k: s32) -> s32 #inline { return -1 - k } + +LocalOf :: (c: *Compiler, fs: *FuncState, e: s32) -> s32 { + return c.p.nodes[e].d +} + +// ---------------------------------------------------------------- expressions + +IsMulti :: (c: *Compiler, e: s32) -> bool { + kind := c.p.nodes[e].kind + return kind == E_CALL || kind == E_METHOD || kind == E_VARARG +} + +// A non-captured local's register, or -1. +PlainLocalReg :: (c: *Compiler, fs: *FuncState, e: s32) -> s32 { + if c.p.nodes[e].kind != E_NAME || c.p.nodes[e].c != 1 { return -1 } + local := c.p.nodes[e].d + if c.funcs[fs.info].locals[local].captured { return -1 } + return c.funcs[fs.info].locals[local].reg +} + +AnyReg :: (c: *Compiler, fs: *FuncState, e: s32) -> s32 { + r := PlainLocalReg(c, fs, e) + if r >= 0 { return r } + r = Reserve(fs, 1) + Expr(c, fs, e, r) + return r +} + +RK :: (c: *Compiler, fs: *FuncState, e: s32) -> s32 { + kind := c.p.nodes[e].kind + if kind == E_NUMBER { return KOperand(NumberK(fs, c.p.nodes[e].num)) } + if kind == E_STRING { return KOperand(StringK(fs, c.p.nodes[e].str)) } + if kind == E_NIL { return KOperand(AddConstant(fs, NilValue())) } + if kind == E_TRUE { return KOperand(AddConstant(fs, BoolValue(true))) } + if kind == E_FALSE { return KOperand(AddConstant(fs, BoolValue(false))) } + return AnyReg(c, fs, e) +} + +// Compile `e` so its single value ends in register dst. +Expr :: (c: *Compiler, fs: *FuncState, e: s32, dst: s32) { + node := c.p.nodes[e] + saved_line := fs.line + fs.line = node.line + saved := fs.freereg + kind := node.kind + if kind == E_NIL { + Emit(fs, OP_LOADNIL, dst, 1, 0) + } else if kind == E_TRUE { + Emit(fs, OP_LOADBOOL, dst, 1, 0) + } else if kind == E_FALSE { + Emit(fs, OP_LOADBOOL, dst, 0, 0) + } else if kind == E_NUMBER { + Emit(fs, OP_LOADK, dst, NumberK(fs, node.num), 0) + } else if kind == E_STRING { + Emit(fs, OP_LOADK, dst, StringK(fs, node.str), 0) + } else if kind == E_VARARG { + Emit(fs, OP_VARARG, dst, 2, 0) + } else if kind == E_NAME { + scope := node.c + if scope == 1 { + local := node.d + reg := c.funcs[fs.info].locals[local].reg + if c.funcs[fs.info].locals[local].captured { + Emit(fs, OP_GETBOX, dst, reg, 0) + } else if reg != dst { + Emit(fs, OP_MOVE, dst, reg, 0) + } + } else if scope == 2 { + Emit(fs, OP_GETUPVAL, dst, node.d, 0) + } else { + Emit(fs, OP_GETGLOBAL, dst, StringK(fs, node.str), 0) + } + } else if kind == E_INDEX { + t := AnyReg(c, fs, node.a) + if c.p.nodes[node.b].kind == E_STRING { + Emit(fs, OP_GETFIELD, dst, t, StringK(fs, c.p.nodes[node.b].str)) + } else { + k := RK(c, fs, node.b) + Emit(fs, OP_GETTABLE, dst, t, k) + } + } else if kind == E_CALL || kind == E_METHOD { + // Reuse dst as the call base when it is the topmost register. + if dst == fs.freereg - 1 && dst >= fs.nactive { + fs.freereg = dst + Call(c, fs, e, 1) + } else { + base := fs.freereg + Call(c, fs, e, 1) + Emit(fs, OP_MOVE, dst, base, 0) + } + } else if kind == E_PAREN { + Expr(c, fs, node.a, dst) + } else if kind == E_FUNCTION { + index := CompileFunction(c, fs, e) + Emit(fs, OP_CLOSURE, dst, index, 0) + } else if kind == E_TABLE { + Table(c, fs, e, dst) + } else if kind == E_AND || kind == E_OR { + Expr(c, fs, node.a, dst) + fs.line = node.line + jump := Emit(fs, ifx kind == E_AND then OP_JF else OP_JT, -1, dst, 0) + Expr(c, fs, node.b, dst) + PatchHere(fs, jump) + } else if kind == E_UNOP { + r := AnyReg(c, fs, node.a) + fs.line = node.line + op: s32 = ifx node.op == OPR_MINUS then OP_UNM else (ifx node.op == OPR_NOT then OP_NOT else OP_LEN) + Emit(fs, op, dst, r, 0) + } else if kind == E_BINOP { + op := cast(s32) node.op + if op == OPR_CONCAT { + ConcatExpr(c, fs, e, dst) + } else { + left := node.a + right := node.b + if op == OPR_GT || op == OPR_GE { + left = node.b + right = node.a + } + rb := RK(c, fs, left) + rc := RK(c, fs, right) + fs.line = node.line + Emit(fs, ArithOpcode(op), dst, rb, rc) + } + } + fs.freereg = saved + fs.line = saved_line +} + +ArithOpcode :: (op: s32) -> s32 { + if op == OPR_ADD { return OP_ADD } + if op == OPR_SUB { return OP_SUB } + if op == OPR_MUL { return OP_MUL } + if op == OPR_DIV { return OP_DIV } + if op == OPR_MOD { return OP_MOD } + if op == OPR_POW { return OP_POW } + if op == OPR_EQ { return OP_EQ } + if op == OPR_NE { return OP_NE } + if op == OPR_LT || op == OPR_GT { return OP_LT } + return OP_LE +} + +ConcatExpr :: (c: *Compiler, fs: *FuncState, e: s32, dst: s32) { + first := fs.freereg + count: s32 = 0 + at := e + while c.p.nodes[at].kind == E_BINOP && c.p.nodes[at].op == OPR_CONCAT { + r := Reserve(fs, 1) + Expr(c, fs, c.p.nodes[at].a, r) + count += 1 + at = c.p.nodes[at].b + } + r := Reserve(fs, 1) + Expr(c, fs, at, r) + fs.line = c.p.nodes[e].line + Emit(fs, OP_CONCAT, dst, first, first + count) +} + +// Compile a call with its function at R[freereg]. want: results, -1 for all. +Call :: (c: *Compiler, fs: *FuncState, e: s32, want: s32) { + node := c.p.nodes[e] + base := Reserve(fs, 1) + if node.kind == E_METHOD { + object := AnyReg(c, fs, node.a) + Reserve(fs, 1) + fs.freereg = base + 2 + fs.line = node.line + Emit(fs, OP_SELF, base, object, KOperand(StringK(fs, node.str))) + } else { + Expr(c, fs, node.a, base) + } + nargs := ExprList(c, fs, node.b, -1) + fs.line = node.line + b: s32 = 0 + if nargs >= 0 { + if node.kind == E_METHOD { nargs += 1 } + b = nargs + 1 + } + Emit(fs, OP_CALL, base, b, want + 1) + fs.freereg = base + (ifx want > 0 then want else 0) + if fs.freereg > fs.max_stack { fs.max_stack = fs.freereg } +} + +// Evaluate a multi-value expression into R[freereg..]: want -1 keeps all. +ExprMulti :: (c: *Compiler, fs: *FuncState, e: s32, want: s32) { + node := c.p.nodes[e] + if node.kind == E_VARARG { + base := fs.freereg + fs.line = node.line + Emit(fs, OP_VARARG, base, want + 1, 0) + if want > 0 { Reserve(fs, want) } + return + } + Call(c, fs, e, want) +} + +// Evaluate a list into consecutive registers from freereg, adjusted to +// `want` values (-1: keep everything, ending in a multi-value). Returns the +// value count, or -1 when the count is only known at run time. +ExprList :: (c: *Compiler, fs: *FuncState, first: s32, want: s32) -> s32 { + base := fs.freereg + n: s32 = 0 + e := first + while e >= 0 { + last := c.p.nodes[e].next < 0 + if last && IsMulti(c, e) && (want < 0 || want > n) { + if want < 0 { + ExprMulti(c, fs, e, -1) + return -1 + } + ExprMulti(c, fs, e, want - n) + fs.freereg = base + want + return want + } + r := Reserve(fs, 1) + Expr(c, fs, e, r) + n += 1 + e = c.p.nodes[e].next + } + if want >= 0 { + if n < want { + Emit(fs, OP_LOADNIL, base + n, want - n, 0) + Reserve(fs, want - n) + } + fs.freereg = base + want + return want + } + return n +} + +Table :: (c: *Compiler, fs: *FuncState, e: s32, dst: s32) { + t := dst + moved := false + if dst != fs.freereg - 1 || dst < fs.nactive { + t = Reserve(fs, 1) + moved = true + } + narr: s32 = 0 + nhash: s32 = 0 + field := c.p.nodes[e].a + while field >= 0 { + if c.p.nodes[field].kind == F_ITEM { narr += 1 } else { nhash += 1 } + field = c.p.nodes[field].next + } + fs.line = c.p.nodes[e].line + Emit(fs, OP_NEWTABLE, t, narr, nhash) + pending: s32 = 0 + stored: s32 = 0 + field = c.p.nodes[e].a + while field >= 0 { + node := c.p.nodes[field] + if node.kind == F_ITEM { + last := node.next < 0 + if last && IsMulti(c, node.a) { + ExprMulti(c, fs, node.a, -1) + fs.line = node.line + Emit(fs, OP_SETLIST, t, 0, stored) + fs.freereg = t + 1 + pending = 0 + field = node.next + continue + } + r := Reserve(fs, 1) + Expr(c, fs, node.a, r) + pending += 1 + if pending == LFIELDS_PER_FLUSH { + fs.line = node.line + Emit(fs, OP_SETLIST, t, pending, stored) + stored += pending + pending = 0 + fs.freereg = t + 1 + } + } else { + saved := fs.freereg + value := RK(c, fs, node.b) + fs.line = node.line + if c.p.nodes[node.a].kind == E_STRING { + Emit(fs, OP_SETFIELD, t, StringK(fs, c.p.nodes[node.a].str), value) + } else { + key := RK(c, fs, node.a) + Emit(fs, OP_SETTABLE, t, key, value) + } + fs.freereg = saved + } + field = node.next + } + if pending > 0 { + Emit(fs, OP_SETLIST, t, pending, stored) + } + fs.freereg = t + 1 + if moved { Emit(fs, OP_MOVE, dst, t, 0) } +} + +// Emit code that jumps when `e` is truthy == jump_when; returns the list. +CondJump :: (c: *Compiler, fs: *FuncState, e: s32, jump_when: bool) -> s32 { + node := c.p.nodes[e] + saved := fs.freereg + saved_line := fs.line + fs.line = node.line + result: s32 = -1 + kind := node.kind + if kind == E_AND { + if jump_when { + skip := CondJump(c, fs, node.a, false) + result = CondJump(c, fs, node.b, true) + PatchHere(fs, skip) + } else { + first := CondJump(c, fs, node.a, false) + second := CondJump(c, fs, node.b, false) + result = Concat(fs, first, second) + } + } else if kind == E_OR { + if jump_when { + first := CondJump(c, fs, node.a, true) + second := CondJump(c, fs, node.b, true) + result = Concat(fs, first, second) + } else { + skip := CondJump(c, fs, node.a, true) + result = CondJump(c, fs, node.b, false) + PatchHere(fs, skip) + } + } else if kind == E_UNOP && node.op == OPR_NOT { + result = CondJump(c, fs, node.a, !jump_when) + } else if kind == E_PAREN { + result = CondJump(c, fs, node.a, jump_when) + } else if kind == E_NIL || kind == E_FALSE { + if !jump_when { result = EmitJump(fs) } + } else if kind == E_TRUE || kind == E_NUMBER || kind == E_STRING || kind == E_FUNCTION || kind == E_TABLE { + if kind == E_FUNCTION || kind == E_TABLE { + // Still evaluate for side effects of nested expressions. + r := Reserve(fs, 1) + Expr(c, fs, e, r) + } + if jump_when { result = EmitJump(fs) } + } else if kind == E_BINOP && node.op >= OPR_NE && node.op <= OPR_GE { + op := cast(s32) node.op + left := node.a + right := node.b + if op == OPR_GT || op == OPR_GE { + left = node.b + right = node.a + } + rb := RK(c, fs, left) + rc := RK(c, fs, right) + fs.line = node.line + opcode: s32 + if op == OPR_EQ { opcode = ifx jump_when then OP_JEQ else OP_JNE } + else if op == OPR_NE { opcode = ifx jump_when then OP_JNE else OP_JEQ } + else if op == OPR_LT || op == OPR_GT { opcode = ifx jump_when then OP_JLT else OP_JNLT } + else { opcode = ifx jump_when then OP_JLE else OP_JNLE } + result = Emit(fs, opcode, -1, rb, rc) + } else { + r := AnyReg(c, fs, e) + fs.line = node.line + result = Emit(fs, ifx jump_when then OP_JT else OP_JF, -1, r, 0) + } + fs.freereg = saved + fs.line = saved_line + return result +} + +// ---------------------------------------------------------------- statements + +ActivateLocal :: (c: *Compiler, fs: *FuncState, decl: s32, reg: s32) { + local := c.p.nodes[decl].d + c.funcs[fs.info].locals[local].reg = reg + lv: LuaLocVar + lv.name = c.p.nodes[decl].str + lv.reg = reg + lv.start_pc = PC(fs) + lv.end_pc = -1 + c.funcs[fs.info].locals[local].locvar = cast(s32) fs.locvars.count + VecPush(fs.locvars, lv) + VecPush(fs.active_locals, local) + if c.funcs[fs.info].locals[local].captured { + Emit(fs, OP_NEWBOX, reg, 0, 0) + } +} + +EnterBlock :: (fs: *FuncState) -> s32 { + fs.depth += 1 + return cast(s32) fs.active_locals.count +} + +LeaveBlock :: (c: *Compiler, fs: *FuncState, mark: s32, reg_mark: s32) { + i := fs.active_locals.count - 1 + while i >= mark { + local := fs.active_locals[i] + lv := c.funcs[fs.info].locals[local].locvar + fs.locvars[lv].end_pc = PC(fs) + i -= 1 + } + VecResize(fs.active_locals, cast(s64) mark) + // Labels of this block go out of scope; pending gotos move outward. + j: s64 = fs.labels.count - 1 + while j >= 0 && fs.labels[j].depth >= fs.depth { + j -= 1 + } + VecResize(fs.labels, j + 1) + g: s64 = 0 + while g < fs.gotos.count { + if fs.gotos[g].depth >= fs.depth { fs.gotos[g].depth = fs.depth - 1 } + g += 1 + } + fs.depth -= 1 + fs.nactive = reg_mark + fs.freereg = reg_mark +} + +Block :: (c: *Compiler, fs: *FuncState, first: s32) -> bool { + mark := EnterBlock(fs) + reg_mark := fs.nactive + ok := Statements(c, fs, first) + LeaveBlock(c, fs, mark, reg_mark) + return ok +} + +Statements :: (c: *Compiler, fs: *FuncState, first: s32) -> bool { + s := first + while s >= 0 { + if !Statement(c, fs, s) { return false } + fs.freereg = fs.nactive + s = c.p.nodes[s].next + } + return true +} + +CompileError :: (c: *Compiler, line: s32, message: string) -> bool { + return ResolveError(c, line, message) +} + +StoreTo :: (c: *Compiler, fs: *FuncState, target: s32, value: s32) { + // value: an RK operand. + node := c.p.nodes[target] + fs.line = node.line + if node.kind == E_NAME { + if node.c == 1 { + local := node.d + reg := c.funcs[fs.info].locals[local].reg + if c.funcs[fs.info].locals[local].captured { + Emit(fs, OP_SETBOX, reg, value, 0) + } else { + if value < 0 { Emit(fs, OP_LOADK, reg, -1 - value, 0) } else if value != reg { Emit(fs, OP_MOVE, reg, value, 0) } + } + return + } + r := value + if r < 0 { + r = Reserve(fs, 1) + Emit(fs, OP_LOADK, r, -1 - value, 0) + } + if node.c == 2 { + Emit(fs, OP_SETUPVAL, r, node.d, 0) + } else { + Emit(fs, OP_SETGLOBAL, r, StringK(fs, node.str), 0) + } + } +} + +SafeDirect :: (c: *Compiler, e: s32) -> bool { + kind := c.p.nodes[e].kind + return kind != E_TABLE && kind != E_AND && kind != E_OR && kind != E_CALL && kind != E_METHOD +} + +Assign :: (c: *Compiler, fs: *FuncState, s: s32) -> bool { + first := c.p.nodes[s].a + exprs := c.p.nodes[s].b + if c.p.nodes[first].next < 0 && exprs >= 0 && c.p.nodes[exprs].next < 0 { + // Single assignment. + target := c.p.nodes[first] + if target.kind == E_INDEX { + t := AnyReg(c, fs, target.a) + if c.p.nodes[target.b].kind == E_STRING { + k := StringK(fs, c.p.nodes[target.b].str) + v := RK(c, fs, exprs) + fs.line = target.line + Emit(fs, OP_SETFIELD, t, k, v) + } else { + k := RK(c, fs, target.b) + v := RK(c, fs, exprs) + fs.line = target.line + Emit(fs, OP_SETTABLE, t, k, v) + } + return true + } + reg := PlainLocalReg(c, fs, first) + if reg >= 0 { + if SafeDirect(c, exprs) { + Expr(c, fs, exprs, reg) + } else { + r := Reserve(fs, 1) + Expr(c, fs, exprs, r) + Emit(fs, OP_MOVE, reg, r, 0) + } + return true + } + v := RK(c, fs, exprs) + StoreTo(c, fs, first, v) + return true + } + // Multiple assignment: evaluate target prefixes, then values, then store. + count: s32 = 0 + target := first + while target >= 0 { + node := c.p.nodes[target] + if node.kind == E_INDEX { + t := Reserve(fs, 1) + Expr(c, fs, node.a, t) + k := Reserve(fs, 1) + Expr(c, fs, node.b, k) + c.p.nodes[target].e = t + } + count += 1 + target = node.next + } + base := fs.freereg + ExprList(c, fs, exprs, count) + i := count - 1 + while i >= 0 { + // Walk to the i-th target. + at := first + j: s32 = 0 + while j < i { at = c.p.nodes[at].next; j += 1 } + node := c.p.nodes[at] + if node.kind == E_INDEX { + fs.line = node.line + Emit(fs, OP_SETTABLE, node.e, node.e + 1, base + i) + } else { + StoreTo(c, fs, at, base + i) + } + i -= 1 + } + return true +} + +LocalStatement :: (c: *Compiler, fs: *FuncState, s: s32) -> bool { + count: s32 = 0 + decl := c.p.nodes[s].a + while decl >= 0 { count += 1; decl = c.p.nodes[decl].next } + base := fs.freereg + exprs := c.p.nodes[s].b + if exprs < 0 { + fs.line = c.p.nodes[s].line + Emit(fs, OP_LOADNIL, base, count, 0) + Reserve(fs, count) + } else if count == 1 && c.p.nodes[exprs].next < 0 && !IsMulti(c, exprs) { + r := Reserve(fs, 1) + Expr(c, fs, exprs, r) + } else { + ExprList(c, fs, exprs, count) + } + decl = c.p.nodes[s].a + i: s32 = 0 + while decl >= 0 { + ActivateLocal(c, fs, decl, base + i) + i += 1 + decl = c.p.nodes[decl].next + } + fs.nactive = base + count + fs.freereg = fs.nactive + return true +} + +LocalFunction :: (c: *Compiler, fs: *FuncState, s: s32) -> bool { + decl := c.p.nodes[s].a + reg := Reserve(fs, 1) + local := c.p.nodes[decl].d + captured := c.funcs[fs.info].locals[local].captured + fs.line = c.p.nodes[s].line + if captured { Emit(fs, OP_LOADNIL, reg, 1, 0) } + ActivateLocal(c, fs, decl, reg) + fs.nactive = reg + 1 + index := CompileFunction(c, fs, c.p.nodes[s].b) + if captured { + t := Reserve(fs, 1) + Emit(fs, OP_CLOSURE, t, index, 0) + Emit(fs, OP_SETBOX, reg, t, 0) + } else { + Emit(fs, OP_CLOSURE, reg, index, 0) + } + return true +} + +FunctionStatement :: (c: *Compiler, fs: *FuncState, s: s32) -> bool { + target := c.p.nodes[s].a + function := c.p.nodes[s].b + node := c.p.nodes[target] + if node.kind == E_INDEX { + t := AnyReg(c, fs, node.a) + r := Reserve(fs, 1) + Expr(c, fs, function, r) + fs.line = c.p.nodes[s].line + Emit(fs, OP_SETFIELD, t, StringK(fs, c.p.nodes[node.b].str), r) + return true + } + reg := PlainLocalReg(c, fs, target) + if reg >= 0 { + Expr(c, fs, function, reg) + return true + } + r := Reserve(fs, 1) + Expr(c, fs, function, r) + StoreTo(c, fs, target, r) + return true +} + +Return :: (c: *Compiler, fs: *FuncState, s: s32) -> bool { + first := c.p.nodes[s].a + fs.line = c.p.nodes[s].line + if first < 0 { + Emit(fs, OP_RETURN, 0, 1, 0) + return true + } + if c.p.nodes[first].next < 0 { + kind := c.p.nodes[first].kind + if kind == E_CALL || kind == E_METHOD { + base := fs.freereg + Call(c, fs, first, -1) + last := fs.code.count - 1 + fs.code[last].op = OP_TAILCALL + Emit(fs, OP_RETURN, base, 0, 0) + return true + } + if kind != E_VARARG { + r := AnyReg(c, fs, first) + fs.line = c.p.nodes[s].line + Emit(fs, OP_RETURN, r, 2, 0) + return true + } + } + base := fs.freereg + n := ExprList(c, fs, first, -1) + fs.line = c.p.nodes[s].line + Emit(fs, OP_RETURN, base, n + 1, 0) + return true +} + +LoopStart :: (fs: *FuncState) -> s64 { return fs.breaks.count } + +LoopEnd :: (fs: *FuncState, mark: s64) { + i := mark + while i < fs.breaks.count { + fs.code[fs.breaks[i]].a = PC(fs) + i += 1 + } + VecResize(fs.breaks, mark) + VecResize(fs.loop_breaks, fs.loop_breaks.count - 1) +} + +Statement :: (c: *Compiler, fs: *FuncState, s: s32) -> bool { + node := c.p.nodes[s] + fs.line = node.line + kind := node.kind + if kind == S_LOCAL { return LocalStatement(c, fs, s) } + if kind == S_LOCALFUNC { return LocalFunction(c, fs, s) } + if kind == S_ASSIGN { return Assign(c, fs, s) } + if kind == S_FUNCTION { return FunctionStatement(c, fs, s) } + if kind == S_CALL { + Call(c, fs, node.a, 0) + return true + } + if kind == S_DO { return Block(c, fs, node.a) } + if kind == S_RETURN { return Return(c, fs, s) } + if kind == S_BREAK { + if fs.loop_breaks.count == 0 { return CompileError(c, node.line, "no loop to break") } + jump := EmitJump(fs) + VecPush(fs.breaks, jump) + return true + } + if kind == S_GOTO { + // Backward jump to a visible label? + i := fs.labels.count - 1 + while i >= 0 { + if fs.labels[i].name == node.str { + Emit(fs, OP_JMP, fs.labels[i].pc, 1, 0) + return true + } + i -= 1 + } + g: GotoInfo + g.name = node.str + g.pc = EmitJump(fs) + g.line = node.line + g.depth = fs.depth + VecPush(fs.gotos, g) + return true + } + if kind == S_LABEL { + i: s64 = 0 + while i < fs.labels.count { + if fs.labels[i].name == node.str && fs.labels[i].depth == fs.depth { + return CompileError(c, node.line, "label already defined") + } + i += 1 + } + label: LabelInfo + label.name = node.str + label.pc = PC(fs) + label.depth = fs.depth + VecPush(fs.labels, label) + // Resolve pending forward gotos from this block or nested blocks. + g: s64 = 0 + while g < fs.gotos.count { + if fs.gotos[g].name == node.str && fs.gotos[g].depth >= fs.depth { + fs.code[fs.gotos[g].pc].a = label.pc + fs.gotos[g] = fs.gotos[fs.gotos.count - 1] + VecResize(fs.gotos, fs.gotos.count - 1) + continue + } + g += 1 + } + return true + } + if kind == S_WHILE { + start := PC(fs) + exit := CondJump(c, fs, node.a, false) + mark := LoopStart(fs) + VecPush(fs.loop_breaks, 1) + if !Block(c, fs, node.b) { return false } + fs.line = node.line + Emit(fs, OP_JMP, start, 1, 0) + PatchHere(fs, exit) + LoopEnd(fs, mark) + return true + } + if kind == S_REPEAT { + start := PC(fs) + mark := LoopStart(fs) + VecPush(fs.loop_breaks, 1) + block_mark := EnterBlock(fs) + reg_mark := fs.nactive + if !Statements(c, fs, node.a) { return false } + back := CondJump(c, fs, node.b, false) + PatchList(fs, back, start) + // Mark the backward jumps for hook checks. + LeaveBlock(c, fs, block_mark, reg_mark) + LoopEnd(fs, mark) + return true + } + if kind == S_IF { + exits: s32 = -1 + current := s + while true { + branch := c.p.nodes[current] + fs.line = branch.line + skip := CondJump(c, fs, branch.a, false) + if !Block(c, fs, branch.b) { return false } + other := branch.c + if other < 0 { + PatchHere(fs, skip) + break + } + exits = Concat(fs, exits, EmitJump(fs)) + PatchHere(fs, skip) + if c.p.nodes[other].kind == S_IF { + current = other + continue + } + if !Block(c, fs, c.p.nodes[other].a) { return false } + break + } + PatchHere(fs, exits) + return true + } + if kind == S_NUMFOR { + base := fs.freereg + Reserve(fs, 3) + Expr(c, fs, node.b, base) + Expr(c, fs, node.c, base + 1) + if node.d >= 0 { + Expr(c, fs, node.d, base + 2) + } else { + Emit(fs, OP_LOADK, base + 2, NumberK(fs, 1.0), 0) + } + fs.nactive = base + 3 + fs.freereg = base + 3 + fs.line = node.line + prep := Emit(fs, OP_FORPREP, base, -1, 0) + mark := LoopStart(fs) + VecPush(fs.loop_breaks, 1) + block_mark := EnterBlock(fs) + reg_mark := fs.nactive + body := PC(fs) + Reserve(fs, 1) + ActivateLocal(c, fs, node.a, base + 3) + fs.nactive = base + 4 + if !Statements(c, fs, node.e) { return false } + LeaveBlock(c, fs, block_mark, reg_mark) + fs.line = node.line + loop := Emit(fs, OP_FORLOOP, base, body, 0) + fs.code[prep].b = loop + LoopEnd(fs, mark) + fs.nactive = base + fs.freereg = base + return true + } + if kind == S_GENFOR { + base := fs.freereg + ExprList(c, fs, node.b, 3) + fs.nactive = base + 3 + fs.freereg = base + 3 + nvars: s32 = 0 + decl := node.a + while decl >= 0 { nvars += 1; decl = c.p.nodes[decl].next } + fs.line = node.line + jump := EmitJump(fs) + mark := LoopStart(fs) + VecPush(fs.loop_breaks, 1) + block_mark := EnterBlock(fs) + reg_mark := fs.nactive + body := PC(fs) + Reserve(fs, nvars) + decl = node.a + i: s32 = 0 + while decl >= 0 { + ActivateLocal(c, fs, decl, base + 3 + i) + i += 1 + decl = c.p.nodes[decl].next + } + fs.nactive = base + 3 + nvars + if !Statements(c, fs, node.c) { return false } + LeaveBlock(c, fs, block_mark, reg_mark) + fs.line = node.line + PatchHere(fs, jump) + Emit(fs, OP_TFORCALL, base, 0, nvars) + if base + 3 + nvars > fs.max_stack { fs.max_stack = base + 3 + nvars } + // The generic call copies f, s, ctl to base+3..base+5; next() writes two. + if base + 6 > fs.max_stack { fs.max_stack = base + 6 } + Emit(fs, OP_TFORLOOP, base, body, 0) + LoopEnd(fs, mark) + fs.nactive = base + fs.freereg = base + return true + } + return true +} + +// ---------------------------------------------------------------- functions + +ChunkSource :: (c: *Compiler) -> s32 { return c.source } + +// Compile a function node into a new prototype; returns its index in the +// enclosing prototype's list. +CompileFunction :: (c: *Compiler, parent: *FuncState, e: s32) -> s32 { + proto := BuildProto(c, e, parent) + index := cast(s32) parent.protos.count + VecPush(parent.protos, proto) + return index +} + +BuildProto :: (c: *Compiler, e: s32, parent: *FuncState) -> s32 { + node := c.p.nodes[e] + fs: FuncState + fs.info = node.d + fs.line = node.line + fs.depth = 0 + // Parameters occupy the first registers. + nparams: s32 = 0 + param := node.a + while param >= 0 { + Reserve(*fs, 1) + ActivateLocal(c, *fs, param, nparams) + nparams += 1 + param = c.p.nodes[param].next + } + fs.nactive = nparams + fs.freereg = nparams + if fs.max_stack < 2 { fs.max_stack = 2 } + ok := Statements(c, *fs, node.b) + fs.line = node.e + Emit(*fs, OP_RETURN, 0, 1, 0) + if ok && fs.gotos.count > 0 { + message: Vec(u8) + BuilderAppend(message, "no visible label '") + BuilderAppend(message, StrView(c.L, fs.gotos[0].name)) + BuilderAppend(message, "' for goto") + CompileError(c, fs.gotos[0].line, BytesView(*message)) + VecFree(message) + } + // Upvalue descriptors refer to parent registers or parent upvalues. + info := fs.info + i: s64 = 0 + while i < c.funcs[info].upvals.count { + desc: LuaUpvalDesc + desc.from_local = c.funcs[info].upvals[i].from_local + if desc.from_local { + parent_info := c.funcs[info].parent + desc.index = c.funcs[parent_info].locals[c.funcs[info].upvals[i].index].reg + } else { + desc.index = c.funcs[info].upvals[i].index + } + VecPush(fs.upvals, desc) + VecPush(fs.upval_names, c.funcs[info].upvals[i].name) + i += 1 + } + h := NewProtoObject(c.L) + VecSwap(c.L.protos[h].code, fs.code) + VecSwap(c.L.protos[h].lines, fs.lines) + VecSwap(c.L.protos[h].constants, fs.constants) + VecSwap(c.L.protos[h].protos, fs.protos) + VecSwap(c.L.protos[h].upvals, fs.upvals) + VecSwap(c.L.protos[h].upval_names, fs.upval_names) + VecSwap(c.L.protos[h].locvars, fs.locvars) + c.L.protos[h].num_params = nparams + c.L.protos[h].is_vararg = node.c == 1 + c.L.protos[h].max_stack = fs.max_stack + 1 + c.L.protos[h].line_defined = node.line + c.L.protos[h].last_line = node.e + c.L.protos[h].source = c.source + c.L.allocated += c.L.protos[h].code.count * 20 + c.L.protos[h].constants.count * 16 + FreeFuncState(*fs) + return h +} + +FreeFuncState :: (fs: *FuncState) { + VecFree(fs.code) + VecFree(fs.lines) + VecFree(fs.constants) + VecFree(fs.protos) + VecFree(fs.upvals) + VecFree(fs.upval_names) + VecFree(fs.locvars) + VecFree(fs.breaks) + VecFree(fs.loop_breaks) + VecFree(fs.gotos) + VecFree(fs.labels) + VecFree(fs.active_locals) +} + +// Parse and compile a chunk. Returns the main prototype or -1 with the +// message in `error`. No garbage collection runs while compiling. +CompileChunk :: (L: *LuaState, text: string, chunkname: string, error: *Vec(u8)) -> s32 { + parser: Parser + p := *parser + p.lx.L = L + p.lx.src = text + p.lx.line = 1 + p.lx.chunk = chunkname + // Skip a shebang line. + if text.count > 0 && text[0] == #char "#" { + while p.lx.pos < text.count && text[p.lx.pos] != 10 { p.lx.pos += 1 } + } + NextToken(*p.lx) + main := AddNode(p, E_FUNCTION, 0) + p.nodes[main].c = 1 + body := ParseBlock(p) + p.nodes[main].b = body + p.nodes[main].e = p.lx.line + if !p.lx.failed && p.lx.tok.kind != TK_EOS { + SyntaxError(p, "'' expected") + } + result: s32 = -1 + if !p.lx.failed { + compiler: Compiler + c := *compiler + c.p = p + c.L = L + c.source = Intern(L, chunkname) + if ResolveFunction(c, -1, main) { + dummy: FuncState + result = BuildProto(c, main, *dummy) + FreeFuncState(*dummy) + } + if p.lx.failed { result = -1 } + i: s64 = 0 + while i < c.funcs.count { + VecFree(c.funcs[i].locals) + VecFree(c.funcs[i].upvals) + VecFree(c.funcs[i].active) + i += 1 + } + VecFree(c.funcs) + } + if p.lx.failed { + VecClear(<= 0 { L.strings[h].mark = 1 } +} + +MarkObject :: (L: *LuaState, t: u8, h: s32) { + if h < 0 { return } + if t == LUA_TTABLE { + if L.tables[h].mark != 0 { return } + L.tables[h].mark = 1 + } else if t == LUA_TFUNCTION { + if L.closures[h].mark != 0 { return } + L.closures[h].mark = 1 + } else if t == LUA_TUSERDATA { + if L.userdata[h].mark != 0 { return } + L.userdata[h].mark = 1 + } else if t == LUA_TTHREAD { + if L.threads[h].mark != 0 { return } + L.threads[h].mark = 1 + } else if t == LUA_TBOX { + if L.boxes[h].mark != 0 { return } + L.boxes[h].mark = 1 + } else if t == LUA_TPROTO { + if L.protos[h].mark != 0 { return } + L.protos[h].mark = 1 + } else { + return + } + VecPush(L.gray, ObjectValue(t, h)) +} + +MarkValue :: (L: *LuaState, v: LuaValue) #inline { + if v.t == LUA_TSTRING { L.strings[v.h].mark = 1; return } + if v.t >= LUA_TTABLE && v.t != LUA_TLIGHTUSERDATA { MarkObject(L, v.t, v.h) } +} + +// Weak tables keep only strings (and plain values) in their weak parts. +MarkWeakPart :: (L: *LuaState, v: LuaValue) #inline { + if v.t == LUA_TSTRING { L.strings[v.h].mark = 1 } +} + +WeakMode :: (L: *LuaState, h: s32) -> (keys: bool, values: bool) { + meta := L.tables[h].meta + if meta < 0 { return false, false } + mode := GetStr(L, meta, L.tm_names[TM_MODE]) + if mode.t != LUA_TSTRING { return false, false } + keys := false + values := false + i: s64 = 0 + while i < L.strings[mode.h].bytes.count { + c := L.strings[mode.h].bytes[i] + if c == #char "k" { keys = true } + if c == #char "v" { values = true } + i += 1 + } + return keys, values +} + +TraverseTable :: (L: *LuaState, h: s32) { + meta := L.tables[h].meta + if meta >= 0 { MarkObject(L, LUA_TTABLE, meta) } + weak_keys, weak_values := WeakMode(L, h) + if weak_keys || weak_values { VecPush(L.weak, h) } + i: s64 = 0 + n := L.tables[h].arr.count + while i < n { + v := L.tables[h].arr[i] + if weak_values { MarkWeakPart(L, v) } else { MarkValue(L, v) } + i += 1 + } + i = 0 + n = L.tables[h].nodes.count + while i < n { + node := L.tables[h].nodes[i] + if node.value.t != LUA_TNIL { + if weak_keys { MarkWeakPart(L, node.key) } else { MarkValue(L, node.key) } + if weak_values { MarkWeakPart(L, node.value) } else { MarkValue(L, node.value) } + } + i += 1 + } +} + +TraverseClosure :: (L: *LuaState, h: s32) { + if L.closures[h].proto >= 0 { MarkObject(L, LUA_TPROTO, L.closures[h].proto) } + if L.closures[h].env >= 0 { MarkObject(L, LUA_TTABLE, L.closures[h].env) } + MarkString(L, L.closures[h].name) + i: s64 = 0 + while i < L.closures[h].upvals.count { + MarkObject(L, LUA_TBOX, L.closures[h].upvals[i]) + i += 1 + } + i = 0 + while i < L.closures[h].native_upvals.count { + MarkValue(L, L.closures[h].native_upvals[i]) + i += 1 + } +} + +TraverseProto :: (L: *LuaState, h: s32) { + MarkString(L, L.protos[h].source) + i: s64 = 0 + while i < L.protos[h].constants.count { + MarkValue(L, L.protos[h].constants[i]) + i += 1 + } + i = 0 + while i < L.protos[h].protos.count { + MarkObject(L, LUA_TPROTO, L.protos[h].protos[i]) + i += 1 + } + i = 0 + while i < L.protos[h].upval_names.count { + MarkString(L, L.protos[h].upval_names[i]) + i += 1 + } + i = 0 + while i < L.protos[h].locvars.count { + MarkString(L, L.protos[h].locvars[i].name) + i += 1 + } +} + +TraverseThread :: (L: *LuaState, h: s32) { + if L.threads[h].env >= 0 { MarkObject(L, LUA_TTABLE, L.threads[h].env) } + top := L.threads[h].top + if top > L.threads[h].stack.count { top = L.threads[h].stack.count } + i: s64 = 0 + while i < top { + MarkValue(L, L.threads[h].stack[i]) + i += 1 + } + i = 0 + while i < L.threads[h].frames.count { + MarkObject(L, LUA_TFUNCTION, L.threads[h].frames[i].closure) + i += 1 + } + i = 0 + while i < L.threads[h].handlers.count { + MarkValue(L, L.threads[h].handlers[i].handler) + i += 1 + } +} + +Propagate :: (L: *LuaState) { + while L.gray.count > 0 { + v := L.gray[L.gray.count - 1] + VecResize(L.gray, L.gray.count - 1) + t := v.t + if t == LUA_TTABLE { + TraverseTable(L, v.h) + } else if t == LUA_TFUNCTION { + TraverseClosure(L, v.h) + } else if t == LUA_TPROTO { + TraverseProto(L, v.h) + } else if t == LUA_TBOX { + MarkValue(L, L.boxes[v.h].value) + } else if t == LUA_TUSERDATA { + if L.userdata[v.h].meta >= 0 { MarkObject(L, LUA_TTABLE, L.userdata[v.h].meta) } + if L.userdata[v.h].env >= 0 { MarkObject(L, LUA_TTABLE, L.userdata[v.h].env) } + } else if t == LUA_TTHREAD { + TraverseThread(L, v.h) + } + } +} + +MarkRoots :: (L: *LuaState) { + MarkObject(L, LUA_TTABLE, L.globals) + MarkObject(L, LUA_TTABLE, L.registry) + MarkObject(L, LUA_TTHREAD, L.main) + MarkObject(L, LUA_TTHREAD, L.cur) + MarkObject(L, LUA_TFUNCTION, L.next_fn) + MarkObject(L, LUA_TFUNCTION, L.inext_fn) + MarkObject(L, LUA_TTABLE, L.file_meta) + i: s64 = 0 + while i < L.resumers.count { + MarkObject(L, LUA_TTHREAD, L.resumers[i]) + i += 1 + } + i = 0 + while i < 11 { + if L.type_meta[i] >= 0 { MarkObject(L, LUA_TTABLE, L.type_meta[i]) } + i += 1 + } + i = 0 + while i < TM_COUNT { + MarkString(L, L.tm_names[i]) + i += 1 + } + MarkString(L, L.name_n) + MarkString(L, L.name_goto) + MarkString(L, L.name_self) + MarkString(L, L.name_loaded) + MarkValue(L, L.error) + i = 0 + while i < L.pending_finalize.count { + MarkObject(L, LUA_TUSERDATA, L.pending_finalize[i]) + i += 1 + } +} + +// An object a weak table may drop: unmarked tables, functions, userdata and +// threads. Strings and plain values always stay. +Unreachable :: (L: *LuaState, v: LuaValue) -> bool #inline { + if v.t == LUA_TTABLE { return L.tables[v.h].mark == 0 } + if v.t == LUA_TFUNCTION { return L.closures[v.h].mark == 0 } + if v.t == LUA_TUSERDATA { return L.userdata[v.h].mark == 0 } + if v.t == LUA_TTHREAD { return L.threads[v.h].mark == 0 } + return false +} + +ClearWeak :: (L: *LuaState) { + w: s64 = 0 + while w < L.weak.count { + h := L.weak[w] + weak_keys, weak_values := WeakMode(L, h) + if weak_values { + i: s64 = 0 + while i < L.tables[h].arr.count { + if Unreachable(L, L.tables[h].arr[i]) { L.tables[h].arr[i] = NilValue() } + i += 1 + } + } + i: s64 = 0 + while i < L.tables[h].nodes.count { + if L.tables[h].nodes[i].value.t != LUA_TNIL { + drop := (weak_keys && Unreachable(L, L.tables[h].nodes[i].key)) || (weak_values && Unreachable(L, L.tables[h].nodes[i].value)) + if drop { L.tables[h].nodes[i].value = NilValue() } + } + i += 1 + } + w += 1 + } + VecClear(L.weak) +} + +// Unreachable userdata with a __gc metamethod survive one more cycle and are +// queued for their finalizer. +SeparateFinalizers :: (L: *LuaState) { + i: s64 = 0 + while i < L.userdata.count { + if L.userdata[i].live && L.userdata[i].mark == 0 && !L.userdata[i].finalized { + meta := L.userdata[i].meta + if meta >= 0 && FastTM(L, meta, TM_GC).t != LUA_TNIL { + VecPush(L.pending_finalize, cast(s32) i) + MarkObject(L, LUA_TUSERDATA, cast(s32) i) + } + } + i += 1 + } + Propagate(L) +} + +Sweep :: (L: *LuaState) -> s64 { + size: s64 = 0 + i: s64 = 0 + while i < L.strings.count { + if L.strings[i].live { + if L.strings[i].mark == 0 && L.strings[i].reserved == 0 { + Unintern(L, cast(s32) i) + VecFree(L.strings[i].bytes) + L.strings[i].live = false + VecPush(L.string_free, cast(s32) i) + } else { + L.strings[i].mark = 0 + size += 40 + L.strings[i].bytes.count + } + } + i += 1 + } + i = 0 + while i < L.tables.count { + if L.tables[i].live { + if L.tables[i].mark == 0 { + VecFree(L.tables[i].arr) + VecFree(L.tables[i].nodes) + L.tables[i].live = false + L.tables[i].meta = -1 + VecPush(L.table_free, cast(s32) i) + } else { + L.tables[i].mark = 0 + size += 80 + L.tables[i].arr.count * 16 + L.tables[i].nodes.count * 32 + } + } + i += 1 + } + i = 0 + while i < L.closures.count { + if L.closures[i].live { + if L.closures[i].mark == 0 { + VecFree(L.closures[i].upvals) + VecFree(L.closures[i].native_upvals) + L.closures[i].live = false + VecPush(L.closure_free, cast(s32) i) + } else { + L.closures[i].mark = 0 + size += 64 + L.closures[i].upvals.count * 4 + L.closures[i].native_upvals.count * 16 + } + } + i += 1 + } + i = 0 + while i < L.protos.count { + if L.protos[i].live { + if L.protos[i].mark == 0 { + VecFree(L.protos[i].code) + VecFree(L.protos[i].lines) + VecFree(L.protos[i].constants) + VecFree(L.protos[i].protos) + VecFree(L.protos[i].upvals) + VecFree(L.protos[i].upval_names) + VecFree(L.protos[i].locvars) + L.protos[i].live = false + VecPush(L.proto_free, cast(s32) i) + } else { + L.protos[i].mark = 0 + size += 160 + L.protos[i].code.count * 20 + L.protos[i].constants.count * 16 + } + } + i += 1 + } + i = 0 + while i < L.boxes.count { + if L.boxes[i].live { + if L.boxes[i].mark == 0 { + L.boxes[i].live = false + L.boxes[i].value = NilValue() + VecPush(L.box_free, cast(s32) i) + } else { + L.boxes[i].mark = 0 + size += 32 + } + } + i += 1 + } + i = 0 + while i < L.userdata.count { + if L.userdata[i].live { + if L.userdata[i].mark == 0 { + FreeUserdata(L, cast(s32) i) + } else { + L.userdata[i].mark = 0 + size += 64 + } + } + i += 1 + } + i = 0 + while i < L.threads.count { + if L.threads[i].live { + if L.threads[i].mark == 0 { + VecFree(L.threads[i].stack) + VecFree(L.threads[i].frames) + VecFree(L.threads[i].handlers) + L.threads[i].live = false + VecPush(L.thread_free, cast(s32) i) + } else { + L.threads[i].mark = 0 + size += 160 + L.threads[i].stack.count * 16 + L.threads[i].frames.count * 64 + } + } + i += 1 + } + return size +} + +FreeUserdata :: (L: *LuaState, h: s32) { + if L.userdata[h].has_finalizer { + finalizer := L.userdata[h].finalizer + L.userdata[h].has_finalizer = false + finalizer(L, L.userdata[h].data, L.userdata[h].tag) + } + L.userdata[h].live = false + L.userdata[h].data = null + L.userdata[h].meta = -1 + L.userdata[h].env = -1 + VecPush(L.userdata_free, h) +} + +// A full collection followed by pending __gc finalizers. +CollectGarbage :: (L: *LuaState) { + if L.collecting { return } + L.collecting = true + VecClear(L.gray) + VecClear(L.weak) + MarkRoots(L) + Propagate(L) + SeparateFinalizers(L) + ClearWeak(L) + size := Sweep(L) + L.allocated = size + L.threshold = size * 2 + if L.threshold < 1048576 { L.threshold = 1048576 } + L.collecting = false + RunFinalizers(L) +} + +RunFinalizers :: (L: *LuaState) { + if L.pending_finalize.count == 0 { return } + L.collecting = true + while L.pending_finalize.count > 0 { + h := L.pending_finalize[L.pending_finalize.count - 1] + VecResize(L.pending_finalize, L.pending_finalize.count - 1) + if !L.userdata[h].live { continue } + L.userdata[h].finalized = true + value := ObjectValue(LUA_TUSERDATA, h) + tm := GetTM(L, value, TM_GC) + if tm.t == LUA_TNIL { continue } + th := L.cur + top := L.threads[th].top + if !EnsureStack(L, top + 3) { continue } + L.threads[th].stack[top] = tm + L.threads[th].stack[top + 1] = value + L.threads[th].top = top + 2 + saved_error := L.error + saved_traced := L.error_traced + ProtectedCall(L, top, 1, 0, NilValue()) + L.error = saved_error + L.error_traced = saved_traced + L.threads[th].top = top + } + L.collecting = false +} diff --git a/src/interp.zi b/src/interp.zi new file mode 100644 index 0000000..2c1468e --- /dev/null +++ b/src/interp.zi @@ -0,0 +1,1579 @@ +// The interpreter: call frames, metamethod dispatch, error positions and the +// bytecode loop. Errors propagate by return value: a failing operation sets +// L.error and returns false, every caller returns at once, and the catcher +// (pcall, a coroutine resume or the host's LuaPCall) truncates the frames. + +#scope_module + +MAX_TAG_LOOP :: 100; + +// Precall results. +CALL_LUA :: 0; +CALL_DONE :: 1; +CALL_YIELD :: 2; +CALL_ERROR :: -1; +CALL_NOT_FUNCTION :: -2; + +// RegisterName kinds. +NAME_NONE :: 0; +NAME_GLOBAL :: 1; +NAME_LOCAL :: 2; +NAME_FIELD :: 3; +NAME_METHOD :: 4; +NAME_UPVALUE :: 5; + +// ---------------------------------------------------------------- strings + +TypeNameOf :: (t: u8) -> string { + if t == LUA_TNIL { return "nil" } + if t == LUA_TFALSE || t == LUA_TTRUE { return "boolean" } + if t == LUA_TNUMBER { return "number" } + if t == LUA_TSTRING { return "string" } + if t == LUA_TTABLE { return "table" } + if t == LUA_TFUNCTION { return "function" } + if t == LUA_TUSERDATA || t == LUA_TLIGHTUSERDATA { return "userdata" } + if t == LUA_TTHREAD { return "thread" } + return "proto" +} + +AppendHex :: (out: *Vec(u8), value: u64, digits: s32) { + hex := "0123456789abcdef" + i := digits - 1 + while i >= 0 { + VecPush(<> cast(u64)(i * 4)) & 15)]) + i -= 1 + } +} + +// The text tostring() gives a value without consulting __tostring. +AppendValueText :: (L: *LuaState, out: *Vec(u8), v: LuaValue) { + t := v.t + if t == LUA_TNIL { BuilderAppend(< (value: float64, ok: bool) #inline { + if v.t == LUA_TNUMBER { return v.n, true } + if v.t == LUA_TSTRING { return ParseNumberText(StrView(L, v.h)) } + return 0.0, false +} + +// Numbers convert to strings for concatenation and string functions. +ToStringHandle :: (L: *LuaState, v: LuaValue) -> (h: s32, ok: bool) { + if v.t == LUA_TSTRING { return v.h, true } + if v.t == LUA_TNUMBER { + buffer: Vec(u8) + AppendNumber(*buffer, v.n) + h := InternBytes(L, *buffer) + VecFree(buffer) + return h, true + } + return -1, false +} + +CompareStrings :: (L: *LuaState, a: s32, b: s32) -> s32 { + if a == b { return 0 } + na := L.strings[a].bytes.count + nb := L.strings[b].bytes.count + n := ifx na < nb then na else nb + i: s64 = 0 + while i < n { + x := L.strings[a].bytes[i] + y := L.strings[b].bytes[i] + if x != y { return ifx x < y then -1 else 1 } + i += 1 + } + if na == nb { return 0 } + return ifx na < nb then -1 else 1 +} + +// ---------------------------------------------------------------- positions + +// Lua's short source name: "=name" and "@file" lose their marker, other +// chunks become [string "first line..."]. +AppendChunkId :: (L: *LuaState, out: *Vec(u8), source: s32) { + if source < 0 { BuilderAppend(< 0 && text[0] == #char "=" { + n := text.count - 1 + if n > limit - 1 { n = limit - 1 } + BuilderAppend(< 0 && text[0] == #char "@" { + n := text.count - 1 + if n <= limit - 1 { + BuilderAppend(< room { end = room; truncated = true } + BuilderAppend(< s32 { + if L.threads[thread].frames[frame].native { return -1 } + cl := L.threads[thread].frames[frame].closure + p := L.closures[cl].proto + pc := L.threads[thread].frames[frame].pc - 1 + if pc < 0 { pc = 0 } + if pc >= L.protos[p].lines.count { return -1 } + return L.protos[p].lines[pc] +} + +// "chunk:line: " for the frame `level` below the top (0 = top) when it runs +// Lua code; nothing for natives. +AppendWhere :: (L: *LuaState, out: *Vec(u8), level: s32) { + th := L.cur + frame := L.threads[th].frames.count - 1 - level + if frame < 0 { return } + if L.threads[th].frames[frame].native { return } + cl := L.threads[th].frames[frame].closure + AppendChunkId(L, out, L.protos[L.closures[cl].proto].source) + VecPush(< bool { + L.error = value + L.error_traced = false + return false +} + +ErrorText :: (L: *LuaState, text: string) -> bool { + return SetError(L, StringValue(Intern(L, text))) +} + +// A runtime error positioned at the running Lua function. +RuntimeError :: (L: *LuaState, text: string) -> bool { + message: Vec(u8) + AppendWhere(L, *message, 0) + BuilderAppend(message, text) + value := StringValue(InternBytes(L, *message)) + VecFree(message) + return SetError(L, value) +} + +LocalName :: (L: *LuaState, p: s32, reg: s32, pc: s64) -> s32 { + found: s32 = -1 + i: s64 = 0 + while i < L.protos[p].locvars.count { + lv := L.protos[p].locvars[i] + if lv.start_pc > pc { break } + if lv.reg == reg && (lv.end_pc < 0 || pc < lv.end_pc) { found = lv.name } + i += 1 + } + return found +} + +WritesRegister :: (ins: LuaInstr, reg: s32) -> bool { + op := ins.op + if op == OP_LOADNIL { return reg >= ins.a && reg < ins.a + ins.b } + if op == OP_SELF { return reg == ins.a || reg == ins.a + 1 } + if op == OP_CALL || op == OP_TAILCALL || op == OP_VARARG { return reg >= ins.a } + if op == OP_TFORCALL { return reg >= ins.a + 3 } + if op == OP_FORLOOP || op == OP_FORPREP { return reg >= ins.a && reg <= ins.a + 3 } + if op == OP_SETUPVAL || op == OP_SETGLOBAL || op == OP_SETTABLE || op == OP_SETFIELD || op == OP_SETBOX || op == OP_SETLIST { return false } + if op >= OP_JMP && op <= OP_JNLE { return false } + if op == OP_RETURN || op == OP_TFORLOOP { return false } + return reg == ins.a +} + +// How register `reg` got its value before instruction `pc` of prototype p. +RegisterName :: (L: *LuaState, p: s32, pc: s64, reg: s32) -> (kind: s32, name: s32) { + local := LocalName(L, p, reg, pc) + if local >= 0 { return NAME_LOCAL, local } + j := pc - 1 + while j >= 0 { + ins := L.protos[p].code[j] + if WritesRegister(ins, reg) { + op := ins.op + if op == OP_GETGLOBAL { return NAME_GLOBAL, L.protos[p].constants[ins.b].h } + if op == OP_GETFIELD { return NAME_FIELD, L.protos[p].constants[ins.c].h } + if op == OP_GETTABLE && ins.c < 0 { + k := L.protos[p].constants[-1 - ins.c] + if k.t == LUA_TSTRING { return NAME_FIELD, k.h } + } + if op == OP_GETUPVAL { return NAME_UPVALUE, L.protos[p].upval_names[ins.b] } + if op == OP_GETBOX || op == OP_MOVE { + name := LocalName(L, p, ins.b, j) + if name >= 0 { return NAME_LOCAL, name } + } + if op == OP_SELF && reg == ins.a && ins.c < 0 { + k := L.protos[p].constants[-1 - ins.c] + if k.t == LUA_TSTRING { return NAME_METHOD, k.h } + } + return NAME_NONE, -1 + } + j -= 1 + } + return NAME_NONE, -1 +} + +NameKindText :: (kind: s32) -> string { + if kind == NAME_GLOBAL { return "global" } + if kind == NAME_LOCAL { return "local" } + if kind == NAME_FIELD { return "field" } + if kind == NAME_METHOD { return "method" } + if kind == NAME_UPVALUE { return "upvalue" } + return "" +} + +// "attempt to global 'x' (a nil value)" for register `reg` of the +// running Lua frame; reg < 0 omits the variable. +TypeError :: (L: *LuaState, v: LuaValue, op: string, reg: s32) -> bool { + message: Vec(u8) + BuilderAppend(message, "attempt to ") + BuilderAppend(message, op) + kind: s32 = NAME_NONE + name: s32 = -1 + th := L.cur + top := L.threads[th].frames.count - 1 + if reg >= 0 && top >= 0 && !L.threads[th].frames[top].native { + cl := L.threads[th].frames[top].closure + kind, name = RegisterName(L, L.closures[cl].proto, L.threads[th].frames[top].pc - 1, reg) + } + if kind != NAME_NONE { + VecPush(message, #char " ") + BuilderAppend(message, NameKindText(kind)) + BuilderAppend(message, " '") + BuilderAppend(message, StrView(L, name)) + BuilderAppend(message, "' (a ") + } else { + BuilderAppend(message, " a ") + } + BuilderAppend(message, TypeNameOf(v.t)) + BuilderAppend(message, " value") + if kind != NAME_NONE { VecPush(message, #char ")") } + ok := RuntimeError(L, BytesView(*message)) + VecFree(message) + return ok +} + +OrderError :: (L: *LuaState, a: LuaValue, b: LuaValue) -> bool { + message: Vec(u8) + BuilderAppend(message, "attempt to compare ") + ta := TypeNameOf(a.t) + tb := TypeNameOf(b.t) + if ta == tb { + BuilderAppend(message, "two ") + BuilderAppend(message, ta) + BuilderAppend(message, " values") + } else { + BuilderAppend(message, ta) + BuilderAppend(message, " with ") + BuilderAppend(message, tb) + } + ok := RuntimeError(L, BytesView(*message)) + VecFree(message) + return ok +} + +// ---------------------------------------------------------------- tracebacks + +// The name a frame's function was called by, from the caller's call site. +FrameFunctionName :: (L: *LuaState, thread: s32, frame: s64) -> (kind: s32, name: s32) { + if frame > 0 && L.threads[thread].frames[frame].tail == 0 { + caller := frame - 1 + if !L.threads[thread].frames[caller].native { + cl := L.threads[thread].frames[caller].closure + p := L.closures[cl].proto + pc := L.threads[thread].frames[caller].pc - 1 + if pc >= 0 && pc < L.protos[p].code.count { + ins := L.protos[p].code[pc] + if ins.op == OP_CALL || ins.op == OP_TAILCALL { + return RegisterName(L, p, pc, ins.a) + } + if ins.op == OP_TFORCALL { return NAME_GLOBAL, -2 } + } + } + } + cl := L.threads[thread].frames[frame].closure + if L.threads[thread].frames[frame].native && L.closures[cl].name >= 0 { + return NAME_GLOBAL, L.closures[cl].name + } + return NAME_NONE, -1 +} + +AppendFrameText :: (L: *LuaState, out: *Vec(u8), thread: s32, frame: s64) { + cl := L.threads[thread].frames[frame].closure + native := L.threads[thread].frames[frame].native + if native { + BuilderAppend(< 0 { + Append(out, cast(s64) line) + VecPush(<") + } + } + if L.threads[thread].frames[frame].tail > 0 { + BuilderAppend(<= 0 { + if shown == 12 && count > 22 { + BuilderAppend(< bool { + if !L.hook_set { + L.hook_left = 1000000000 + return true + } + L.hook_left = ifx L.hook_count > 0 then L.hook_count else 1000000000 + hook := L.hook + L.error = NilValue() + if hook(L) { return true } + if L.error.t == LUA_TNIL { return RuntimeError(L, "instruction limit exceeded") } + L.error_traced = false + return false +} + +// ---------------------------------------------------------------- calls + +// Copy `n` results from stack[first..] to stack[func..], adjusted to `want`. +// Sets top just past the results. +MoveResults :: (L: *LuaState, func: s64, first: s64, n: s64, want: s32) { + th := L.cur + count := n + if want >= 0 { + count = want + EnsureStack(L, func + count + 1) + } + i: s64 = 0 + while i < count { + if i < n { + L.threads[th].stack[func + i] = L.threads[th].stack[first + i] + } else { + L.threads[th].stack[func + i] = NilValue() + } + i += 1 + } + L.threads[th].top = func + count +} + +PushFrame :: (L: *LuaState, frame: LuaFrame) { + VecPush(L.threads[L.cur].frames, frame) +} + +PopFrame :: (L: *LuaState) { + th := L.cur + VecResize(L.threads[th].frames, L.threads[th].frames.count - 1) +} + +// Start a call of the value at stack[func] with nargs arguments above it. +// A Lua function gets a frame for Execute to run (CALL_LUA); a native runs to +// completion here (CALL_DONE, results at func with top past them). +Precall :: (L: *LuaState, func: s64, nargs: s32, want: s32) -> s32 { + th := L.cur + count := nargs + f := L.threads[th].stack[func] + if f.t != LUA_TFUNCTION { + tm := GetTM(L, f, TM_CALL) + if tm.t != LUA_TFUNCTION { return CALL_NOT_FUNCTION } + if !EnsureStack(L, func + count + 2) { RuntimeError(L, "stack overflow"); return CALL_ERROR } + i := func + count + while i >= func { + L.threads[th].stack[i + 1] = L.threads[th].stack[i] + i -= 1 + } + L.threads[th].stack[func] = tm + count += 1 + f = tm + } + cl := f.h + p := L.closures[cl].proto + if p >= 0 { + if L.threads[th].frames.count >= cast(s64)(L.limits.max_frames + L.handler_slack) { + RuntimeError(L, "stack overflow") + return CALL_ERROR + } + np := L.protos[p].num_params + ms := cast(s64) L.protos[p].max_stack + frame: LuaFrame + frame.closure = cl + frame.func = func + frame.want = want + frame.vararg = func + 1 + if L.protos[p].is_vararg { + base := func + 1 + count + if !EnsureStack(L, base + ms + 1) { RuntimeError(L, "stack overflow"); return CALL_ERROR } + i: s64 = 0 + while i < np { + if i < count { + L.threads[th].stack[base + i] = L.threads[th].stack[func + 1 + i] + } else { + L.threads[th].stack[base + i] = NilValue() + } + i += 1 + } + frame.base = base + frame.vararg = func + 1 + np + frame.nvarargs = ifx count > np then count - np else 0 + j := base + np + while j < base + ms { L.threads[th].stack[j] = NilValue(); j += 1 } + } else { + base := func + 1 + if !EnsureStack(L, base + ms + 1) { RuntimeError(L, "stack overflow"); return CALL_ERROR } + j := base + (ifx count < np then count else np) + while j < base + ms { L.threads[th].stack[j] = NilValue(); j += 1 } + frame.base = base + } + PushFrame(L, frame) + L.threads[th].top = frame.base + ms + L.hook_left -= 1 + if L.hook_left <= 0 { + if !HookFire(L) { return CALL_ERROR } + } + return CALL_LUA + } + // A native function. + if L.native_depth >= L.limits.max_native_depth + L.handler_slack { + RuntimeError(L, "C stack overflow") + return CALL_ERROR + } + if !EnsureStack(L, func + count + 24) { RuntimeError(L, "stack overflow"); return CALL_ERROR } + frame: LuaFrame + frame.closure = cl + frame.func = func + frame.base = func + 1 + frame.want = want + frame.native = true + PushFrame(L, frame) + L.threads[th].top = func + 1 + count + native := L.closures[cl].native + L.native_depth += 1 + n := native(L) + L.native_depth -= 1 + if n < 0 { + if n == LUA_NATIVE_YIELD { + L.threads[th].yield_func = func + L.threads[th].yield_want = want + PopFrame(L) + return CALL_YIELD + } + if L.error_traced == false { TraceError(L) } + return CALL_ERROR + } + top := L.threads[th].top + available := top - (func + 1) + if cast(s64) n > available { n = cast(s32) available } + PopFrame(L) + MoveResults(L, func, top - n, n, want) + return CALL_DONE +} + +// Call stack[func] with nargs arguments from native code; results land at +// func (top just past them). False with L.error set on failure. +CallValue :: (L: *LuaState, func: s64, nargs: s32, want: s32) -> bool { + th := L.cur + L.threads[th].nesting += 1 + r := Precall(L, func, nargs, want) + ok := true + if r == CALL_LUA { + status := Execute(L, L.threads[th].frames.count - 1) + ok = status == LUA_OK + } else if r == CALL_NOT_FUNCTION { + TypeError(L, L.threads[th].stack[func], "call", -1) + TraceError(L) + ok = false + } else if r == CALL_YIELD { + RuntimeError(L, "attempt to yield across metamethod/C-call boundary") + TraceError(L) + ok = false + } else if r == CALL_ERROR { + TraceError(L) + ok = false + } + L.threads[th].nesting -= 1 + return ok +} + +// Call metamethod f(a, b) for one result. +CallTM :: (L: *LuaState, f: LuaValue, a: LuaValue, b: LuaValue, out: *LuaValue) -> bool { + th := L.cur + top := L.threads[th].top + if !EnsureStack(L, top + 4) { return RuntimeError(L, "stack overflow") } + L.threads[th].stack[top] = f + L.threads[th].stack[top + 1] = a + L.threads[th].stack[top + 2] = b + L.threads[th].top = top + 3 + if !CallValue(L, top, 2, 1) { return false } + < bool { + th := L.cur + top := L.threads[th].top + if !EnsureStack(L, top + 5) { return RuntimeError(L, "stack overflow") } + L.threads[th].stack[top] = f + L.threads[th].stack[top + 1] = a + L.threads[th].stack[top + 2] = b + L.threads[th].stack[top + 3] = c + L.threads[th].top = top + 4 + if !CallValue(L, top, 3, 0) { return false } + L.threads[th].top = top + return true +} + +// ---------------------------------------------------------------- operations + +GetIndex :: (L: *LuaState, t: LuaValue, key: LuaValue, out: *LuaValue, reg: s32) -> bool { + current := t + loop: s32 = 0 + while loop < MAX_TAG_LOOP { + tm: LuaValue + if current.t == LUA_TTABLE { + v := RawGet(L, current.h, key) + if v.t != LUA_TNIL { < bool { + if key.t == LUA_TNIL { return RuntimeError(L, "table index is nil") } + if key.t == LUA_TNUMBER && key.n != key.n { return RuntimeError(L, "table index is NaN") } + return true +} + +SetIndex :: (L: *LuaState, t: LuaValue, key: LuaValue, value: LuaValue, reg: s32) -> bool { + current := t + loop: s32 = 0 + while loop < MAX_TAG_LOOP { + tm: LuaValue + if current.t == LUA_TTABLE { + h := current.h + meta := L.tables[h].meta + if meta < 0 { + if !ValidKey(L, key) { return false } + RawSet(L, h, key, value) + return true + } + existing := RawGet(L, h, key) + if existing.t != LUA_TNIL { + RawSet(L, h, key, value) + return true + } + tm = FastTM(L, meta, TM_NEWINDEX) + if tm.t == LUA_TNIL { + if !ValidKey(L, key) { return false } + RawSet(L, h, key, value) + return true + } + } else { + tm = GetTM(L, current, TM_NEWINDEX) + if tm.t == LUA_TNIL { return TypeError(L, current, "index", ifx loop == 0 then reg else -1) } + } + if tm.t == LUA_TFUNCTION { return CallTM3(L, tm, current, key, value) } + current = tm + loop += 1 + } + return RuntimeError(L, "loop in settable") +} + +ArithNumbers :: (event: s32, a: float64, b: float64) -> float64 #inline { + if event == TM_ADD { return a + b } + if event == TM_SUB { return a - b } + if event == TM_MUL { return a * b } + if event == TM_DIV { return a / b } + if event == TM_MOD { return LuaMod(a, b) } + if event == TM_POW { return LuaPow(a, b) } + return -a +} + +Arith :: (L: *LuaState, event: s32, b: LuaValue, c: LuaValue, out: *LuaValue, rb: s32, rc: s32) -> bool { + nb, okb := ToNumber(L, b) + nc, okc := ToNumber(L, c) + if okb && okc { + < LuaValue { + tm := GetTM(L, a, event) + if tm.t == LUA_TNIL { return tm } + other := GetTM(L, b, event) + if !RawEqual(tm, other) { return NilValue() } + return tm +} + +EqualValues :: (L: *LuaState, a: LuaValue, b: LuaValue, out: *bool) -> bool { + if RawEqual(a, b) { < bool { + if a.t == LUA_TNUMBER && b.t == LUA_TNUMBER { < bool { + if a.t == LUA_TNUMBER && b.t == LUA_TNUMBER { < bool { + if v.t == LUA_TSTRING { < bool #inline { return v.t == LUA_TSTRING || v.t == LUA_TNUMBER } + +// Concatenate stack[first..last] (absolute indices) into stack[first]. +ConcatRange :: (L: *LuaState, first: s64, last_index: s64, frame_base: s64) -> bool { + th := L.cur + last := last_index + while last > first { + top := L.threads[th].stack[last] + prev := L.threads[th].stack[last - 1] + if IsStringLike(prev) && IsStringLike(top) { + n: s64 = 2 + while last - n >= first && IsStringLike(L.threads[th].stack[last - n]) { n += 1 } + start := last - n + 1 + VecClear(L.scratch) + i := start + while i <= last { + v := L.threads[th].stack[i] + if v.t == LUA_TSTRING { + BuilderAppend(L.scratch, StrView(L, v.h)) + } else { + AppendNumber(*L.scratch, v.n) + } + i += 1 + } + h := InternBytes(L, *L.scratch) + L.threads[th].stack[start] = StringValue(h) + last = start + } else { + tm := GetTM(L, prev, TM_CONCAT) + if tm.t == LUA_TNIL { tm = GetTM(L, top, TM_CONCAT) } + if tm.t == LUA_TNIL { + culprit := ifx IsStringLike(prev) then last else last - 1 + return TypeError(L, L.threads[th].stack[culprit], "concatenate", cast(s32)(culprit - frame_base)) + } + result: LuaValue + if !CallTM(L, tm, prev, top, *result) { return false } + L.threads[th].stack[last - 1] = result + last -= 1 + } + } + return true +} + +// tostring() semantics including __tostring. +ToStringMeta :: (L: *LuaState, v: LuaValue, out: *LuaValue) -> bool { + if v.t == LUA_TSTRING { < bool #inline { + if L.allocated < L.threshold { return true } + return GCStep(L) +} + +GCStep :: (L: *LuaState) -> bool #cold { + if L.collecting { return true } + CollectGarbage(L) + if L.limits.max_memory > 0 && L.allocated > L.limits.max_memory { + return SetError(L, StringValue(Intern(L, "not enough memory"))) + } + return true +} + +ExecuteError :: (L: *LuaState) -> s32 #cold { + TraceError(L) + return LUA_ERRRUN +} + +// ---------------------------------------------------------------- the loop + +// Run the frame at index `stop` of the running thread (and everything it +// calls) until it returns. LUA_YIELD leaves the frames in place for resume. +Execute :: (L: *LuaState, stop: s64) -> s32 { + th := L.cur + while true { + fi := L.threads[th].frames.count - 1 + cl := L.threads[th].frames[fi].closure + p := L.closures[cl].proto + base := L.threads[th].frames[fi].base + pc := L.threads[th].frames[fi].pc + ms := cast(s64) L.protos[p].max_stack + code: *LuaInstr = *L.protos[p].code[0] + K: *LuaValue = null + if L.protos[p].constants.count > 0 { K = *L.protos[p].constants[0] } + R: *LuaValue = *L.threads[th].stack[base] + env := L.closures[cl].env + + while true { + ins := code[pc] + pc += 1 + a := ins.a + op := ins.op + if op == { + case OP_MOVE; + R[a] = R[ins.b] + case OP_LOADK; + R[a] = K[ins.b] + case OP_GETFIELD; + t := R[ins.b] + key := K[ins.c] + done := false + if t.t == LUA_TTABLE { + v := GetStr(L, t.h, key.h) + if v.t != LUA_TNIL || L.tables[t.h].meta < 0 { + R[a] = v + done = true + } + } + if !done { + L.threads[th].frames[fi].pc = pc + result: LuaValue + if !GetIndex(L, t, key, *result, ins.b) { return ExecuteError(L) } + R = *L.threads[th].stack[base] + R[a] = result + } + case OP_GETTABLE; + t := R[ins.b] + key := ifx ins.c < 0 then K[-1 - ins.c] else R[ins.c] + done := false + if t.t == LUA_TTABLE { + v: LuaValue + if key.t == LUA_TNUMBER { + index := SafeInteger(key.n) + if cast(float64) index == key.n && index >= 1 && index <= L.tables[t.h].arr.count { + v = L.tables[t.h].arr[index - 1] + } else { + v = RawGet(L, t.h, key) + } + } else { + v = RawGet(L, t.h, key) + } + if v.t != LUA_TNIL || L.tables[t.h].meta < 0 { + R[a] = v + done = true + } + } + if !done { + L.threads[th].frames[fi].pc = pc + result: LuaValue + if !GetIndex(L, t, key, *result, ins.b) { return ExecuteError(L) } + R = *L.threads[th].stack[base] + R[a] = result + } + case OP_GETGLOBAL; + key := K[ins.b] + v := GetStr(L, env, key.h) + if v.t != LUA_TNIL || L.tables[env].meta < 0 { + R[a] = v + } else { + L.threads[th].frames[fi].pc = pc + result: LuaValue + if !GetIndex(L, TableValue(env), key, *result, -1) { return ExecuteError(L) } + R = *L.threads[th].stack[base] + R[a] = result + } + case OP_GETBOX; + R[a] = L.boxes[R[ins.b].h].value + case OP_GETUPVAL; + R[a] = L.boxes[L.closures[cl].upvals[ins.b]].value + case OP_ADD; + b := ifx ins.b < 0 then K[-1 - ins.b] else R[ins.b] + c := ifx ins.c < 0 then K[-1 - ins.c] else R[ins.c] + if b.t == LUA_TNUMBER && c.t == LUA_TNUMBER { + R[a] = NumberValue(b.n + c.n) + } else { + L.threads[th].frames[fi].pc = pc + result: LuaValue + if !Arith(L, TM_ADD, b, c, *result, ins.b, ins.c) { return ExecuteError(L) } + R = *L.threads[th].stack[base] + R[a] = result + } + case OP_SUB; + b := ifx ins.b < 0 then K[-1 - ins.b] else R[ins.b] + c := ifx ins.c < 0 then K[-1 - ins.c] else R[ins.c] + if b.t == LUA_TNUMBER && c.t == LUA_TNUMBER { + R[a] = NumberValue(b.n - c.n) + } else { + L.threads[th].frames[fi].pc = pc + result: LuaValue + if !Arith(L, TM_SUB, b, c, *result, ins.b, ins.c) { return ExecuteError(L) } + R = *L.threads[th].stack[base] + R[a] = result + } + case OP_MUL; + b := ifx ins.b < 0 then K[-1 - ins.b] else R[ins.b] + c := ifx ins.c < 0 then K[-1 - ins.c] else R[ins.c] + if b.t == LUA_TNUMBER && c.t == LUA_TNUMBER { + R[a] = NumberValue(b.n * c.n) + } else { + L.threads[th].frames[fi].pc = pc + result: LuaValue + if !Arith(L, TM_MUL, b, c, *result, ins.b, ins.c) { return ExecuteError(L) } + R = *L.threads[th].stack[base] + R[a] = result + } + case OP_DIV; + b := ifx ins.b < 0 then K[-1 - ins.b] else R[ins.b] + c := ifx ins.c < 0 then K[-1 - ins.c] else R[ins.c] + if b.t == LUA_TNUMBER && c.t == LUA_TNUMBER { + R[a] = NumberValue(b.n / c.n) + } else { + L.threads[th].frames[fi].pc = pc + result: LuaValue + if !Arith(L, TM_DIV, b, c, *result, ins.b, ins.c) { return ExecuteError(L) } + R = *L.threads[th].stack[base] + R[a] = result + } + case OP_MOD; + b := ifx ins.b < 0 then K[-1 - ins.b] else R[ins.b] + c := ifx ins.c < 0 then K[-1 - ins.c] else R[ins.c] + if b.t == LUA_TNUMBER && c.t == LUA_TNUMBER { + R[a] = NumberValue(LuaMod(b.n, c.n)) + } else { + L.threads[th].frames[fi].pc = pc + result: LuaValue + if !Arith(L, TM_MOD, b, c, *result, ins.b, ins.c) { return ExecuteError(L) } + R = *L.threads[th].stack[base] + R[a] = result + } + case OP_POW; + b := ifx ins.b < 0 then K[-1 - ins.b] else R[ins.b] + c := ifx ins.c < 0 then K[-1 - ins.c] else R[ins.c] + if b.t == LUA_TNUMBER && c.t == LUA_TNUMBER { + R[a] = NumberValue(LuaPow(b.n, c.n)) + } else { + L.threads[th].frames[fi].pc = pc + result: LuaValue + if !Arith(L, TM_POW, b, c, *result, ins.b, ins.c) { return ExecuteError(L) } + R = *L.threads[th].stack[base] + R[a] = result + } + case OP_JMP; + if ins.a < pc { + L.hook_left -= 1 + if L.hook_left <= 0 { + L.threads[th].frames[fi].pc = pc + if !HookFire(L) { return ExecuteError(L) } + R = *L.threads[th].stack[base] + } + } + pc = ins.a + case OP_JT; + if Truthy(R[ins.b]) { + if ins.a < pc { + L.hook_left -= 1 + if L.hook_left <= 0 { + L.threads[th].frames[fi].pc = pc + if !HookFire(L) { return ExecuteError(L) } + R = *L.threads[th].stack[base] + } + } + pc = ins.a + } + case OP_JF; + if !Truthy(R[ins.b]) { + if ins.a < pc { + L.hook_left -= 1 + if L.hook_left <= 0 { + L.threads[th].frames[fi].pc = pc + if !HookFire(L) { return ExecuteError(L) } + R = *L.threads[th].stack[base] + } + } + pc = ins.a + } + case OP_JEQ; + b := ifx ins.b < 0 then K[-1 - ins.b] else R[ins.b] + c := ifx ins.c < 0 then K[-1 - ins.c] else R[ins.c] + equal := false + if b.t == c.t && b.t == LUA_TNUMBER { + equal = b.n == c.n + } else if RawEqual(b, c) { + equal = true + } else if b.t == c.t && (b.t == LUA_TTABLE || b.t == LUA_TUSERDATA) { + L.threads[th].frames[fi].pc = pc + if !EqualValues(L, b, c, *equal) { return ExecuteError(L) } + R = *L.threads[th].stack[base] + } + if equal { pc = ins.a } + case OP_JNE; + b := ifx ins.b < 0 then K[-1 - ins.b] else R[ins.b] + c := ifx ins.c < 0 then K[-1 - ins.c] else R[ins.c] + equal := false + if b.t == c.t && b.t == LUA_TNUMBER { + equal = b.n == c.n + } else if RawEqual(b, c) { + equal = true + } else if b.t == c.t && (b.t == LUA_TTABLE || b.t == LUA_TUSERDATA) { + L.threads[th].frames[fi].pc = pc + if !EqualValues(L, b, c, *equal) { return ExecuteError(L) } + R = *L.threads[th].stack[base] + } + if !equal { pc = ins.a } + case OP_JLT; + b := ifx ins.b < 0 then K[-1 - ins.b] else R[ins.b] + c := ifx ins.c < 0 then K[-1 - ins.c] else R[ins.c] + result := false + if b.t == LUA_TNUMBER && c.t == LUA_TNUMBER { + result = b.n < c.n + } else { + L.threads[th].frames[fi].pc = pc + if !LessThan(L, b, c, *result) { return ExecuteError(L) } + R = *L.threads[th].stack[base] + } + if result { + if ins.a < pc { + L.hook_left -= 1 + if L.hook_left <= 0 { + L.threads[th].frames[fi].pc = pc + if !HookFire(L) { return ExecuteError(L) } + R = *L.threads[th].stack[base] + } + } + pc = ins.a + } + case OP_JNLT; + b := ifx ins.b < 0 then K[-1 - ins.b] else R[ins.b] + c := ifx ins.c < 0 then K[-1 - ins.c] else R[ins.c] + result := false + if b.t == LUA_TNUMBER && c.t == LUA_TNUMBER { + result = b.n < c.n + } else { + L.threads[th].frames[fi].pc = pc + if !LessThan(L, b, c, *result) { return ExecuteError(L) } + R = *L.threads[th].stack[base] + } + if !result { + if ins.a < pc { + L.hook_left -= 1 + if L.hook_left <= 0 { + L.threads[th].frames[fi].pc = pc + if !HookFire(L) { return ExecuteError(L) } + R = *L.threads[th].stack[base] + } + } + pc = ins.a + } + case OP_JLE; + b := ifx ins.b < 0 then K[-1 - ins.b] else R[ins.b] + c := ifx ins.c < 0 then K[-1 - ins.c] else R[ins.c] + result := false + if b.t == LUA_TNUMBER && c.t == LUA_TNUMBER { + result = b.n <= c.n + } else { + L.threads[th].frames[fi].pc = pc + if !LessEqual(L, b, c, *result) { return ExecuteError(L) } + R = *L.threads[th].stack[base] + } + if result { + if ins.a < pc { + L.hook_left -= 1 + if L.hook_left <= 0 { + L.threads[th].frames[fi].pc = pc + if !HookFire(L) { return ExecuteError(L) } + R = *L.threads[th].stack[base] + } + } + pc = ins.a + } + case OP_JNLE; + b := ifx ins.b < 0 then K[-1 - ins.b] else R[ins.b] + c := ifx ins.c < 0 then K[-1 - ins.c] else R[ins.c] + result := false + if b.t == LUA_TNUMBER && c.t == LUA_TNUMBER { + result = b.n <= c.n + } else { + L.threads[th].frames[fi].pc = pc + if !LessEqual(L, b, c, *result) { return ExecuteError(L) } + R = *L.threads[th].stack[base] + } + if !result { + if ins.a < pc { + L.hook_left -= 1 + if L.hook_left <= 0 { + L.threads[th].frames[fi].pc = pc + if !HookFire(L) { return ExecuteError(L) } + R = *L.threads[th].stack[base] + } + } + pc = ins.a + } + case OP_CALL; + func := base + a + nargs: s32 = 0 + if ins.b != 0 { + nargs = ins.b - 1 + L.threads[th].top = func + 1 + nargs + } else { + nargs = cast(s32)(L.threads[th].top - func - 1) + } + want := ins.c - 1 + L.threads[th].frames[fi].pc = pc + r := Precall(L, func, nargs, want) + if r == CALL_LUA { break } + if r == CALL_NOT_FUNCTION { + TypeError(L, L.threads[th].stack[func], "call", a) + return ExecuteError(L) + } + if r == CALL_ERROR { return ExecuteError(L) } + if r == CALL_YIELD { return LUA_YIELD } + if want >= 0 { L.threads[th].top = base + ms } + if L.allocated >= L.threshold { + if !GCStep(L) { return ExecuteError(L) } + } + R = *L.threads[th].stack[base] + env = L.closures[cl].env + case OP_RETURN; + first := base + a + n: s64 = 0 + if ins.b != 0 { n = ins.b - 1 } else { n = L.threads[th].top - first } + func := L.threads[th].frames[fi].func + want := L.threads[th].frames[fi].want + S: *LuaValue = *L.threads[th].stack[0] + i: s64 = 0 + if want < 0 { + while i < n { S[func + i] = S[first + i]; i += 1 } + } else { + // The caller reserved registers for `want` results. + if func + want >= L.threads[th].stack.count { + EnsureStack(L, func + want + 1) + S = *L.threads[th].stack[0] + } + while i < want { + if i < n { S[func + i] = S[first + i] } else { S[func + i] = NilValue() } + i += 1 + } + } + VecResize(L.threads[th].frames, fi) + if fi == stop { + L.threads[th].top = func + (ifx want < 0 then n else cast(s64) want) + return LUA_OK + } + if want < 0 { + L.threads[th].top = func + n + } else { + caller := fi - 1 + ccl := L.threads[th].frames[caller].closure + L.threads[th].top = L.threads[th].frames[caller].base + L.protos[L.closures[ccl].proto].max_stack + } + break + case OP_SETFIELD; + t := R[a] + key := K[ins.b] + value := ifx ins.c < 0 then K[-1 - ins.c] else R[ins.c] + if t.t == LUA_TTABLE && L.tables[t.h].meta < 0 { + SetStr(L, t.h, key.h, value) + } else { + L.threads[th].frames[fi].pc = pc + if !SetIndex(L, t, key, value, a) { return ExecuteError(L) } + R = *L.threads[th].stack[base] + } + case OP_SETTABLE; + t := R[a] + key := ifx ins.b < 0 then K[-1 - ins.b] else R[ins.b] + value := ifx ins.c < 0 then K[-1 - ins.c] else R[ins.c] + done := false + if t.t == LUA_TTABLE && L.tables[t.h].meta < 0 { + if key.t == LUA_TNUMBER { + index := SafeInteger(key.n) + if cast(float64) index == key.n { + SetInt(L, t.h, index, value) + done = true + } + } else if key.t == LUA_TSTRING { + SetStr(L, t.h, key.h, value) + done = true + } + } + if !done { + L.threads[th].frames[fi].pc = pc + if !SetIndex(L, t, key, value, a) { return ExecuteError(L) } + R = *L.threads[th].stack[base] + } + case OP_SETGLOBAL; + key := K[ins.b] + if L.tables[env].meta < 0 { + SetStr(L, env, key.h, R[a]) + } else { + L.threads[th].frames[fi].pc = pc + if !SetIndex(L, TableValue(env), key, R[a], -1) { return ExecuteError(L) } + R = *L.threads[th].stack[base] + } + case OP_SETBOX; + L.boxes[R[a].h].value = ifx ins.b < 0 then K[-1 - ins.b] else R[ins.b] + case OP_SETUPVAL; + L.boxes[L.closures[cl].upvals[ins.b]].value = R[a] + case OP_SELF; + object := R[ins.b] + key := ifx ins.c < 0 then K[-1 - ins.c] else R[ins.c] + R[a + 1] = object + done := false + if object.t == LUA_TTABLE && key.t == LUA_TSTRING { + v := GetStr(L, object.h, key.h) + if v.t != LUA_TNIL || L.tables[object.h].meta < 0 { + R[a] = v + done = true + } + } + if !done { + L.threads[th].frames[fi].pc = pc + result: LuaValue + if !GetIndex(L, object, key, *result, ins.b) { return ExecuteError(L) } + R = *L.threads[th].stack[base] + R[a] = result + } + case OP_FORLOOP; + step := R[a + 2].n + index := R[a].n + step + limit := R[a + 1].n + if (step > 0.0 && index <= limit) || (step <= 0.0 && index >= limit) { + R[a].n = index + R[a + 3] = NumberValue(index) + L.hook_left -= 1 + if L.hook_left <= 0 { + L.threads[th].frames[fi].pc = pc + if !HookFire(L) { return ExecuteError(L) } + R = *L.threads[th].stack[base] + } + pc = ins.b + } + case OP_TFORCALL; + f := R[a] + nvars := ins.c + handled := false + if f.t == LUA_TFUNCTION && R[a + 1].t == LUA_TTABLE { + if f.h == L.next_fn { + L.threads[th].frames[fi].pc = pc + found, ok := TableNext(L, R[a + 1].h, R[a + 2], *R[a + 3], *R[a + 4]) + if !ok { + RuntimeError(L, "invalid key to 'next'") + return ExecuteError(L) + } + if !found { R[a + 3] = NilValue() } + j: s32 = 2 + while j < nvars { R[a + 3 + j] = NilValue(); j += 1 } + handled = true + } else if f.h == L.inext_fn { + index := R[a + 2].n + 1.0 + v := GetInt(L, R[a + 1].h, SafeInteger(index)) + if v.t == LUA_TNIL { + R[a + 3] = NilValue() + } else { + R[a + 3] = NumberValue(index) + R[a + 4] = v + } + j: s32 = 2 + while j < nvars { R[a + 3 + j] = NilValue(); j += 1 } + handled = true + } + } + if !handled { + R[a + 3] = R[a] + R[a + 4] = R[a + 1] + R[a + 5] = R[a + 2] + func := base + a + 3 + L.threads[th].top = func + 3 + L.threads[th].frames[fi].pc = pc + r := Precall(L, func, 2, nvars) + if r == CALL_LUA { break } + if r == CALL_NOT_FUNCTION { + TypeError(L, L.threads[th].stack[func], "call", a) + return ExecuteError(L) + } + if r == CALL_ERROR { return ExecuteError(L) } + if r == CALL_YIELD { return LUA_YIELD } + L.threads[th].top = base + ms + R = *L.threads[th].stack[base] + env = L.closures[cl].env + } + case OP_TFORLOOP; + if R[a + 3].t != LUA_TNIL { + R[a + 2] = R[a + 3] + L.hook_left -= 1 + if L.hook_left <= 0 { + L.threads[th].frames[fi].pc = pc + if !HookFire(L) { return ExecuteError(L) } + R = *L.threads[th].stack[base] + } + pc = ins.b + } + case OP_LOADNIL; + j: s32 = 0 + while j < ins.b { R[a + j] = NilValue(); j += 1 } + case OP_LOADBOOL; + R[a] = BoolValue(ins.b != 0) + case OP_NOT; + R[a] = BoolValue(!Truthy(R[ins.b])) + case OP_UNM; + b := R[ins.b] + if b.t == LUA_TNUMBER { + R[a] = NumberValue(-b.n) + } else { + L.threads[th].frames[fi].pc = pc + result: LuaValue + if !Arith(L, TM_UNM, b, b, *result, ins.b, ins.b) { return ExecuteError(L) } + R = *L.threads[th].stack[base] + R[a] = result + } + case OP_LEN; + b := R[ins.b] + if b.t == LUA_TSTRING { + R[a] = NumberValue(cast(float64) L.strings[b.h].bytes.count) + } else if b.t == LUA_TTABLE { + R[a] = NumberValue(cast(float64) TableLength(L, b.h)) + } else { + L.threads[th].frames[fi].pc = pc + result: LuaValue + if !LengthOf(L, b, *result, ins.b) { return ExecuteError(L) } + R = *L.threads[th].stack[base] + R[a] = result + } + case OP_CONCAT; + L.threads[th].frames[fi].pc = pc + if !ConcatRange(L, base + ins.b, base + ins.c, base) { return ExecuteError(L) } + R = *L.threads[th].stack[base] + R[a] = R[ins.b] + if L.allocated >= L.threshold { + if !GCStep(L) { return ExecuteError(L) } + R = *L.threads[th].stack[base] + } + case OP_EQ; + b := ifx ins.b < 0 then K[-1 - ins.b] else R[ins.b] + c := ifx ins.c < 0 then K[-1 - ins.c] else R[ins.c] + equal := false + if RawEqual(b, c) { + equal = true + } else if b.t == c.t && (b.t == LUA_TTABLE || b.t == LUA_TUSERDATA) { + L.threads[th].frames[fi].pc = pc + if !EqualValues(L, b, c, *equal) { return ExecuteError(L) } + R = *L.threads[th].stack[base] + } + R[a] = BoolValue(equal) + case OP_NE; + b := ifx ins.b < 0 then K[-1 - ins.b] else R[ins.b] + c := ifx ins.c < 0 then K[-1 - ins.c] else R[ins.c] + equal := false + if RawEqual(b, c) { + equal = true + } else if b.t == c.t && (b.t == LUA_TTABLE || b.t == LUA_TUSERDATA) { + L.threads[th].frames[fi].pc = pc + if !EqualValues(L, b, c, *equal) { return ExecuteError(L) } + R = *L.threads[th].stack[base] + } + R[a] = BoolValue(!equal) + case OP_LT; + b := ifx ins.b < 0 then K[-1 - ins.b] else R[ins.b] + c := ifx ins.c < 0 then K[-1 - ins.c] else R[ins.c] + result := false + if b.t == LUA_TNUMBER && c.t == LUA_TNUMBER { + result = b.n < c.n + } else { + L.threads[th].frames[fi].pc = pc + if !LessThan(L, b, c, *result) { return ExecuteError(L) } + R = *L.threads[th].stack[base] + } + R[a] = BoolValue(result) + case OP_LE; + b := ifx ins.b < 0 then K[-1 - ins.b] else R[ins.b] + c := ifx ins.c < 0 then K[-1 - ins.c] else R[ins.c] + result := false + if b.t == LUA_TNUMBER && c.t == LUA_TNUMBER { + result = b.n <= c.n + } else { + L.threads[th].frames[fi].pc = pc + if !LessEqual(L, b, c, *result) { return ExecuteError(L) } + R = *L.threads[th].stack[base] + } + R[a] = BoolValue(result) + case OP_NEWTABLE; + R[a] = TableValue(NewTable(L, ins.b, ins.c)) + if L.allocated >= L.threshold { + L.threads[th].frames[fi].pc = pc + if !GCStep(L) { return ExecuteError(L) } + R = *L.threads[th].stack[base] + } + case OP_SETLIST; + t := R[a].h + n := cast(s64) ins.b + if n == 0 { + n = L.threads[th].top - (base + a) - 1 + L.threads[th].top = base + ms + } + j: s64 = 1 + while j <= n { + SetInt(L, t, cast(s64) ins.c + j, R[a + j]) + j += 1 + } + case OP_CLOSURE; + child := L.protos[p].protos[ins.b] + fresh := NewClosureObject(L) + L.closures[fresh].proto = child + L.closures[fresh].env = env + count := L.protos[child].upvals.count + if count > 0 { VecReserve(L.closures[fresh].upvals, count) } + j: s64 = 0 + while j < count { + desc := L.protos[child].upvals[j] + box: s32 = 0 + if desc.from_local { + box = R[desc.index].h + } else { + box = L.closures[cl].upvals[desc.index] + } + VecPush(L.closures[fresh].upvals, box) + j += 1 + } + L.allocated += count * 4 + R[a] = FunctionValue(fresh) + if L.allocated >= L.threshold { + L.threads[th].frames[fi].pc = pc + if !GCStep(L) { return ExecuteError(L) } + R = *L.threads[th].stack[base] + } + case OP_NEWBOX; + box := NewBox(L, R[a]) + R[a] = ObjectValue(LUA_TBOX, box) + case OP_VARARG; + nv := cast(s64) L.threads[th].frames[fi].nvarargs + source := L.threads[th].frames[fi].vararg + want := cast(s64)(ins.b - 1) + if want < 0 { + want = nv + if !EnsureStack(L, base + a + nv + 1) { + L.threads[th].frames[fi].pc = pc + RuntimeError(L, "stack overflow") + return ExecuteError(L) + } + L.threads[th].top = base + a + nv + R = *L.threads[th].stack[base] + } + S: *LuaValue = *L.threads[th].stack[0] + j: s64 = 0 + while j < want { + if j < nv { R[a + j] = S[source + j] } else { R[a + j] = NilValue() } + j += 1 + } + case OP_TAILCALL; + func := base + a + nargs: s32 = 0 + if ins.b != 0 { + nargs = ins.b - 1 + L.threads[th].top = func + 1 + nargs + } else { + nargs = cast(s32)(L.threads[th].top - func - 1) + } + L.threads[th].frames[fi].pc = pc + f := R[a] + if f.t == LUA_TFUNCTION && L.closures[f.h].proto >= 0 { + dest := L.threads[th].frames[fi].func + want := L.threads[th].frames[fi].want + tail := L.threads[th].frames[fi].tail + 1 + S: *LuaValue = *L.threads[th].stack[0] + j: s64 = 0 + while j <= nargs { S[dest + j] = S[func + j]; j += 1 } + VecResize(L.threads[th].frames, fi) + r := Precall(L, dest, nargs, want) + if r != CALL_LUA { return ExecuteError(L) } + L.threads[th].frames[fi].tail = tail + break + } + r := Precall(L, func, nargs, LUA_MULTRET) + if r == CALL_LUA { break } + if r == CALL_NOT_FUNCTION { + TypeError(L, L.threads[th].stack[func], "call", a) + return ExecuteError(L) + } + if r == CALL_ERROR { return ExecuteError(L) } + if r == CALL_YIELD { return LUA_YIELD } + R = *L.threads[th].stack[base] + case OP_FORPREP; + init, ok1 := ToNumber(L, R[a]) + limit, ok2 := ToNumber(L, R[a + 1]) + step, ok3 := ToNumber(L, R[a + 2]) + if !ok1 || !ok2 || !ok3 { + L.threads[th].frames[fi].pc = pc + what := ifx !ok1 then "'for' initial value must be a number" else (ifx !ok2 then "'for' limit must be a number" else "'for' step must be a number") + RuntimeError(L, what) + return ExecuteError(L) + } + R[a] = NumberValue(init - step) + R[a + 1] = NumberValue(limit) + R[a + 2] = NumberValue(step) + pc = ins.b + case; + L.threads[th].frames[fi].pc = pc + RuntimeError(L, "bad opcode") + return ExecuteError(L) + } + } + // A call pushed a frame or a return popped one: reload. + } + return LUA_OK +} diff --git a/src/lexer.zi b/src/lexer.zi new file mode 100644 index 0000000..469ffe0 --- /dev/null +++ b/src/lexer.zi @@ -0,0 +1,421 @@ +// Lua 5.1 lexer over a borrowed source view. Names and string literals are +// interned immediately; the parser receives string handles. + +#scope_module + +TK_AND :: 257; +TK_BREAK :: 258; +TK_DO :: 259; +TK_ELSE :: 260; +TK_ELSEIF :: 261; +TK_END :: 262; +TK_FALSE :: 263; +TK_FOR :: 264; +TK_FUNCTION :: 265; +TK_IF :: 266; +TK_IN :: 267; +TK_LOCAL :: 268; +TK_NIL :: 269; +TK_NOT :: 270; +TK_OR :: 271; +TK_REPEAT :: 272; +TK_RETURN :: 273; +TK_THEN :: 274; +TK_TRUE :: 275; +TK_UNTIL :: 276; +TK_WHILE :: 277; +TK_CONCAT :: 278; +TK_DOTS :: 279; +TK_EQ :: 280; +TK_GE :: 281; +TK_LE :: 282; +TK_NE :: 283; +TK_NUMBER :: 284; +TK_NAME :: 285; +TK_STRING :: 286; +TK_EOS :: 287; + +RESERVED_COUNT :: 21; + +Token :: struct { + kind: s32 + line: s32 + num: float64 + str: s32 +} + +Lexer :: struct { + L: *LuaState + src: string + pos: s64 + line: s32 + chunk: string + tok: Token + ahead: Token + has_ahead: bool + last_line: s32 + failed: bool + message: Vec(u8) + buf: Vec(u8) +} + +ReservedWords :: () -> [21]string { + words: [21]string = .["and", "break", "do", "else", "elseif", "end", "false", "for", "function", "if", "in", "local", "nil", "not", "or", "repeat", "return", "then", "true", "until", "while"] + return words +} + +// Mark reserved words in the string table so the lexer finds them by handle. +InternReserved :: (L: *LuaState) { + words := ReservedWords() + i: s32 = 0 + while i < RESERVED_COUNT { + h := Intern(L, words[i]) + L.strings[h].reserved = cast(u8)(i + 1) + i += 1 + } +} + +TokenText :: (kind: s32, out: *Vec(u8)) { + if kind < 257 { + VecPush(<="); return } + if kind == TK_LE { BuilderAppend(<"); return } + if kind == TK_NAME { BuilderAppend(<"); return } + if kind == TK_STRING { BuilderAppend(<"); return } + BuilderAppend(<") +} + +LexError :: (lx: *Lexer, message: string, near: bool) { + if lx.failed { return } + lx.failed = true + VecClear(lx.message) + AppendChunkIdText(*lx.message, lx.chunk) + VecPush(lx.message, #char ":") + Append(*lx.message, cast(s64) lx.line) + BuilderAppend(lx.message, ": ") + BuilderAppend(lx.message, message) + if near { + BuilderAppend(lx.message, " near '") + if lx.tok.kind == TK_NAME || lx.tok.kind == TK_STRING { + BuilderAppend(lx.message, StrView(lx.L, lx.tok.str)) + } else if lx.tok.kind == TK_NUMBER { + AppendNumber(*lx.message, lx.tok.num) + } else { + TokenText(lx.tok.kind, *lx.message) + } + VecPush(lx.message, #char "'") + } +} + +IsAlpha :: (c: u8) -> bool #inline { return (c >= #char "a" && c <= #char "z") || (c >= #char "A" && c <= #char "Z") || c == #char "_" } +IsDigit :: (c: u8) -> bool #inline { return c >= #char "0" && c <= #char "9" } +IsAlnum :: (c: u8) -> bool #inline { return IsAlpha(c) || IsDigit(c) } +IsSpace :: (c: u8) -> bool #inline { return c == 32 || (c >= 9 && c <= 13) } +IsXDigit :: (c: u8) -> bool #inline { return IsDigit(c) || (c >= #char "a" && c <= #char "f") || (c >= #char "A" && c <= #char "F") } + +Peek :: (lx: *Lexer, offset: s64) -> u8 #inline { + at := lx.pos + offset + if at >= lx.src.count { return 0 } + return lx.src[at] +} + +AtEnd :: (lx: *Lexer) -> bool #inline { return lx.pos >= lx.src.count } + +// Consume a newline sequence (\n, \r, \n\r or \r\n). +SkipNewline :: (lx: *Lexer) { + c := lx.src[lx.pos] + lx.pos += 1 + if !AtEnd(lx) { + d := lx.src[lx.pos] + if (d == 10 || d == 13) && d != c { lx.pos += 1 } + } + lx.line += 1 +} + +// Level of a long bracket at pos ([==[ gives 2), or -1 when not one. +LongBracketLevel :: (lx: *Lexer) -> s32 { + open := lx.src[lx.pos] + at := lx.pos + 1 + level: s32 = 0 + while at < lx.src.count && lx.src[at] == #char "=" { level += 1; at += 1 } + if at < lx.src.count && lx.src[at] == open { return level } + return -1 - level +} + +// Read [[...]] content starting at pos (on the first bracket). +ReadLongString :: (lx: *Lexer, level: s32, keep: bool) -> bool { + lx.pos += 2 + cast(s64) level + VecClear(lx.buf) + // Skip a first newline. + if !AtEnd(lx) && (lx.src[lx.pos] == 10 || lx.src[lx.pos] == 13) { SkipNewline(lx) } + while true { + if AtEnd(lx) { + LexError(lx, ifx keep then "unfinished long string" else "unfinished long comment", false) + return false + } + c := lx.src[lx.pos] + if c == #char "]" { + at := lx.pos + 1 + count: s32 = 0 + while at < lx.src.count && lx.src[at] == #char "=" { count += 1; at += 1 } + if count == level && at < lx.src.count && lx.src[at] == #char "]" { + lx.pos = at + 1 + return true + } + if keep { VecPush(lx.buf, c) } + lx.pos += 1 + } else if c == 10 || c == 13 { + if keep { VecPush(lx.buf, 10) } + SkipNewline(lx) + } else { + if keep { VecPush(lx.buf, c) } + lx.pos += 1 + } + } + return false +} + +ReadString :: (lx: *Lexer, quote: u8) -> bool { + lx.pos += 1 + VecClear(lx.buf) + while true { + if AtEnd(lx) { LexError(lx, "unfinished string", false); return false } + c := lx.src[lx.pos] + if c == quote { lx.pos += 1; return true } + if c == 10 || c == 13 { LexError(lx, "unfinished string", false); return false } + if c == #char "\\" { + lx.pos += 1 + if AtEnd(lx) { LexError(lx, "unfinished string", false); return false } + e := lx.src[lx.pos] + if e == #char "n" { VecPush(lx.buf, 10); lx.pos += 1 } + else if e == #char "t" { VecPush(lx.buf, 9); lx.pos += 1 } + else if e == #char "r" { VecPush(lx.buf, 13); lx.pos += 1 } + else if e == #char "a" { VecPush(lx.buf, 7); lx.pos += 1 } + else if e == #char "b" { VecPush(lx.buf, 8); lx.pos += 1 } + else if e == #char "f" { VecPush(lx.buf, 12); lx.pos += 1 } + else if e == #char "v" { VecPush(lx.buf, 11); lx.pos += 1 } + else if e == 10 || e == 13 { VecPush(lx.buf, 10); SkipNewline(lx) } + else if e == #char "x" { + // LuaJIT/5.2 hex escape. + if lx.pos + 2 < lx.src.count && IsXDigit(lx.src[lx.pos + 1]) && IsXDigit(lx.src[lx.pos + 2]) { + VecPush(lx.buf, cast(u8)(HexDigitValue(lx.src[lx.pos + 1]) * 16 + HexDigitValue(lx.src[lx.pos + 2]))) + lx.pos += 3 + } else { + LexError(lx, "invalid escape sequence", false) + return false + } + } else if e == #char "z" { + // LuaJIT: skip following whitespace. + lx.pos += 1 + while !AtEnd(lx) && IsSpace(lx.src[lx.pos]) { + if lx.src[lx.pos] == 10 || lx.src[lx.pos] == 13 { SkipNewline(lx) } else { lx.pos += 1 } + } + } else if IsDigit(e) { + value: s32 = 0 + digits: s32 = 0 + while digits < 3 && !AtEnd(lx) && IsDigit(lx.src[lx.pos]) { + value = value * 10 + cast(s32)(lx.src[lx.pos] - #char "0") + lx.pos += 1 + digits += 1 + } + if value > 255 { LexError(lx, "escape sequence too large", false); return false } + VecPush(lx.buf, cast(u8) value) + } else { + // \\, \", \' and any other character stand for themselves. + VecPush(lx.buf, e) + lx.pos += 1 + } + continue + } + VecPush(lx.buf, c) + lx.pos += 1 + } + return false +} + +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 } + if c >= #char "A" && c <= #char "F" { return cast(s32)(c - #char "A") + 10 } + return -1 +} + +ReadNumber :: (lx: *Lexer) -> bool { + start := lx.pos + if lx.src[lx.pos] == #char "0" && (Peek(lx, 1) == #char "x" || Peek(lx, 1) == #char "X") { + lx.pos += 2 + } + while !AtEnd(lx) { + c := lx.src[lx.pos] + if IsAlnum(c) || c == #char "." { + if (c == #char "e" || c == #char "E") && (Peek(lx, 1) == #char "+" || Peek(lx, 1) == #char "-") && !IsHexPrefixed(lx.src, start) { + lx.pos += 2 + continue + } + if (c == #char "p" || c == #char "P") && (Peek(lx, 1) == #char "+" || Peek(lx, 1) == #char "-") && IsHexPrefixed(lx.src, start) { + lx.pos += 2 + continue + } + lx.pos += 1 + } else { + break + } + } + value, ok := ParseNumberText(lx.src[start:lx.pos]) + if !ok { + lx.tok.kind = TK_NUMBER + VecClear(lx.buf) + LexError(lx, "malformed number", false) + BuilderAppend(lx.message, " near '") + BuilderAppend(lx.message, lx.src[start:lx.pos]) + VecPush(lx.message, #char "'") + return false + } + lx.tok.num = value + return true +} + +IsHexPrefixed :: (src: string, start: s64) -> bool { + return start + 1 < src.count && src[start] == #char "0" && (src[start + 1] == #char "x" || src[start + 1] == #char "X") +} + +// Scan the next token into lx.tok. +Scan :: (lx: *Lexer) { + while true { + if AtEnd(lx) { + lx.tok.kind = TK_EOS + lx.tok.line = lx.line + return + } + c := lx.src[lx.pos] + lx.tok.line = lx.line + if c == 10 || c == 13 { SkipNewline(lx); continue } + if IsSpace(c) { lx.pos += 1; continue } + if c == #char "-" { + if Peek(lx, 1) != #char "-" { lx.pos += 1; lx.tok.kind = #char "-"; return } + lx.pos += 2 + if !AtEnd(lx) && lx.src[lx.pos] == #char "[" { + level := LongBracketLevel(lx) + if level >= 0 { + if !ReadLongString(lx, level, false) { lx.tok.kind = TK_EOS; return } + continue + } + } + while !AtEnd(lx) && lx.src[lx.pos] != 10 && lx.src[lx.pos] != 13 { lx.pos += 1 } + continue + } + if c == #char "[" { + level := LongBracketLevel(lx) + if level >= 0 { + if !ReadLongString(lx, level, true) { lx.tok.kind = TK_EOS; return } + lx.tok.kind = TK_STRING + lx.tok.str = InternBytes(lx.L, *lx.buf) + return + } + if level != -1 { LexError(lx, "invalid long string delimiter", false); lx.tok.kind = TK_EOS; return } + lx.pos += 1 + lx.tok.kind = #char "[" + return + } + if c == #char "=" { + lx.pos += 1 + if Peek(lx, 0) == #char "=" { lx.pos += 1; lx.tok.kind = TK_EQ } else { lx.tok.kind = #char "=" } + return + } + if c == #char "<" { + lx.pos += 1 + if Peek(lx, 0) == #char "=" { lx.pos += 1; lx.tok.kind = TK_LE } else { lx.tok.kind = #char "<" } + return + } + if c == #char ">" { + lx.pos += 1 + if Peek(lx, 0) == #char "=" { lx.pos += 1; lx.tok.kind = TK_GE } else { lx.tok.kind = #char ">" } + return + } + if c == #char "~" { + lx.pos += 1 + if Peek(lx, 0) == #char "=" { lx.pos += 1; lx.tok.kind = TK_NE } else { lx.tok.kind = #char "~" } + return + } + if c == #char "\"" || c == #char "'" { + if !ReadString(lx, c) { lx.tok.kind = TK_EOS; return } + lx.tok.kind = TK_STRING + lx.tok.str = InternBytes(lx.L, *lx.buf) + return + } + if c == #char "." { + if Peek(lx, 1) == #char "." { + if Peek(lx, 2) == #char "." { lx.pos += 3; lx.tok.kind = TK_DOTS; return } + lx.pos += 2 + lx.tok.kind = TK_CONCAT + return + } + if !IsDigit(Peek(lx, 1)) { lx.pos += 1; lx.tok.kind = #char "."; return } + if !ReadNumber(lx) { lx.tok.kind = TK_EOS; return } + lx.tok.kind = TK_NUMBER + return + } + if IsDigit(c) { + if !ReadNumber(lx) { lx.tok.kind = TK_EOS; return } + lx.tok.kind = TK_NUMBER + return + } + if IsAlpha(c) { + start := lx.pos + while !AtEnd(lx) && IsAlnum(lx.src[lx.pos]) { lx.pos += 1 } + h := Intern(lx.L, lx.src[start:lx.pos]) + reserved := lx.L.strings[h].reserved + if reserved > 0 { + lx.tok.kind = 256 + cast(s32) reserved + } else { + lx.tok.kind = TK_NAME + lx.tok.str = h + } + return + } + // Single-character token; control characters are rejected. + if c < 32 || c >= 127 { + lx.pos += 1 + lx.tok.kind = cast(s32) c + LexError(lx, "unexpected symbol", true) + lx.tok.kind = TK_EOS + return + } + lx.pos += 1 + lx.tok.kind = cast(s32) c + return + } +} + +NextToken :: (lx: *Lexer) { + lx.last_line = lx.tok.line + if lx.has_ahead { + lx.tok = lx.ahead + lx.has_ahead = false + return + } + Scan(lx) +} + +LookAhead :: (lx: *Lexer) -> s32 { + if !lx.has_ahead { + saved := lx.tok + Scan(lx) + lx.ahead = lx.tok + lx.tok = saved + lx.has_ahead = true + } + return lx.ahead.kind +} diff --git a/src/lib_base.zi b/src/lib_base.zi new file mode 100644 index 0000000..32f96fa --- /dev/null +++ b/src/lib_base.zi @@ -0,0 +1,743 @@ +// Base library, coroutines and a minimal package/require. + +#scope_module + +SetNative :: (L: *LuaState, t: s32, name: string, fn: LuaNative) -> s32 { + h := NewNative(L, fn, name) + SetStr(L, t, Intern(L, name), FunctionValue(h)) + return h +} + +SetValue :: (L: *LuaState, t: s32, name: string, v: LuaValue) { + SetStr(L, t, Intern(L, name), v) +} + +Slot1 :: (L: *LuaState) -> s64 #inline { return StackBase(L) } + +ReturnValue :: (L: *LuaState, v: LuaValue) -> s32 #inline { + Push(L, v) + return 1 +} + +ReturnNil :: (L: *LuaState) -> s32 #inline { + Push(L, NilValue()) + return 1 +} + +// Push nil, message: the failure convention of load/io functions. +ReturnFailure :: (L: *LuaState, message: string) -> s32 { + Push(L, NilValue()) + Push(L, StringValue(Intern(L, message))) + return 2 +} + +EmitText :: (L: *LuaState, text: string) { + if L.print_sink_set { + sink := L.print_sink + sink(L.print_context, text) + } else { + print("%", text) + } +} + +BasePrint :: (L: *LuaState) -> s32 { + n := ArgCount(L) + out: Vec(u8) + i: s32 = 1 + while i <= n { + s: LuaValue + if !ToStringMeta(L, Arg(L, i), *s) { VecFree(out); return LUA_NATIVE_ERROR } + if !IsStringLike(s) { + VecFree(out) + return LuaErrorText(L, "'tostring' must return a string to 'print'") + } + if i > 1 { VecPush(out, 9) } + if s.t == LUA_TSTRING { BuilderAppend(out, StrView(L, s.h)) } else { AppendNumber(*out, s.n) } + i += 1 + } + VecPush(out, 10) + EmitText(L, BytesView(*out)) + VecFree(out) + return 0 +} + +BaseType :: (L: *LuaState) -> s32 { + if ArgCount(L) < 1 { return LuaArgError(L, 1, "value expected") } + return ReturnValue(L, StringValue(Intern(L, TypeNameOf(Arg(L, 1).t)))) +} + +BaseToString :: (L: *LuaState) -> s32 { + if ArgCount(L) < 1 { return LuaArgError(L, 1, "value expected") } + s: LuaValue + if !ToStringMeta(L, Arg(L, 1), *s) { return LUA_NATIVE_ERROR } + return ReturnValue(L, s) +} + +DigitValue :: (c: u8) -> s32 { + if c >= #char "0" && c <= #char "9" { return cast(s32)(c - #char "0") } + if c >= #char "a" && c <= #char "z" { return cast(s32)(c - #char "a") + 10 } + if c >= #char "A" && c <= #char "Z" { return cast(s32)(c - #char "A") + 10 } + return 99 +} + +BaseToNumber :: (L: *LuaState) -> s32 { + base, ok := LuaOptInteger(L, 2, 10) + if !ok { return LUA_NATIVE_ERROR } + v := Arg(L, 1) + if base == 10 { + if ArgCount(L) < 1 { return LuaArgError(L, 1, "value expected") } + n, converted := ToNumber(L, v) + if converted { return ReturnValue(L, NumberValue(n)) } + return ReturnNil(L) + } + text, is_text := LuaCheckString(L, 1) + if !is_text { return LUA_NATIVE_ERROR } + if base < 2 || base > 36 { return LuaArgError(L, 2, "base out of range") } + at: s64 = 0 + while at < text.count && IsWhitespaceByte(text[at]) { at += 1 } + negative := false + if at < text.count && (text[at] == #char "-" || text[at] == #char "+") { + negative = text[at] == #char "-" + at += 1 + } + if base == 16 && at + 1 < text.count && text[at] == #char "0" && (text[at + 1] == #char "x" || text[at + 1] == #char "X") { at += 2 } + value: float64 = 0.0 + digits: s64 = 0 + while at < text.count { + d := DigitValue(text[at]) + if d >= base { break } + value = value * cast(float64) base + cast(float64) d + digits += 1 + at += 1 + } + while at < text.count && IsWhitespaceByte(text[at]) { at += 1 } + if digits == 0 || at != text.count { return ReturnNil(L) } + return ReturnValue(L, NumberValue(ifx negative then -value else value)) +} + +BaseNext :: (L: *LuaState) -> s32 { + if !LuaCheckTable(L, 1) { return LUA_NATIVE_ERROR } + k: LuaValue + v: LuaValue + found, ok := TableNext(L, Arg(L, 1).h, Arg(L, 2), *k, *v) + if !ok { return LuaErrorText(L, "invalid key to 'next'") } + if !found { return ReturnNil(L) } + Push(L, k) + Push(L, v) + return 2 +} + +BasePairs :: (L: *LuaState) -> s32 { + if !LuaCheckTable(L, 1) { return LUA_NATIVE_ERROR } + t := Arg(L, 1) + Push(L, FunctionValue(L.next_fn)) + Push(L, t) + Push(L, NilValue()) + return 3 +} + +BaseInext :: (L: *LuaState) -> s32 { + if !LuaCheckTable(L, 1) { return LUA_NATIVE_ERROR } + index, ok := LuaCheckInteger(L, 2) + if !ok { return LUA_NATIVE_ERROR } + index += 1 + v := GetInt(L, Arg(L, 1).h, index) + if v.t == LUA_TNIL { return 0 } + Push(L, NumberValue(cast(float64) index)) + Push(L, v) + return 2 +} + +BaseIpairs :: (L: *LuaState) -> s32 { + if !LuaCheckTable(L, 1) { return LUA_NATIVE_ERROR } + t := Arg(L, 1) + Push(L, FunctionValue(L.inext_fn)) + Push(L, t) + Push(L, NumberValue(0.0)) + return 3 +} + +BaseRawGet :: (L: *LuaState) -> s32 { + if !LuaCheckTable(L, 1) { return LUA_NATIVE_ERROR } + return ReturnValue(L, RawGet(L, Arg(L, 1).h, Arg(L, 2))) +} + +BaseRawSet :: (L: *LuaState) -> s32 { + if !LuaCheckTable(L, 1) { return LUA_NATIVE_ERROR } + if !LuaCheckAny(L, 3) { return LUA_NATIVE_ERROR } + key := Arg(L, 2) + if key.t == LUA_TNIL { return LuaErrorText(L, "table index is nil") } + if key.t == LUA_TNUMBER && key.n != key.n { return LuaErrorText(L, "table index is NaN") } + t := Arg(L, 1) + RawSet(L, t.h, key, Arg(L, 3)) + return ReturnValue(L, t) +} + +BaseRawEqual :: (L: *LuaState) -> s32 { + if !LuaCheckAny(L, 1) || !LuaCheckAny(L, 2) { return LUA_NATIVE_ERROR } + return ReturnValue(L, BoolValue(RawEqual(Arg(L, 1), Arg(L, 2)))) +} + +BaseGetMetatable :: (L: *LuaState) -> s32 { + if !LuaCheckAny(L, 1) { return LUA_NATIVE_ERROR } + mt := MetatableOf(L, Arg(L, 1)) + if mt < 0 { return ReturnNil(L) } + protected := GetStr(L, mt, L.tm_names[TM_METATABLE]) + if protected.t != LUA_TNIL { return ReturnValue(L, protected) } + return ReturnValue(L, TableValue(mt)) +} + +BaseSetMetatable :: (L: *LuaState) -> s32 { + if !LuaCheckTable(L, 1) { return LUA_NATIVE_ERROR } + t := Arg(L, 1) + mt := Arg(L, 2) + if mt.t != LUA_TNIL && mt.t != LUA_TTABLE { return LuaArgError(L, 2, "nil or table expected") } + old := L.tables[t.h].meta + if old >= 0 && GetStr(L, old, L.tm_names[TM_METATABLE]).t != LUA_TNIL { + return LuaErrorText(L, "cannot change a protected metatable") + } + L.tables[t.h].meta = ifx mt.t == LUA_TTABLE then mt.h else -1 + return ReturnValue(L, t) +} + +BaseAssert :: (L: *LuaState) -> s32 { + if !LuaCheckAny(L, 1) { return LUA_NATIVE_ERROR } + if Truthy(Arg(L, 1)) { return ArgCount(L) } + if ArgCount(L) < 2 { return LuaErrorText(L, "assertion failed!") } + message := Arg(L, 2) + if message.t == LUA_TSTRING { return LuaErrorText(L, StrView(L, message.h)) } + if message.t == LUA_TNUMBER { + h, ok := ToStringHandle(L, message) + return LuaErrorText(L, StrView(L, h)) + } + SetError(L, message) + return LUA_NATIVE_ERROR +} + +BaseError :: (L: *LuaState) -> s32 { + level, ok := LuaOptInteger(L, 2, 1) + if !ok { return LUA_NATIVE_ERROR } + v := Arg(L, 1) + // LuaJIT adds the position only to string messages; numbers stay numbers. + if v.t == LUA_TSTRING && level > 0 { + h := v.h + text: Vec(u8) + AppendWhere(L, *text, cast(s32) level) + BuilderAppend(text, StrView(L, h)) + v = StringValue(InternBytes(L, *text)) + VecFree(text) + } + SetError(L, v) + return LUA_NATIVE_ERROR +} + +// pcall(f, ...) -> true, results | false, error +BasePcall :: (L: *LuaState) -> s32 { + if ArgCount(L) < 1 { return LuaArgError(L, 1, "value expected") } + th := L.cur + func := Slot1(L) + nargs := ArgCount(L) - 1 + status := ProtectedCall(L, func, nargs, LUA_MULTRET, NilValue()) + if status == LUA_OK { + n := L.threads[th].top - func + Push(L, NilValue()) + i := L.threads[th].top - 1 + while i > func { + L.threads[th].stack[i] = L.threads[th].stack[i - 1] + i -= 1 + } + L.threads[th].stack[func] = BoolValue(true) + return cast(s32)(n + 1) + } + L.threads[th].top = func + Push(L, BoolValue(false)) + Push(L, L.error) + L.error = NilValue() + return 2 +} + +// xpcall(f, handler, ...) -> true, results | false, handler(error) +BaseXpcall :: (L: *LuaState) -> s32 { + if ArgCount(L) < 2 { return LuaArgError(L, 2, "value expected") } + th := L.cur + func := Slot1(L) + handler := L.threads[th].stack[func + 1] + // Drop the handler from the argument list; the handler entry keeps it alive. + i := func + 1 + while i + 1 < L.threads[th].top { + L.threads[th].stack[i] = L.threads[th].stack[i + 1] + i += 1 + } + L.threads[th].top -= 1 + nargs := cast(s32)(L.threads[th].top - func - 1) + status := ProtectedCall(L, func, nargs, LUA_MULTRET, handler) + if status == LUA_OK { + n := L.threads[th].top - func + Push(L, NilValue()) + j := L.threads[th].top - 1 + while j > func { + L.threads[th].stack[j] = L.threads[th].stack[j - 1] + j -= 1 + } + L.threads[th].stack[func] = BoolValue(true) + return cast(s32)(n + 1) + } + L.threads[th].top = func + Push(L, BoolValue(false)) + Push(L, L.error) + L.error = NilValue() + return 2 +} + +BaseSelect :: (L: *LuaState) -> s32 { + n := ArgCount(L) + first := Arg(L, 1) + if first.t == LUA_TSTRING && StrLen(L, first.h) == 1 && L.strings[first.h].bytes[0] == #char "#" { + return ReturnValue(L, NumberValue(cast(float64)(n - 1))) + } + i, ok := LuaCheckInteger(L, 1) + if !ok { return LUA_NATIVE_ERROR } + if i < 0 { i = n + i } else if i > n { i = n } + if i < 1 { return LuaArgError(L, 1, "index out of range") } + return cast(s32)(n - i) +} + +BaseUnpack :: (L: *LuaState) -> s32 { + if !LuaCheckTable(L, 1) { return LUA_NATIVE_ERROR } + t := Arg(L, 1).h + first, ok1 := LuaOptInteger(L, 2, 1) + if !ok1 { return LUA_NATIVE_ERROR } + last: s64 = 0 + if Arg(L, 3).t == LUA_TNIL { + last = TableLength(L, t) + } else { + value, ok2 := LuaCheckInteger(L, 3) + if !ok2 { return LUA_NATIVE_ERROR } + last = value + } + if first > last { return 0 } + count := last - first + 1 + if count >= 8000000 || !EnsureStack(L, Top(L) + count + 1) { return LuaErrorText(L, "too many results to unpack") } + i := first + while i <= last { + Push(L, GetInt(L, t, i)) + i += 1 + } + return cast(s32) count +} + +// Gather a chunk from a reader function into bytes. +ReadChunkPieces :: (L: *LuaState, out: *Vec(u8)) -> bool { + th := L.cur + reader := Arg(L, 1) + while true { + top := L.threads[th].top + Push(L, reader) + if !CallValue(L, top, 0, 1) { return false } + piece := L.threads[th].stack[top] + L.threads[th].top = top + if piece.t == LUA_TNIL { return true } + if piece.t != LUA_TSTRING { return ErrorText(L, "reader function must return a string") } + if StrLen(L, piece.h) == 0 { return true } + BuilderAppend(< s32 { + if status != LUA_OK { + message := PopValue(L) + Push(L, NilValue()) + Push(L, message) + return 2 + } + if env.t == LUA_TTABLE { + f := PopValue(L) + L.closures[f.h].env = env.h + Push(L, f) + } + return 1 +} + +BaseLoad :: (L: *LuaState) -> s32 { + chunk := Arg(L, 1) + env := Arg(L, 4) + if chunk.t == LUA_TSTRING || chunk.t == LUA_TNUMBER { + text, ok := LuaCheckString(L, 1) + name, ok2 := LuaOptString(L, 2, text) + if !ok2 { return LUA_NATIVE_ERROR } + status := LoadChunk(L, text, name, -1) + return LoadResult(L, status, env) + } + if chunk.t != LUA_TFUNCTION { return LuaTypeError(L, 1, "function") } + name, ok := LuaOptString(L, 2, "=(load)") + if !ok { return LUA_NATIVE_ERROR } + name_handle := Intern(L, name) + bytes: Vec(u8) + if !ReadChunkPieces(L, *bytes) { + VecFree(bytes) + message := L.error + L.error = NilValue() + Push(L, NilValue()) + Push(L, message) + return 2 + } + status := LoadChunk(L, BytesView(*bytes), StrView(L, name_handle), -1) + VecFree(bytes) + return LoadResult(L, status, env) +} + +BaseLoadString :: (L: *LuaState) -> s32 { + text, ok := LuaCheckString(L, 1) + if !ok { return LUA_NATIVE_ERROR } + name, ok2 := LuaOptString(L, 2, text) + if !ok2 { return LUA_NATIVE_ERROR } + status := LoadChunk(L, text, name, -1) + return LoadResult(L, status, NilValue()) +} + +// A path inside the file root; false when files are disabled or the path +// leaves the root. +ResolvePath :: (L: *LuaState, path: string, out: *Vec(u8)) -> bool { + if L.file_root.count == 0 { return false } + i: s64 = 0 + while i + 1 < path.count { + if path[i] == #char "." && path[i + 1] == #char "." { + before := i == 0 || path[i - 1] == #char "/" + after := i + 2 >= path.count || path[i + 2] == #char "/" + if before && after { return false } + } + i += 1 + } + root := BytesView(*L.file_root) + if path.count > 0 && path[0] == #char "/" { + if path.count < root.count || path[0:root.count] != root { return false } + BuilderAppend(< 0 && root[root.count - 1] != #char "/" { VecPush(< s32 { + full: Vec(u8) + if !ResolvePath(L, path, *full) { + VecFree(full) + text: Vec(u8) + BuilderAppend(text, "cannot open ") + BuilderAppend(text, path) + Push(L, StringValue(InternBytes(L, *text))) + VecFree(text) + return LUA_ERRFILE + } + bytes: Vec(u8) + if !ReadFileInto(BytesView(*full), *bytes) { + VecFree(bytes) + VecFree(full) + text: Vec(u8) + BuilderAppend(text, "cannot open ") + BuilderAppend(text, path) + Push(L, StringValue(InternBytes(L, *text))) + VecFree(text) + return LUA_ERRFILE + } + name: Vec(u8) + VecPush(name, #char "@") + BuilderAppend(name, path) + status := LoadChunk(L, BytesView(*bytes), BytesView(*name), -1) + VecFree(name) + VecFree(bytes) + VecFree(full) + return status +} + +BaseLoadFile :: (L: *LuaState) -> s32 { + path, ok := LuaCheckString(L, 1) + if !ok { return LUA_NATIVE_ERROR } + return LoadResult(L, LoadFileChunk(L, path), NilValue()) +} + +BaseDoFile :: (L: *LuaState) -> s32 { + path, ok := LuaCheckString(L, 1) + if !ok { return LUA_NATIVE_ERROR } + th := L.cur + func := L.threads[th].top + if LoadFileChunk(L, path) != LUA_OK { return LuaRaiseError(L) } + if !CallValue(L, func, 0, LUA_MULTRET) { return LUA_NATIVE_ERROR } + return cast(s32)(L.threads[th].top - func) +} + +// The closure at call level `level` (1 = the caller of the native), or -1. +LevelClosure :: (L: *LuaState, level: s64) -> s32 { + th := L.cur + frame := L.threads[th].frames.count - 1 - level + if frame < 0 { return -2 } + return L.threads[th].frames[frame].closure +} + +BaseGetFenv :: (L: *LuaState) -> s32 { + v := Arg(L, 1) + if v.t == LUA_TFUNCTION { + return ReturnValue(L, TableValue(L.closures[v.h].env)) + } + level, ok := LuaOptInteger(L, 1, 1) + if !ok { return LUA_NATIVE_ERROR } + if level < 0 { return LuaArgError(L, 1, "level must be non-negative") } + if level == 0 { return ReturnValue(L, TableValue(L.threads[L.cur].env)) } + cl := LevelClosure(L, level) + if cl == -2 { return LuaArgError(L, 1, "invalid level") } + if L.closures[cl].proto < 0 { return ReturnValue(L, TableValue(L.threads[L.cur].env)) } + return ReturnValue(L, TableValue(L.closures[cl].env)) +} + +BaseSetFenv :: (L: *LuaState) -> s32 { + env := Arg(L, 2) + if env.t != LUA_TTABLE { return LuaTypeError(L, 2, "table") } + v := Arg(L, 1) + if v.t == LUA_TFUNCTION { + if L.closures[v.h].proto < 0 { return LuaErrorText(L, "'setfenv' cannot change environment of given object") } + L.closures[v.h].env = env.h + return ReturnValue(L, v) + } + level, ok := LuaCheckInteger(L, 1) + if !ok { return LUA_NATIVE_ERROR } + if level < 0 { return LuaArgError(L, 1, "level must be non-negative") } + if level == 0 { + L.threads[L.cur].env = env.h + return 0 + } + cl := LevelClosure(L, level) + if cl == -2 { return LuaArgError(L, 1, "invalid level") } + if L.closures[cl].proto < 0 { return LuaErrorText(L, "'setfenv' cannot change environment of given object") } + L.closures[cl].env = env.h + return ReturnValue(L, FunctionValue(cl)) +} + +BaseCollectGarbage :: (L: *LuaState) -> s32 { + option, ok := LuaOptString(L, 1, "collect") + if !ok { return LUA_NATIVE_ERROR } + if option == "count" { + Push(L, NumberValue(cast(float64) L.allocated / 1024.0)) + Push(L, NumberValue(cast(float64)(L.allocated % 1024))) + return 2 + } + if option == "collect" || option == "step" { + if !L.collecting { CollectGarbage(L) } + if option == "step" { return ReturnValue(L, BoolValue(true)) } + return ReturnValue(L, NumberValue(0.0)) + } + if option == "stop" { L.threshold = 9223372036854775807; return ReturnValue(L, NumberValue(0.0)) } + if option == "restart" { L.threshold = L.allocated * 2; return ReturnValue(L, NumberValue(0.0)) } + if option == "setpause" || option == "setstepmul" { return ReturnValue(L, NumberValue(200.0)) } + return LuaArgError(L, 1, "invalid option") +} + +BaseGcInfo :: (L: *LuaState) -> s32 { + return ReturnValue(L, NumberValue(cast(float64)(L.allocated / 1024))) +} + +BaseNewProxy :: (L: *LuaState) -> s32 { + h := NewUserdataObject(L) + v := Arg(L, 1) + if v.t == LUA_TTRUE { + L.userdata[h].meta = NewTable(L, 0, 0) + } else if v.t == LUA_TUSERDATA { + L.userdata[h].meta = L.userdata[v.h].meta + } else if v.t != LUA_TNIL && v.t != LUA_TFALSE { + return LuaArgError(L, 1, "boolean or proxy expected") + } + return ReturnValue(L, ObjectValue(LUA_TUSERDATA, h)) +} + +PackageTable :: (L: *LuaState, name: string) -> s32 { + package := GetStr(L, L.globals, Intern(L, "package")) + if package.t != LUA_TTABLE { return -1 } + t := GetStr(L, package.h, Intern(L, name)) + if t.t != LUA_TTABLE { return -1 } + return t.h +} + +BaseRequire :: (L: *LuaState) -> s32 { + name, ok := LuaCheckString(L, 1) + if !ok { return LUA_NATIVE_ERROR } + key := Intern(L, name) + loaded := PackageTable(L, "loaded") + if loaded >= 0 { + v := GetStr(L, loaded, key) + if Truthy(v) { return ReturnValue(L, v) } + } + preload := PackageTable(L, "preload") + loader := NilValue() + if preload >= 0 { loader = GetStr(L, preload, key) } + if loader.t == LUA_TNIL { + text: Vec(u8) + BuilderAppend(text, "module '") + BuilderAppend(text, StrView(L, key)) + BuilderAppend(text, "' not found") + result := LuaErrorText(L, BytesView(*text)) + VecFree(text) + return result + } + th := L.cur + func := L.threads[th].top + Push(L, loader) + Push(L, StringValue(key)) + if !CallValue(L, func, 1, 1) { return LUA_NATIVE_ERROR } + result := L.threads[th].stack[func] + if loaded >= 0 { + if result.t == LUA_TNIL { + existing := GetStr(L, loaded, key) + result = ifx existing.t == LUA_TNIL then BoolValue(true) else existing + } + SetStr(L, loaded, key, result) + } + L.threads[th].top = func + return ReturnValue(L, result) +} + +// ---------------------------------------------------------------- coroutines + +CheckThread :: (L: *LuaState, n: s32) -> s32 { + v := Arg(L, n) + if v.t != LUA_TTHREAD { LuaTypeError(L, n, "coroutine"); return -1 } + return v.h +} + +CoCreate :: (L: *LuaState) -> s32 { + f := Arg(L, 1) + if f.t != LUA_TFUNCTION { return LuaTypeError(L, 1, "function") } + co := NewThreadObject(L) + L.threads[co].stack[0] = f + L.threads[co].top = 1 + L.threads[co].env = L.threads[L.cur].env + return ReturnValue(L, ObjectValue(LUA_TTHREAD, co)) +} + +CoResume :: (L: *LuaState) -> s32 { + co := CheckThread(L, 1) + if co < 0 { return LUA_NATIVE_ERROR } + th := L.cur + nargs := ArgCount(L) - 1 + status, count := ResumeThread(L, co, nargs) + // Results replaced the arguments; put the status flag below them. + first := L.threads[th].top - count + Push(L, NilValue()) + i := L.threads[th].top - 1 + while i > first { + L.threads[th].stack[i] = L.threads[th].stack[i - 1] + i -= 1 + } + L.threads[th].stack[first] = BoolValue(status == LUA_OK || status == LUA_YIELD) + return count + 1 +} + +CoYield :: (L: *LuaState) -> s32 { + th := L.cur + if th == L.main { return LuaErrorText(L, "attempt to yield from outside a coroutine") } + if L.threads[th].nesting > 0 { return LuaErrorText(L, "attempt to yield across metamethod/C-call boundary") } + return LUA_NATIVE_YIELD +} + +CoStatus :: (L: *LuaState) -> s32 { + co := CheckThread(L, 1) + if co < 0 { return LUA_NATIVE_ERROR } + text := "suspended" + if co == L.cur { text = "running" } + else if L.threads[co].status == THREAD_DEAD { text = "dead" } + else if L.threads[co].status == THREAD_NORMAL { text = "normal" } + else if L.threads[co].status == THREAD_RUNNING { text = "normal" } + return ReturnValue(L, StringValue(Intern(L, text))) +} + +CoRunning :: (L: *LuaState) -> s32 { + if L.cur == L.main { return ReturnNil(L) } + return ReturnValue(L, ObjectValue(LUA_TTHREAD, L.cur)) +} + +CoWrapCall :: (L: *LuaState) -> s32 { + co := IndexValue(L, LuaUpvalueIndex(1)) + th := L.cur + nargs := ArgCount(L) + status, count := ResumeThread(L, co.h, nargs) + if status == LUA_OK || status == LUA_YIELD { return count } + message := PopValue(L) + if IsStringLike(message) { + h, ok := ToStringHandle(L, message) + text: Vec(u8) + AppendWhere(L, *text, 1) + BuilderAppend(text, StrView(L, h)) + message = StringValue(InternBytes(L, *text)) + VecFree(text) + } + SetError(L, message) + return LUA_NATIVE_ERROR +} + +CoWrap :: (L: *LuaState) -> s32 { + if CoCreate(L) < 0 { return LUA_NATIVE_ERROR } + LuaPushNativeClosure(L, CoWrapCall, 1, "wrap") + return 1 +} + +OpenCoroutine :: (L: *LuaState) { + t := NewTable(L, 0, 8) + SetValue(L, L.globals, "coroutine", TableValue(t)) + SetNative(L, t, "create", CoCreate) + SetNative(L, t, "resume", CoResume) + SetNative(L, t, "yield", CoYield) + SetNative(L, t, "status", CoStatus) + SetNative(L, t, "running", CoRunning) + SetNative(L, t, "wrap", CoWrap) +} + +OpenBase :: (L: *LuaState) { + g := L.globals + SetValue(L, g, "_G", TableValue(g)) + SetValue(L, g, "_VERSION", StringValue(Intern(L, "Lua 5.1"))) + SetNative(L, g, "print", BasePrint) + SetNative(L, g, "type", BaseType) + SetNative(L, g, "tostring", BaseToString) + SetNative(L, g, "tonumber", BaseToNumber) + L.next_fn = SetNative(L, g, "next", BaseNext) + SetNative(L, g, "pairs", BasePairs) + SetNative(L, g, "ipairs", BaseIpairs) + L.inext_fn = NewNative(L, BaseInext, "ipairs_iterator") + SetNative(L, g, "rawget", BaseRawGet) + SetNative(L, g, "rawset", BaseRawSet) + SetNative(L, g, "rawequal", BaseRawEqual) + SetNative(L, g, "getmetatable", BaseGetMetatable) + SetNative(L, g, "setmetatable", BaseSetMetatable) + SetNative(L, g, "assert", BaseAssert) + SetNative(L, g, "error", BaseError) + SetNative(L, g, "pcall", BasePcall) + SetNative(L, g, "xpcall", BaseXpcall) + SetNative(L, g, "select", BaseSelect) + SetNative(L, g, "unpack", BaseUnpack) + SetNative(L, g, "load", BaseLoad) + SetNative(L, g, "loadstring", BaseLoadString) + SetNative(L, g, "loadfile", BaseLoadFile) + SetNative(L, g, "dofile", BaseDoFile) + SetNative(L, g, "getfenv", BaseGetFenv) + SetNative(L, g, "setfenv", BaseSetFenv) + SetNative(L, g, "collectgarbage", BaseCollectGarbage) + SetNative(L, g, "gcinfo", BaseGcInfo) + SetNative(L, g, "newproxy", BaseNewProxy) + SetNative(L, g, "require", BaseRequire) + package := NewTable(L, 0, 4) + SetValue(L, g, "package", TableValue(package)) + loaded := NewTable(L, 0, 16) + SetValue(L, package, "loaded", TableValue(loaded)) + SetValue(L, package, "preload", TableValue(NewTable(L, 0, 0))) + SetValue(L, package, "path", StringValue(Intern(L, ""))) + SetValue(L, package, "cpath", StringValue(Intern(L, ""))) + SetValue(L, loaded, "_G", TableValue(g)) +} + +// Register a library table in globals and package.loaded. +RegisterLibrary :: (L: *LuaState, name: string, t: s32) { + SetValue(L, L.globals, name, TableValue(t)) + loaded := PackageTable(L, "loaded") + if loaded >= 0 { SetValue(L, loaded, name, TableValue(t)) } +} diff --git a/src/lib_bit.zi b/src/lib_bit.zi new file mode 100644 index 0000000..2e25320 --- /dev/null +++ b/src/lib_bit.zi @@ -0,0 +1,146 @@ +// LuaJIT's bit library: 32-bit operations returning signed results. + +#scope_module + +// LuaJIT's normalization: round to an integer and keep the low 32 bits. +ToBit :: (x: float64) -> u32 #inline { + bits: NumberBits + bits.f = x + 6755399441055744.0 + return cast(u32)(bits.u & 0xFFFFFFFF) +} + +BitResult :: (L: *LuaState, x: u32) -> s32 #inline { + Push(L, NumberValue(cast(float64) cast(s32) x)) + return 1 +} + +BitArg :: (L: *LuaState, n: s32) -> (value: u32, ok: bool) #inline { + x, ok := LuaCheckNumber(L, n) + if !ok { return 0, false } + return ToBit(x), true +} + +BitToBit :: (L: *LuaState) -> s32 { + x, ok := BitArg(L, 1) + if !ok { return LUA_NATIVE_ERROR } + return BitResult(L, x) +} + +BitBnot :: (L: *LuaState) -> s32 { + x, ok := BitArg(L, 1) + if !ok { return LUA_NATIVE_ERROR } + return BitResult(L, ~x) +} + +BIT_AND :: 0; +BIT_OR :: 1; +BIT_XOR :: 2; + +BitFold :: (L: *LuaState, op: s32) -> s32 { + x, ok := BitArg(L, 1) + if !ok { return LUA_NATIVE_ERROR } + n := ArgCount(L) + i: s32 = 2 + while i <= n { + y, oky := BitArg(L, i) + if !oky { return LUA_NATIVE_ERROR } + if op == BIT_AND { x &= y } else if op == BIT_OR { x |= y } else { x ^= y } + i += 1 + } + return BitResult(L, x) +} + +BitBand :: (L: *LuaState) -> s32 { return BitFold(L, BIT_AND) } +BitBor :: (L: *LuaState) -> s32 { return BitFold(L, BIT_OR) } +BitBxor :: (L: *LuaState) -> s32 { return BitFold(L, BIT_XOR) } + +ShiftArgs :: (L: *LuaState) -> (x: u32, n: u32, ok: bool) { + x, ok1 := BitArg(L, 1) + if !ok1 { return 0, 0, false } + n, ok2 := BitArg(L, 2) + if !ok2 { return 0, 0, false } + return x, n & 31, true +} + +BitLshift :: (L: *LuaState) -> s32 { + x, n, ok := ShiftArgs(L) + if !ok { return LUA_NATIVE_ERROR } + return BitResult(L, x << n) +} + +BitRshift :: (L: *LuaState) -> s32 { + x, n, ok := ShiftArgs(L) + if !ok { return LUA_NATIVE_ERROR } + return BitResult(L, x >> n) +} + +BitArshift :: (L: *LuaState) -> s32 { + x, n, ok := ShiftArgs(L) + if !ok { return LUA_NATIVE_ERROR } + return BitResult(L, cast(u32)(cast(s32) x >> cast(s32) n)) +} + +BitRol :: (L: *LuaState) -> s32 { + x, n, ok := ShiftArgs(L) + if !ok { return LUA_NATIVE_ERROR } + if n == 0 { return BitResult(L, x) } + return BitResult(L, (x << n) | (x >> (32 - n))) +} + +BitRor :: (L: *LuaState) -> s32 { + x, n, ok := ShiftArgs(L) + if !ok { return LUA_NATIVE_ERROR } + if n == 0 { return BitResult(L, x) } + return BitResult(L, (x >> n) | (x << (32 - n))) +} + +BitBswap :: (L: *LuaState) -> s32 { + x, ok := BitArg(L, 1) + if !ok { return LUA_NATIVE_ERROR } + y := (x >> 24) | ((x >> 8) & 0xFF00) | ((x << 8) & 0xFF0000) | (x << 24) + return BitResult(L, y) +} + +BitTohex :: (L: *LuaState) -> s32 { + x, ok := BitArg(L, 1) + if !ok { return LUA_NATIVE_ERROR } + n: s64 = 8 + if Arg(L, 2).t != LUA_TNIL { + value, okn := BitArg(L, 2) + if !okn { return LUA_NATIVE_ERROR } + n = cast(s64) cast(s32) value + } + upper := false + if n < 0 { + upper = true + n = -n + } + if n > 8 { n = 8 } + digits := ifx upper then "0123456789ABCDEF" else "0123456789abcdef" + out: Vec(u8) + i := n - 1 + while i >= 0 { + VecPush(out, digits[cast(s64)((x >> cast(u32)(i * 4)) & 15)]) + i -= 1 + } + Push(L, StringValue(InternBytes(L, *out))) + VecFree(out) + return 1 +} + +OpenBit :: (L: *LuaState) { + t := NewTable(L, 0, 12) + RegisterLibrary(L, "bit", t) + SetNative(L, t, "tobit", BitToBit) + SetNative(L, t, "tohex", BitTohex) + SetNative(L, t, "bnot", BitBnot) + SetNative(L, t, "band", BitBand) + SetNative(L, t, "bor", BitBor) + SetNative(L, t, "bxor", BitBxor) + SetNative(L, t, "lshift", BitLshift) + SetNative(L, t, "rshift", BitRshift) + SetNative(L, t, "arshift", BitArshift) + SetNative(L, t, "rol", BitRol) + SetNative(L, t, "ror", BitRor) + SetNative(L, t, "bswap", BitBswap) +} diff --git a/src/lib_debug.zi b/src/lib_debug.zi new file mode 100644 index 0000000..2ed7bf9 --- /dev/null +++ b/src/lib_debug.zi @@ -0,0 +1,299 @@ +// The debug library subset mods use: traceback, getinfo, locals and +// upvalues, raw metatables, the registry and inert hooks. + +#scope_module + +// An optional thread first argument: the thread and the argument shift. +ThreadArg :: (L: *LuaState) -> (thread: s32, shift: s32) { + v := Arg(L, 1) + if v.t == LUA_TTHREAD { return v.h, 1 } + return L.cur, 0 +} + +DebugTraceback :: (L: *LuaState) -> s32 { + thread, shift := ThreadArg(L) + message := Arg(L, 1 + shift) + if message.t != LUA_TNIL && !IsStringLike(message) { return ReturnValue(L, message) } + fallback: s64 = ifx thread == L.cur then 1 else 0 + level, ok := LuaOptInteger(L, 2 + shift, fallback) + if !ok { return LUA_NATIVE_ERROR } + text: Vec(u8) + if message.t == LUA_TSTRING { + BuilderAppend(text, StrView(L, message.h)) + VecPush(text, 10) + } else if message.t == LUA_TNUMBER { + AppendNumber(*text, message.n) + VecPush(text, 10) + } + if level < 0 { level = 0 } + AppendTraceback(L, *text, thread, cast(s32) level) + Push(L, StringValue(InternBytes(L, *text))) + VecFree(text) + return 1 +} + +// Error handler for CallWithTraceback: message plus the stack below it. +TracebackHandler :: (L: *LuaState) -> s32 { + message := Arg(L, 1) + if message.t != LUA_TNIL && !IsStringLike(message) { return ReturnValue(L, message) } + text: Vec(u8) + if message.t == LUA_TSTRING { + BuilderAppend(text, StrView(L, message.h)) + } else if message.t == LUA_TNUMBER { + AppendNumber(*text, message.n) + } else { + BuilderAppend(text, "(error object is nil)") + } + VecPush(text, 10) + AppendTraceback(L, *text, L.cur, 1) + Push(L, StringValue(InternBytes(L, *text))) + VecFree(text) + return 1 +} + +HasOption :: (what: string, c: u8) -> bool { + i: s64 = 0 + while i < what.count { + if what[i] == c { return true } + i += 1 + } + return false +} + +// Fill the info table for closure cl, with frame details when frame >= 0. +FillInfo :: (L: *LuaState, t: s32, what: string, cl: s32, thread: s32, frame: s64) { + p := L.closures[cl].proto + if HasOption(what, #char "S") { + if p < 0 { + SetValue(L, t, "source", StringValue(Intern(L, "=[C]"))) + SetValue(L, t, "short_src", StringValue(Intern(L, "[C]"))) + SetValue(L, t, "what", StringValue(Intern(L, "C"))) + SetValue(L, t, "linedefined", NumberValue(-1.0)) + SetValue(L, t, "lastlinedefined", NumberValue(-1.0)) + } else { + source := L.protos[p].source + SetValue(L, t, "source", ifx source >= 0 then StringValue(source) else StringValue(Intern(L, "=?"))) + short: Vec(u8) + AppendChunkId(L, *short, source) + SetValue(L, t, "short_src", StringValue(InternBytes(L, *short))) + VecFree(short) + main := L.protos[p].line_defined == 0 + SetValue(L, t, "what", StringValue(Intern(L, ifx main then "main" else "Lua"))) + SetValue(L, t, "linedefined", NumberValue(cast(float64) L.protos[p].line_defined)) + SetValue(L, t, "lastlinedefined", NumberValue(cast(float64)(ifx main then -1 else L.protos[p].last_line))) + } + } + if HasOption(what, #char "l") { + line: s32 = -1 + if frame >= 0 { line = FrameLine(L, thread, frame) } + SetValue(L, t, "currentline", NumberValue(cast(float64) line)) + } + if HasOption(what, #char "u") { + n := ifx p < 0 then L.closures[cl].native_upvals.count else L.closures[cl].upvals.count + SetValue(L, t, "nups", NumberValue(cast(float64) n)) + } + if HasOption(what, #char "n") && frame >= 0 { + kind, name := FrameFunctionName(L, thread, frame) + if kind != NAME_NONE { + if name == -2 { + SetValue(L, t, "name", StringValue(Intern(L, "for iterator"))) + SetValue(L, t, "namewhat", StringValue(Intern(L, "for iterator"))) + } else { + SetValue(L, t, "name", StringValue(name)) + SetValue(L, t, "namewhat", StringValue(Intern(L, NameKindText(kind)))) + } + } else { + SetValue(L, t, "namewhat", StringValue(Intern(L, ""))) + } + } + if HasOption(what, #char "f") { SetValue(L, t, "func", FunctionValue(cl)) } +} + +DebugGetinfo :: (L: *LuaState) -> s32 { + thread, shift := ThreadArg(L) + what, ok := LuaOptString(L, 2 + shift, "flnSu") + if !ok { return LUA_NATIVE_ERROR } + target := Arg(L, 1 + shift) + if what.count > 0 && what[0] == #char ">" { what = what[1:] } + t := NewTable(L, 0, 12) + if target.t == LUA_TFUNCTION { + FillInfo(L, t, what, target.h, thread, -1) + return ReturnValue(L, TableValue(t)) + } + if target.t != LUA_TNUMBER { return LuaArgError(L, 1 + shift, "function or level expected") } + level := SafeInteger(target.n) + // Level 0 is getinfo itself on the running thread. + frame := L.threads[thread].frames.count - 1 - level + if level < 0 || frame < 0 { return ReturnNil(L) } + FillInfo(L, t, what, L.threads[thread].frames[frame].closure, thread, frame) + return ReturnValue(L, TableValue(t)) +} + +Unbox :: (L: *LuaState, v: LuaValue) -> LuaValue #inline { + if v.t == LUA_TBOX { return L.boxes[v.h].value } + return v +} + +// The n-th active local of the frame: register and name, or -1. +ActiveLocal :: (L: *LuaState, thread: s32, frame: s64, n: s64) -> (reg: s32, name: s32) { + if L.threads[thread].frames[frame].native { return -1, -1 } + cl := L.threads[thread].frames[frame].closure + p := L.closures[cl].proto + pc := cast(s64) L.threads[thread].frames[frame].pc - 1 + if pc < 0 { pc = 0 } + count: s64 = 0 + i: s64 = 0 + while i < L.protos[p].locvars.count { + lv := L.protos[p].locvars[i] + if lv.start_pc > pc { break } + if lv.end_pc < 0 || pc < lv.end_pc { + count += 1 + if count == n { return lv.reg, lv.name } + } + i += 1 + } + return -1, -1 +} + +LocalFrame :: (L: *LuaState, thread: s32, level: s64) -> s64 { + frame := L.threads[thread].frames.count - 1 - level + if level < 0 || frame < 0 { return -1 } + return frame +} + +DebugGetlocal :: (L: *LuaState) -> s32 { + thread, shift := ThreadArg(L) + level, ok1 := LuaCheckInteger(L, 1 + shift) + if !ok1 { return LUA_NATIVE_ERROR } + n, ok2 := LuaCheckInteger(L, 2 + shift) + if !ok2 { return LUA_NATIVE_ERROR } + frame := LocalFrame(L, thread, level) + if frame < 0 { return LuaArgError(L, 1 + shift, "level out of range") } + reg, name := ActiveLocal(L, thread, frame, n) + if reg < 0 { return ReturnNil(L) } + base := L.threads[thread].frames[frame].base + Push(L, StringValue(name)) + Push(L, Unbox(L, L.threads[thread].stack[base + reg])) + return 2 +} + +DebugSetlocal :: (L: *LuaState) -> s32 { + thread, shift := ThreadArg(L) + level, ok1 := LuaCheckInteger(L, 1 + shift) + if !ok1 { return LUA_NATIVE_ERROR } + n, ok2 := LuaCheckInteger(L, 2 + shift) + if !ok2 { return LUA_NATIVE_ERROR } + frame := LocalFrame(L, thread, level) + if frame < 0 { return LuaArgError(L, 1 + shift, "level out of range") } + reg, name := ActiveLocal(L, thread, frame, n) + if reg < 0 { return ReturnNil(L) } + slot := L.threads[thread].frames[frame].base + reg + value := Arg(L, 3 + shift) + current := L.threads[thread].stack[slot] + if current.t == LUA_TBOX { L.boxes[current.h].value = value } else { L.threads[thread].stack[slot] = value } + return ReturnValue(L, StringValue(name)) +} + +DebugGetupvalue :: (L: *LuaState) -> s32 { + f := Arg(L, 1) + if f.t != LUA_TFUNCTION { return LuaTypeError(L, 1, "function") } + n, ok := LuaCheckInteger(L, 2) + if !ok { return LUA_NATIVE_ERROR } + cl := f.h + p := L.closures[cl].proto + if p < 0 { + if n < 1 || n > L.closures[cl].native_upvals.count { return 0 } + Push(L, StringValue(Intern(L, ""))) + Push(L, L.closures[cl].native_upvals[n - 1]) + return 2 + } + if n < 1 || n > L.closures[cl].upvals.count { return 0 } + name := ifx n <= L.protos[p].upval_names.count then L.protos[p].upval_names[n - 1] else -1 + Push(L, ifx name >= 0 then StringValue(name) else StringValue(Intern(L, "?"))) + Push(L, L.boxes[L.closures[cl].upvals[n - 1]].value) + return 2 +} + +DebugSetupvalue :: (L: *LuaState) -> s32 { + f := Arg(L, 1) + if f.t != LUA_TFUNCTION { return LuaTypeError(L, 1, "function") } + n, ok := LuaCheckInteger(L, 2) + if !ok { return LUA_NATIVE_ERROR } + if !LuaCheckAny(L, 3) { return LUA_NATIVE_ERROR } + cl := f.h + p := L.closures[cl].proto + value := Arg(L, 3) + if p < 0 { + if n < 1 || n > L.closures[cl].native_upvals.count { return 0 } + L.closures[cl].native_upvals[n - 1] = value + return ReturnValue(L, StringValue(Intern(L, ""))) + } + if n < 1 || n > L.closures[cl].upvals.count { return 0 } + L.boxes[L.closures[cl].upvals[n - 1]].value = value + name := ifx n <= L.protos[p].upval_names.count then L.protos[p].upval_names[n - 1] else -1 + return ReturnValue(L, ifx name >= 0 then StringValue(name) else StringValue(Intern(L, "?"))) +} + +DebugGetmetatable :: (L: *LuaState) -> s32 { + if !LuaCheckAny(L, 1) { return LUA_NATIVE_ERROR } + mt := MetatableOf(L, Arg(L, 1)) + if mt < 0 { return ReturnNil(L) } + return ReturnValue(L, TableValue(mt)) +} + +DebugSetmetatable :: (L: *LuaState) -> s32 { + v := Arg(L, 1) + m := Arg(L, 2) + if m.t != LUA_TNIL && m.t != LUA_TTABLE { return LuaArgError(L, 2, "nil or table expected") } + mt: s32 = ifx m.t == LUA_TTABLE then m.h else -1 + if v.t == LUA_TTABLE { + L.tables[v.h].meta = mt + } else if v.t == LUA_TUSERDATA { + L.userdata[v.h].meta = mt + } else if v.t < 11 { + L.type_meta[v.t] = mt + } + return ReturnValue(L, BoolValue(true)) +} + +DebugGetregistry :: (L: *LuaState) -> s32 { return ReturnValue(L, TableValue(L.registry)) } + +DebugGetfenv :: (L: *LuaState) -> s32 { + v := Arg(L, 1) + if v.t == LUA_TFUNCTION && L.closures[v.h].env >= 0 { return ReturnValue(L, TableValue(L.closures[v.h].env)) } + if v.t == LUA_TUSERDATA && L.userdata[v.h].env >= 0 { return ReturnValue(L, TableValue(L.userdata[v.h].env)) } + if v.t == LUA_TTHREAD && L.threads[v.h].env >= 0 { return ReturnValue(L, TableValue(L.threads[v.h].env)) } + return ReturnNil(L) +} + +DebugSetfenv :: (L: *LuaState) -> s32 { + v := Arg(L, 1) + e := Arg(L, 2) + if e.t != LUA_TTABLE { return LuaTypeError(L, 2, "table") } + if v.t == LUA_TFUNCTION { L.closures[v.h].env = e.h } + else if v.t == LUA_TUSERDATA { L.userdata[v.h].env = e.h } + else if v.t == LUA_TTHREAD { L.threads[v.h].env = e.h } + else { return LuaErrorText(L, "'setfenv' cannot change environment of given object") } + return ReturnValue(L, v) +} + +DebugSethook :: (L: *LuaState) -> s32 { return 0 } +DebugGethook :: (L: *LuaState) -> s32 { return ReturnNil(L) } + +OpenDebug :: (L: *LuaState) { + t := NewTable(L, 0, 16) + RegisterLibrary(L, "debug", t) + SetNative(L, t, "traceback", DebugTraceback) + SetNative(L, t, "getinfo", DebugGetinfo) + SetNative(L, t, "getlocal", DebugGetlocal) + SetNative(L, t, "setlocal", DebugSetlocal) + SetNative(L, t, "getupvalue", DebugGetupvalue) + SetNative(L, t, "setupvalue", DebugSetupvalue) + SetNative(L, t, "getmetatable", DebugGetmetatable) + SetNative(L, t, "setmetatable", DebugSetmetatable) + SetNative(L, t, "getregistry", DebugGetregistry) + SetNative(L, t, "getfenv", DebugGetfenv) + SetNative(L, t, "setfenv", DebugSetfenv) + SetNative(L, t, "sethook", DebugSethook) + SetNative(L, t, "gethook", DebugGethook) +} diff --git a/src/lib_math.zi b/src/lib_math.zi new file mode 100644 index 0000000..28d92d2 --- /dev/null +++ b/src/lib_math.zi @@ -0,0 +1,289 @@ +// Math library of Lua 5.1 on Ziran's std/math, with LuaJIT's math.log base. + +#scope_module + +PI :: 3.141592653589793; + +NumberArg :: (L: *LuaState, n: s32) -> (value: float64, ok: bool) #inline { + return LuaCheckNumber(L, n) +} + +ReturnNumber :: (L: *LuaState, x: float64) -> s32 #inline { + Push(L, NumberValue(x)) + return 1 +} + +MathAbs :: (L: *LuaState) -> s32 { + x, ok := NumberArg(L, 1) + if !ok { return LUA_NATIVE_ERROR } + return ReturnNumber(L, ifx x < 0.0 then -x else (ifx x == 0.0 then 0.0 else x)) +} +MathCeil :: (L: *LuaState) -> s32 { + x, ok := NumberArg(L, 1) + if !ok { return LUA_NATIVE_ERROR } + return ReturnNumber(L, Ceil(x)) +} +MathFloor :: (L: *LuaState) -> s32 { + x, ok := NumberArg(L, 1) + if !ok { return LUA_NATIVE_ERROR } + return ReturnNumber(L, Floor(x)) +} +MathSqrt :: (L: *LuaState) -> s32 { + x, ok := NumberArg(L, 1) + if !ok { return LUA_NATIVE_ERROR } + return ReturnNumber(L, Sqrt(x)) +} +MathSin :: (L: *LuaState) -> s32 { + x, ok := NumberArg(L, 1) + if !ok { return LUA_NATIVE_ERROR } + return ReturnNumber(L, Sin(x)) +} +MathCos :: (L: *LuaState) -> s32 { + x, ok := NumberArg(L, 1) + if !ok { return LUA_NATIVE_ERROR } + return ReturnNumber(L, Cos(x)) +} +MathTan :: (L: *LuaState) -> s32 { + x, ok := NumberArg(L, 1) + if !ok { return LUA_NATIVE_ERROR } + return ReturnNumber(L, Tan(x)) +} +MathAsin :: (L: *LuaState) -> s32 { + x, ok := NumberArg(L, 1) + if !ok { return LUA_NATIVE_ERROR } + return ReturnNumber(L, Asin(x)) +} +MathAcos :: (L: *LuaState) -> s32 { + x, ok := NumberArg(L, 1) + if !ok { return LUA_NATIVE_ERROR } + return ReturnNumber(L, Acos(x)) +} +MathAtan :: (L: *LuaState) -> s32 { + x, ok := NumberArg(L, 1) + if !ok { return LUA_NATIVE_ERROR } + return ReturnNumber(L, Atan(x)) +} +MathAtan2 :: (L: *LuaState) -> s32 { + y, ok1 := NumberArg(L, 1) + if !ok1 { return LUA_NATIVE_ERROR } + x, ok2 := NumberArg(L, 2) + if !ok2 { return LUA_NATIVE_ERROR } + return ReturnNumber(L, Atan2(y, x)) +} +MathSinh :: (L: *LuaState) -> s32 { + x, ok := NumberArg(L, 1) + if !ok { return LUA_NATIVE_ERROR } + return ReturnNumber(L, Sinh(x)) +} +MathCosh :: (L: *LuaState) -> s32 { + x, ok := NumberArg(L, 1) + if !ok { return LUA_NATIVE_ERROR } + return ReturnNumber(L, Cosh(x)) +} +MathTanh :: (L: *LuaState) -> s32 { + x, ok := NumberArg(L, 1) + if !ok { return LUA_NATIVE_ERROR } + return ReturnNumber(L, Tanh(x)) +} +MathExp :: (L: *LuaState) -> s32 { + x, ok := NumberArg(L, 1) + if !ok { return LUA_NATIVE_ERROR } + return ReturnNumber(L, Exp(x)) +} +MathLog :: (L: *LuaState) -> s32 { + x, ok := NumberArg(L, 1) + if !ok { return LUA_NATIVE_ERROR } + if Arg(L, 2).t == LUA_TNIL { return ReturnNumber(L, Log(x)) } + base, ok2 := NumberArg(L, 2) + if !ok2 { return LUA_NATIVE_ERROR } + if base == 2.0 { return ReturnNumber(L, Log2(x)) } + if base == 10.0 { return ReturnNumber(L, Log10(x)) } + return ReturnNumber(L, Log(x) / Log(base)) +} +MathLog10 :: (L: *LuaState) -> s32 { + x, ok := NumberArg(L, 1) + if !ok { return LUA_NATIVE_ERROR } + return ReturnNumber(L, Log10(x)) +} +MathPow :: (L: *LuaState) -> s32 { + x, ok1 := NumberArg(L, 1) + if !ok1 { return LUA_NATIVE_ERROR } + y, ok2 := NumberArg(L, 2) + if !ok2 { return LUA_NATIVE_ERROR } + return ReturnNumber(L, LuaPow(x, y)) +} +MathFmod :: (L: *LuaState) -> s32 { + x, ok1 := NumberArg(L, 1) + if !ok1 { return LUA_NATIVE_ERROR } + y, ok2 := NumberArg(L, 2) + if !ok2 { return LUA_NATIVE_ERROR } + return ReturnNumber(L, Fmod(x, y)) +} +MathModf :: (L: *LuaState) -> s32 { + x, ok := NumberArg(L, 1) + if !ok { return LUA_NATIVE_ERROR } + if x == Infinity() || x == -Infinity() { + Push(L, NumberValue(x)) + Push(L, NumberValue(0.0)) + return 2 + } + whole := Trunc(x) + Push(L, NumberValue(whole)) + Push(L, NumberValue(ifx x != x then x else x - whole)) + return 2 +} +MathFrexp :: (L: *LuaState) -> s32 { + x, ok := NumberArg(L, 1) + if !ok { return LUA_NATIVE_ERROR } + if x == 0.0 || x != x || x == Infinity() || x == -Infinity() { + Push(L, NumberValue(x)) + Push(L, NumberValue(0.0)) + return 2 + } + bits: NumberBits + bits.f = x + exponent := cast(s64)((bits.u >> 52) & 2047) + adjust: s64 = 0 + if exponent == 0 { + // Subnormal: scale into the normal range first. + bits.f = x * 18014398509481984.0 + exponent = cast(s64)((bits.u >> 52) & 2047) + adjust = -54 + } + bits.u = (bits.u & ~(cast(u64) 2047 << 52)) | (cast(u64) 1022 << 52) + Push(L, NumberValue(bits.f)) + Push(L, NumberValue(cast(float64)(exponent - 1022 + adjust))) + return 2 +} +MathLdexp :: (L: *LuaState) -> s32 { + x, ok1 := NumberArg(L, 1) + if !ok1 { return LUA_NATIVE_ERROR } + e, ok2 := LuaCheckInteger(L, 2) + if !ok2 { return LUA_NATIVE_ERROR } + if e > 4096 { e = 4096 } + if e < -4096 { e = -4096 } + return ReturnNumber(L, ScaleByPowerOfTwo(x, cast(s32) e)) +} +MathDeg :: (L: *LuaState) -> s32 { + x, ok := NumberArg(L, 1) + if !ok { return LUA_NATIVE_ERROR } + return ReturnNumber(L, x * (180.0 / PI)) +} +MathRad :: (L: *LuaState) -> s32 { + x, ok := NumberArg(L, 1) + if !ok { return LUA_NATIVE_ERROR } + return ReturnNumber(L, x * (PI / 180.0)) +} +MathMin :: (L: *LuaState) -> s32 { + n := ArgCount(L) + best, ok := NumberArg(L, 1) + if !ok { return LUA_NATIVE_ERROR } + i: s32 = 2 + while i <= n { + x, okx := NumberArg(L, i) + if !okx { return LUA_NATIVE_ERROR } + if x < best { best = x } + i += 1 + } + return ReturnNumber(L, best) +} +MathMax :: (L: *LuaState) -> s32 { + n := ArgCount(L) + best, ok := NumberArg(L, 1) + if !ok { return LUA_NATIVE_ERROR } + i: s32 = 2 + while i <= n { + x, okx := NumberArg(L, i) + if !okx { return LUA_NATIVE_ERROR } + if x > best { best = x } + i += 1 + } + return ReturnNumber(L, best) +} + +// xorshift64* state lives in the LuaState. +RandomNext :: (L: *LuaState) -> float64 { + x := L.random_state + if x == 0 { x = 0x9E3779B97F4A7C15 } + x ^= x >> 12 + x ^= x << 25 + x ^= x >> 27 + L.random_state = x + r := x * 0x2545F4914F6CDD1D + // 53 random bits into [0, 1). + return cast(float64)(r >> 11) * (1.0 / 9007199254740992.0) +} + +MathRandom :: (L: *LuaState) -> s32 { + r := RandomNext(L) + n := ArgCount(L) + if n == 0 { return ReturnNumber(L, r) } + if n == 1 { + u, ok := NumberArg(L, 1) + if !ok { return LUA_NATIVE_ERROR } + u = Floor(u) + if u < 1.0 { return LuaArgError(L, 1, "interval is empty") } + return ReturnNumber(L, Floor(r * u) + 1.0) + } + if n == 2 { + l, ok1 := NumberArg(L, 1) + if !ok1 { return LUA_NATIVE_ERROR } + u, ok2 := NumberArg(L, 2) + if !ok2 { return LUA_NATIVE_ERROR } + l = Floor(l) + u = Floor(u) + if l > u { return LuaArgError(L, 2, "interval is empty") } + return ReturnNumber(L, Floor(r * (u - l + 1.0)) + l) + } + return LuaErrorText(L, "wrong number of arguments") +} + +MathRandomSeed :: (L: *LuaState) -> s32 { + x, ok := NumberArg(L, 1) + if !ok { return LUA_NATIVE_ERROR } + bits: NumberBits + bits.f = x + L.random_state = MixHash(bits.u ^ 0x9E3779B97F4A7C15) + if L.random_state == 0 { L.random_state = 1 } + // Discard a few values like LuaJIT does after seeding. + i := 0 + while i < 10 { RandomNext(L); i += 1 } + return 0 +} + +OpenMath :: (L: *LuaState) { + t := NewTable(L, 0, 32) + RegisterLibrary(L, "math", t) + SetNative(L, t, "abs", MathAbs) + SetNative(L, t, "ceil", MathCeil) + SetNative(L, t, "floor", MathFloor) + SetNative(L, t, "sqrt", MathSqrt) + SetNative(L, t, "sin", MathSin) + SetNative(L, t, "cos", MathCos) + SetNative(L, t, "tan", MathTan) + SetNative(L, t, "asin", MathAsin) + SetNative(L, t, "acos", MathAcos) + SetNative(L, t, "atan", MathAtan) + SetNative(L, t, "atan2", MathAtan2) + SetNative(L, t, "sinh", MathSinh) + SetNative(L, t, "cosh", MathCosh) + SetNative(L, t, "tanh", MathTanh) + SetNative(L, t, "exp", MathExp) + SetNative(L, t, "log", MathLog) + SetNative(L, t, "log10", MathLog10) + SetNative(L, t, "pow", MathPow) + SetNative(L, t, "fmod", MathFmod) + SetNative(L, t, "mod", MathFmod) + SetNative(L, t, "modf", MathModf) + SetNative(L, t, "frexp", MathFrexp) + SetNative(L, t, "ldexp", MathLdexp) + SetNative(L, t, "deg", MathDeg) + SetNative(L, t, "rad", MathRad) + SetNative(L, t, "min", MathMin) + SetNative(L, t, "max", MathMax) + SetNative(L, t, "random", MathRandom) + SetNative(L, t, "randomseed", MathRandomSeed) + SetValue(L, t, "pi", NumberValue(PI)) + SetValue(L, t, "huge", NumberValue(Infinity())) + L.random_state = 0x2545F4914F6CDD1D +} diff --git a/src/lib_os.zi b/src/lib_os.zi new file mode 100644 index 0000000..7d4d3ba --- /dev/null +++ b/src/lib_os.zi @@ -0,0 +1,595 @@ +// Sandboxed os and io subsets: clocks and dates, environment reads the host +// allows, io.write through the print sink and read-only files under the +// file root. Nothing here writes files or runs processes. + +#scope_module + +DaysFromCivil :: (year: s64, month: s64, day: s64) -> s64 { + y := ifx month <= 2 then year - 1 else year + era := (ifx y >= 0 then y else y - 399) / 400 + yoe := y - era * 400 + mp := ifx month > 2 then month - 3 else month + 9 + doy := (153 * mp + 2) / 5 + day - 1 + doe := yoe * 365 + yoe / 4 - yoe / 100 + doy + return era * 146097 + doe - 719468 +} + +FloorDiv :: (a: s64, b: s64) -> s64 #inline { + q := a / b + if (a % b != 0) && ((a < 0) != (b < 0)) { q -= 1 } + return q +} + +CivilSeconds :: (when: LocalDateTime) -> s64 { + days := DaysFromCivil(cast(s64) when.year, cast(s64) when.month, cast(s64) when.day) + return days * 86400 + cast(s64) when.hour * 3600 + cast(s64) when.minute * 60 + cast(s64) when.second +} + +// 0 = Sunday. +WeekDay :: (when: LocalDateTime) -> s64 { + days := DaysFromCivil(cast(s64) when.year, cast(s64) when.month, cast(s64) when.day) + w := (days + 4) % 7 + if w < 0 { w += 7 } + return w +} + +FieldInteger :: (L: *LuaState, t: s32, name: string, fallback: s64, required: bool, ok: *bool) -> s64 { + v := GetStr(L, t, Intern(L, name)) + if v.t == LUA_TNUMBER { return SafeInteger(Floor(v.n)) } + if v.t == LUA_TSTRING { + n, converted := ParseNumberText(StrView(L, v.h)) + if converted { return SafeInteger(Floor(n)) } + } + if required { + text: Vec(u8) + BuilderAppend(text, "field '") + BuilderAppend(text, name) + BuilderAppend(text, "' missing in date table") + LuaErrorText(L, BytesView(*text)) + VecFree(text) + < s32 { + v := Arg(L, 1) + if v.t == LUA_TNIL { return ReturnValue(L, NumberValue(cast(float64) UnixNow())) } + if v.t != LUA_TTABLE { return LuaTypeError(L, 1, "table") } + ok := true + t := v.h + second := FieldInteger(L, t, "sec", 0, false, *ok) + minute := FieldInteger(L, t, "min", 0, false, *ok) + hour := FieldInteger(L, t, "hour", 12, false, *ok) + day := FieldInteger(L, t, "day", 0, true, *ok) + if !ok { return LUA_NATIVE_ERROR } + month := FieldInteger(L, t, "month", 0, true, *ok) + if !ok { return LUA_NATIVE_ERROR } + year := FieldInteger(L, t, "year", 0, true, *ok) + if !ok { return LUA_NATIVE_ERROR } + // Normalize the month like mktime; days, hours and so on add linearly. + year += FloorDiv(month - 1, 12) + month = month - 1 - FloorDiv(month - 1, 12) * 12 + 1 + guess := DaysFromCivil(year, month, 1) * 86400 + (day - 1) * 86400 + hour * 3600 + minute * 60 + second + // The fields are local time: subtract the zone offset at that moment. + local := LocalAt(guess) + if local.valid { + offset := CivilSeconds(local) - guess + result := guess - offset + again := LocalAt(result) + if again.valid { result = guess - (CivilSeconds(again) - result) } + return ReturnValue(L, NumberValue(cast(float64) result)) + } + return ReturnValue(L, NumberValue(cast(float64) guess)) +} + +OsClock :: (L: *LuaState) -> s32 { + elapsed := MonotonicNanoseconds() - L.clock_start + return ReturnValue(L, NumberValue(cast(float64) elapsed / 1000000000.0)) +} + +OsDifftime :: (L: *LuaState) -> s32 { + a, ok1 := LuaCheckNumber(L, 1) + if !ok1 { return LUA_NATIVE_ERROR } + b, ok2 := LuaOptNumber(L, 2, 0.0) + if !ok2 { return LUA_NATIVE_ERROR } + return ReturnValue(L, NumberValue(a - b)) +} + +DAY_NAMES :: "SunMonTueWedThuFriSat"; +MONTH_NAMES :: "JanFebMarAprMayJunJulAugSepOctNovDec"; + +DayFullName :: (w: s64) -> string { + if w == 0 { return "Sunday" } + if w == 1 { return "Monday" } + if w == 2 { return "Tuesday" } + if w == 3 { return "Wednesday" } + if w == 4 { return "Thursday" } + if w == 5 { return "Friday" } + return "Saturday" +} + +MonthFullName :: (m: s64) -> string { + if m == 1 { return "January" } + if m == 2 { return "February" } + if m == 3 { return "March" } + if m == 4 { return "April" } + if m == 5 { return "May" } + if m == 6 { return "June" } + if m == 7 { return "July" } + if m == 8 { return "August" } + if m == 9 { return "September" } + if m == 10 { return "October" } + if m == 11 { return "November" } + return "December" +} + +AppendTwo :: (out: *Vec(u8), value: s64, pad: u8) { + if value < 10 { + VecPush(< bool { + wday := WeekDay(when) + if conv == #char "a" { BuilderAppend(< s32 { + format, ok := LuaOptString(L, 1, "%c") + if !ok { return LUA_NATIVE_ERROR } + seconds: s64 = 0 + if Arg(L, 2).t == LUA_TNIL { + seconds = UnixNow() + } else { + n, okn := LuaCheckNumber(L, 2) + if !okn { return LUA_NATIVE_ERROR } + seconds = SafeInteger(Floor(n)) + } + utc := false + text := format + if text.count > 0 && text[0] == #char "!" { + utc = true + text = text[1:] + } + when := ifx utc then UtcAt(seconds) else LocalAt(seconds) + if !when.valid { return ReturnNil(L) } + if text.count >= 2 && text[0] == #char "*" && text[1] == #char "t" { + t := NewTable(L, 0, 9) + SetValue(L, t, "year", NumberValue(cast(float64) when.year)) + SetValue(L, t, "month", NumberValue(cast(float64) when.month)) + SetValue(L, t, "day", NumberValue(cast(float64) when.day)) + SetValue(L, t, "hour", NumberValue(cast(float64) when.hour)) + SetValue(L, t, "min", NumberValue(cast(float64) when.minute)) + SetValue(L, t, "sec", NumberValue(cast(float64) when.second)) + SetValue(L, t, "wday", NumberValue(cast(float64)(WeekDay(when) + 1))) + SetValue(L, t, "yday", NumberValue(cast(float64)(when.day_of_year + 1))) + SetValue(L, t, "isdst", BoolValue(false)) + return ReturnValue(L, TableValue(t)) + } + out: Vec(u8) + i: s64 = 0 + while i < text.count { + c := text[i] + if c == #char "%" && i + 1 < text.count { + conv := text[i + 1] + if !AppendDateField(*out, conv, when, utc) { + VecPush(out, #char "%") + VecPush(out, conv) + } + i += 2 + continue + } + VecPush(out, c) + i += 1 + } + Push(L, StringValue(InternBytes(L, *out))) + VecFree(out) + return 1 +} + +// Allowed when a host prefix (separated by 0 bytes) starts the name. +EnvironmentAllowed :: (L: *LuaState, name: string) -> bool { + prefixes := BytesView(*L.env_allow) + start: s64 = 0 + i: s64 = 0 + while i <= prefixes.count { + if i == prefixes.count || prefixes[i] == 0 { + length := i - start + if length > 0 && name.count >= length && name[0:length] == prefixes[start:i] { return true } + start = i + 1 + } + i += 1 + } + return false +} + +OsGetenv :: (L: *LuaState) -> s32 { + name, ok := LuaCheckString(L, 1) + if !ok { return LUA_NATIVE_ERROR } + if name.count == 0 || name.count > 200 || !EnvironmentAllowed(L, name) { return ReturnNil(L) } + value := EnvironmentText(name) + if value.count == 0 { return ReturnNil(L) } + return ReturnValue(L, StringValue(Intern(L, value))) +} + +// ---------------------------------------------------------------- io + +FILE_DATA :: 1; +FILE_POSITION :: 2; +FILE_CLOSED :: 3; +FILE_TAG :: 0x4C554146; + +IoWrite :: (L: *LuaState) -> s32 { + n := ArgCount(L) + out: Vec(u8) + i: s32 = 1 + while i <= n { + v := Arg(L, i) + if v.t == LUA_TSTRING { + BuilderAppend(out, StrView(L, v.h)) + } else if v.t == LUA_TNUMBER { + AppendNumber(*out, v.n) + } else { + VecFree(out) + return LuaTypeError(L, i, "string") + } + i += 1 + } + if out.count > 0 { EmitText(L, BytesView(*out)) } + VecFree(out) + return 0 +} + +// Methods on io.stdout/io.stderr: f:write(...) returns f. +StdWrite :: (L: *LuaState) -> s32 { + n := ArgCount(L) + out: Vec(u8) + i: s32 = 2 + while i <= n { + v := Arg(L, i) + if v.t == LUA_TSTRING { + BuilderAppend(out, StrView(L, v.h)) + } else if v.t == LUA_TNUMBER { + AppendNumber(*out, v.n) + } else { + VecFree(out) + return LuaTypeError(L, i, "string") + } + i += 1 + } + if out.count > 0 { EmitText(L, BytesView(*out)) } + VecFree(out) + return ReturnValue(L, Arg(L, 1)) +} + +StdNoop :: (L: *LuaState) -> s32 { return ReturnValue(L, Arg(L, 1)) } + +FileState :: (L: *LuaState, n: s32) -> s32 { + v := Arg(L, n) + if v.t == LUA_TUSERDATA && L.userdata[v.h].tag == FILE_TAG && L.userdata[v.h].env >= 0 { + return L.userdata[v.h].env + } + LuaTypeError(L, n, "FILE*") + return -1 +} + +OpenFileObject :: (L: *LuaState, path: string) -> bool { + full: Vec(u8) + if !ResolvePath(L, path, *full) { + VecFree(full) + return false + } + bytes: Vec(u8) + if !ReadFileInto(BytesView(*full), *bytes) { + VecFree(bytes) + VecFree(full) + return false + } + VecFree(full) + state := NewTable(L, 3, 0) + SetInt(L, state, FILE_DATA, StringValue(InternBytes(L, *bytes))) + SetInt(L, state, FILE_POSITION, NumberValue(0.0)) + VecFree(bytes) + h := NewUserdataObject(L) + L.userdata[h].tag = FILE_TAG + L.userdata[h].env = state + L.userdata[h].meta = L.file_meta + Push(L, ObjectValue(LUA_TUSERDATA, h)) + return true +} + +IoOpen :: (L: *LuaState) -> s32 { + path, ok := LuaCheckString(L, 1) + if !ok { return LUA_NATIVE_ERROR } + mode, okm := LuaOptString(L, 2, "r") + if !okm { return LUA_NATIVE_ERROR } + if mode.count == 0 || mode[0] != #char "r" || (mode.count > 1 && mode[1] == #char "+") { + Push(L, NilValue()) + text: Vec(u8) + BuilderAppend(text, path) + BuilderAppend(text, ": writing is not allowed in this sandbox") + Push(L, StringValue(InternBytes(L, *text))) + VecFree(text) + return 2 + } + if OpenFileObject(L, path) { return 1 } + Push(L, NilValue()) + text: Vec(u8) + BuilderAppend(text, path) + BuilderAppend(text, ": No such file or directory") + Push(L, StringValue(InternBytes(L, *text))) + VecFree(text) + Push(L, NumberValue(2.0)) + return 3 +} + +// Read one item by format from the file state; false at end of file. +ReadItem :: (L: *LuaState, state: s32, format: LuaValue, out: *LuaValue) -> bool { + data := StrView(L, GetInt(L, state, FILE_DATA).h) + position := SafeInteger(GetInt(L, state, FILE_POSITION).n) + if format.t == LUA_TNUMBER { + count := SafeInteger(format.n) + if position >= data.count && count > 0 { return false } + if position >= data.count { < data.count { end = data.count } + < 0 && spec[0] == #char "*" { spec = spec[1:] } + kind: u8 = ifx spec.count > 0 then spec[0] else #char "l" + if kind == #char "a" { + <= data.count { return false } + end := position + while end < data.count && data[end] != 10 { end += 1 } + line_end := end + if kind == #char "L" && end < data.count { line_end = end + 1 } + < s32 { + if Truthy(GetInt(L, state, FILE_CLOSED)) { return LuaErrorText(L, "attempt to use a closed file") } + n := ArgCount(L) + if n < first { + v: LuaValue + if !ReadItem(L, state, NilValue(), *v) { return ReturnNil(L) } + return ReturnValue(L, v) + } + count: s32 = 0 + i := first + while i <= n { + v: LuaValue + if !ReadItem(L, state, Arg(L, i), *v) { + Push(L, NilValue()) + return count + 1 + } + Push(L, v) + count += 1 + i += 1 + } + return count +} + +FileRead :: (L: *LuaState) -> s32 { + state := FileState(L, 1) + if state < 0 { return LUA_NATIVE_ERROR } + return ReadFormats(L, state, 2) +} + +FileClose :: (L: *LuaState) -> s32 { + state := FileState(L, 1) + if state < 0 { return LUA_NATIVE_ERROR } + SetInt(L, state, FILE_CLOSED, BoolValue(true)) + return ReturnValue(L, BoolValue(true)) +} + +FileSeek :: (L: *LuaState) -> s32 { + state := FileState(L, 1) + if state < 0 { return LUA_NATIVE_ERROR } + whence, ok := LuaOptString(L, 2, "cur") + if !ok { return LUA_NATIVE_ERROR } + offset, ok2 := LuaOptInteger(L, 3, 0) + if !ok2 { return LUA_NATIVE_ERROR } + size := cast(s64) StrView(L, GetInt(L, state, FILE_DATA).h).count + position := SafeInteger(GetInt(L, state, FILE_POSITION).n) + if whence == "set" { position = offset } + else if whence == "cur" { position += offset } + else if whence == "end" { position = size + offset } + else { return LuaArgError(L, 2, "invalid option") } + if position < 0 { position = 0 } + SetInt(L, state, FILE_POSITION, NumberValue(cast(float64) position)) + return ReturnValue(L, NumberValue(cast(float64) position)) +} + +FileLinesStep :: (L: *LuaState) -> s32 { + file := IndexValue(L, LuaUpvalueIndex(1)) + state := L.userdata[file.h].env + if Truthy(GetInt(L, state, FILE_CLOSED)) { return LuaErrorText(L, "file is already closed") } + v: LuaValue + if !ReadItem(L, state, NilValue(), *v) { return ReturnNil(L) } + return ReturnValue(L, v) +} + +FileLines :: (L: *LuaState) -> s32 { + state := FileState(L, 1) + if state < 0 { return LUA_NATIVE_ERROR } + Push(L, Arg(L, 1)) + LuaPushNativeClosure(L, FileLinesStep, 1, "lines") + return 1 +} + +FileToString :: (L: *LuaState) -> s32 { + state := FileState(L, 1) + if state < 0 { return LUA_NATIVE_ERROR } + if Truthy(GetInt(L, state, FILE_CLOSED)) { return ReturnValue(L, StringValue(Intern(L, "file (closed)"))) } + text: Vec(u8) + BuilderAppend(text, "file (0x") + AppendHex(*text, cast(u64) Arg(L, 1).h, 8) + VecPush(text, #char ")") + Push(L, StringValue(InternBytes(L, *text))) + VecFree(text) + return 1 +} + +IoLines :: (L: *LuaState) -> s32 { + path, ok := LuaCheckString(L, 1) + if !ok { return LUA_NATIVE_ERROR } + if !OpenFileObject(L, path) { + text: Vec(u8) + BuilderAppend(text, path) + BuilderAppend(text, ": No such file or directory") + result := LuaErrorText(L, BytesView(*text)) + VecFree(text) + return result + } + LuaPushNativeClosure(L, FileLinesStep, 1, "lines") + return 1 +} + +IoRead :: (L: *LuaState) -> s32 { return ReturnNil(L) } + +IoType :: (L: *LuaState) -> s32 { + v := Arg(L, 1) + if v.t == LUA_TUSERDATA && L.userdata[v.h].tag == FILE_TAG { + state := L.userdata[v.h].env + closed := Truthy(GetInt(L, state, FILE_CLOSED)) + return ReturnValue(L, StringValue(Intern(L, ifx closed then "closed file" else "file"))) + } + if v.t == LUA_TUSERDATA && L.userdata[v.h].tag == FILE_TAG + 1 { + return ReturnValue(L, StringValue(Intern(L, "file"))) + } + return ReturnNil(L) +} + +OpenOs :: (L: *LuaState) { + L.clock_start = MonotonicNanoseconds() + os := NewTable(L, 0, 8) + RegisterLibrary(L, "os", os) + SetNative(L, os, "time", OsTime) + SetNative(L, os, "clock", OsClock) + SetNative(L, os, "date", OsDate) + SetNative(L, os, "difftime", OsDifftime) + SetNative(L, os, "getenv", OsGetenv) + + // File handles share one metatable with the methods as __index. + methods := NewTable(L, 0, 6) + SetNative(L, methods, "read", FileRead) + SetNative(L, methods, "lines", FileLines) + SetNative(L, methods, "close", FileClose) + SetNative(L, methods, "seek", FileSeek) + meta := NewTable(L, 0, 3) + SetStr(L, meta, L.tm_names[TM_INDEX], TableValue(methods)) + SetNative(L, meta, "__tostring", FileToString) + L.file_meta = meta + SetStr(L, L.registry, Intern(L, "FILE*"), TableValue(meta)) + + io := NewTable(L, 0, 8) + RegisterLibrary(L, "io", io) + SetNative(L, io, "write", IoWrite) + SetNative(L, io, "read", IoRead) + SetNative(L, io, "open", IoOpen) + SetNative(L, io, "lines", IoLines) + SetNative(L, io, "type", IoType) + std_methods := NewTable(L, 0, 4) + SetNative(L, std_methods, "write", StdWrite) + SetNative(L, std_methods, "flush", StdNoop) + SetNative(L, std_methods, "setvbuf", StdNoop) + std_meta := NewTable(L, 0, 1) + SetStr(L, std_meta, L.tm_names[TM_INDEX], TableValue(std_methods)) + i := 0 + while i < 2 { + h := NewUserdataObject(L) + L.userdata[h].tag = FILE_TAG + 1 + L.userdata[h].meta = std_meta + SetValue(L, io, ifx i == 0 then "stdout" else "stderr", ObjectValue(LUA_TUSERDATA, h)) + i += 1 + } +} diff --git a/src/lib_string.zi b/src/lib_string.zi new file mode 100644 index 0000000..17b6009 --- /dev/null +++ b/src/lib_string.zi @@ -0,0 +1,1007 @@ +// String library with Lua patterns, following lstrlib.c of Lua 5.1 and the +// LuaJIT additions Luanti code relies on (string.rep separators, %s using +// __tostring in string.format). + +#scope_module + +MAX_CAPTURES :: 32; +CAP_UNFINISHED :: -1; +CAP_POSITION :: -2; +MAX_MATCH_DEPTH :: 200; + +MatchState :: struct { + L: *LuaState + src: string + pat: string + level: s32 + depth: s32 + failed: bool + capture_start: [32]s64 + capture_len: [32]s64 +} + +MatchFail :: (ms: *MatchState, message: string) -> s64 { + if !ms.failed { + ms.failed = true + LuaErrorText(ms.L, message) + } + return -1 +} + +// Relative string positions: negative counts from the end. +StringPosition :: (position: s64, length: s64) -> s64 #inline { + if position < 0 { return length + position + 1 } + return position +} + +IsLowerByte :: (c: u8) -> bool #inline { return c >= #char "a" && c <= #char "z" } +IsUpperByte :: (c: u8) -> bool #inline { return c >= #char "A" && c <= #char "Z" } +IsControlByte :: (c: u8) -> bool #inline { return c < 32 || c == 127 } +IsPunctByte :: (c: u8) -> bool #inline { return c > 32 && c < 127 && !IsDigit(c) && !(IsAlpha(c) && c != #char "_") } + +ClassMatches :: (c: u8, cl: u8) -> bool { + lower := cl | 32 + result := false + if lower == #char "a" { result = IsAlpha(c) && c != #char "_" } + else if lower == #char "c" { result = IsControlByte(c) } + else if lower == #char "d" { result = IsDigit(c) } + else if lower == #char "l" { result = IsLowerByte(c) } + else if lower == #char "p" { result = IsPunctByte(c) } + else if lower == #char "s" { result = IsSpace(c) } + else if lower == #char "u" { result = IsUpperByte(c) } + else if lower == #char "w" { result = (IsAlpha(c) && c != #char "_") || IsDigit(c) } + else if lower == #char "x" { result = IsXDigit(c) } + else if lower == #char "z" { result = c == 0 } + else { return cl == c } + if IsUpperByte(cl) { return !result } + return result +} + +// End of the single-character class starting at p. +ClassEnd :: (ms: *MatchState, p: s64) -> s64 { + pat := ms.pat + at := p + c := pat[at] + at += 1 + if c == #char "%" { + if at >= pat.count { return MatchFail(ms, "malformed pattern (ends with '%')") } + return at + 1 + } + if c == #char "[" { + if at < pat.count && pat[at] == #char "^" { at += 1 } + // Look for the closing ']'; the first character may be ']'. + first := true + while true { + if at >= pat.count { return MatchFail(ms, "malformed pattern (missing ']')") } + cc := pat[at] + at += 1 + if cc == #char "]" && !first { return at } + first = false + if cc == #char "%" { + if at >= pat.count { return MatchFail(ms, "malformed pattern (missing ']')") } + at += 1 + } + } + } + return at +} + +// c against the set [..] spanning pat[p..ec] (p at '[', ec at ']'). +BracketMatches :: (ms: *MatchState, c: u8, p_in: s64, ec: s64) -> bool { + pat := ms.pat + p := p_in + 1 + negate := false + if pat[p] == #char "^" { + negate = true + p += 1 + } + while p < ec { + if pat[p] == #char "%" && p + 1 < ec { + p += 1 + if ClassMatches(c, pat[p]) { return !negate } + p += 1 + } else if p + 2 < ec && pat[p + 1] == #char "-" { + if pat[p] <= c && c <= pat[p + 2] { return !negate } + p += 3 + } else { + if pat[p] == c { return !negate } + p += 1 + } + } + return negate +} + +SingleMatch :: (ms: *MatchState, s: s64, p: s64, ep: s64) -> bool { + if s >= ms.src.count { return false } + c := ms.src[s] + pc := ms.pat[p] + if pc == #char "." { return true } + if pc == #char "%" { return ClassMatches(c, ms.pat[p + 1]) } + if pc == #char "[" { return BracketMatches(ms, c, p, ep - 1) } + return pc == c +} + +MatchBalance :: (ms: *MatchState, s: s64, p: s64) -> s64 { + if p + 1 >= ms.pat.count { return MatchFail(ms, "unbalanced pattern") } + if s >= ms.src.count || ms.src[s] != ms.pat[p] { return -1 } + open := ms.pat[p] + close := ms.pat[p + 1] + depth: s64 = 1 + at := s + 1 + while at < ms.src.count { + c := ms.src[at] + if c == close { + depth -= 1 + if depth == 0 { return at + 1 } + } else if c == open { + depth += 1 + } + at += 1 + } + return -1 +} + +MaxExpand :: (ms: *MatchState, s: s64, p: s64, ep: s64) -> s64 { + i: s64 = 0 + while SingleMatch(ms, s + i, p, ep) { i += 1 } + while i >= 0 { + result := DoMatch(ms, s + i, ep + 1) + if result >= 0 { return result } + if ms.failed { return -1 } + i -= 1 + } + return -1 +} + +MinExpand :: (ms: *MatchState, s: s64, p: s64, ep: s64) -> s64 { + at := s + while true { + result := DoMatch(ms, at, ep + 1) + if result >= 0 { return result } + if ms.failed { return -1 } + if SingleMatch(ms, at, p, ep) { at += 1 } else { return -1 } + } + return -1 +} + +StartCapture :: (ms: *MatchState, s: s64, p: s64, what: s64) -> s64 { + if ms.level >= MAX_CAPTURES { return MatchFail(ms, "too many captures") } + ms.capture_start[ms.level] = s + ms.capture_len[ms.level] = what + ms.level += 1 + result := DoMatch(ms, s, p) + if result < 0 { ms.level -= 1 } + return result +} + +EndCapture :: (ms: *MatchState, s: s64, p: s64) -> s64 { + l: s32 = -1 + level := ms.level - 1 + while level >= 0 { + if ms.capture_len[level] == CAP_UNFINISHED { l = level; break } + level -= 1 + } + if l < 0 { return MatchFail(ms, "invalid pattern capture") } + ms.capture_len[l] = s - ms.capture_start[l] + result := DoMatch(ms, s, p) + if result < 0 { ms.capture_len[l] = CAP_UNFINISHED } + return result +} + +MatchCapture :: (ms: *MatchState, s: s64, digit: u8) -> s64 { + l := cast(s32)(digit - #char "1") + if l < 0 || l >= ms.level || ms.capture_len[l] == CAP_UNFINISHED { return MatchFail(ms, "invalid capture index") } + length := ms.capture_len[l] + if ms.src.count - s >= length { + start := ms.capture_start[l] + i: s64 = 0 + while i < length { + if ms.src[start + i] != ms.src[s + i] { return -1 } + i += 1 + } + return s + length + } + return -1 +} + +// Match pattern from p against the subject from s; the end of the match or -1. +DoMatch :: (ms: *MatchState, s_in: s64, p_in: s64) -> s64 { + ms.depth += 1 + if ms.depth > MAX_MATCH_DEPTH { + ms.depth -= 1 + return MatchFail(ms, "pattern too complex") + } + s := s_in + p := p_in + result: s64 = -1 + while true { + if p >= ms.pat.count { result = s; break } + pc := ms.pat[p] + if pc == #char "(" { + if p + 1 < ms.pat.count && ms.pat[p + 1] == #char ")" { + result = StartCapture(ms, s, p + 2, CAP_POSITION) + } else { + result = StartCapture(ms, s, p + 1, CAP_UNFINISHED) + } + break + } + if pc == #char ")" { + result = EndCapture(ms, s, p + 1) + break + } + if pc == #char "$" && p + 1 == ms.pat.count { + result = ifx s == ms.src.count then s else -1 + break + } + if pc == #char "%" && p + 1 < ms.pat.count { + next := ms.pat[p + 1] + if next == #char "b" { + s = MatchBalance(ms, s, p + 2) + if s >= 0 { + p += 4 + continue + } + result = -1 + break + } + if next == #char "f" { + p += 2 + if p >= ms.pat.count || ms.pat[p] != #char "[" { + result = MatchFail(ms, "missing '[' after '%f' in pattern") + break + } + ep := ClassEnd(ms, p) + if ms.failed { result = -1; break } + previous: u8 = ifx s == 0 then 0 else ms.src[s - 1] + current: u8 = ifx s < ms.src.count then ms.src[s] else 0 + if !BracketMatches(ms, previous, p, ep - 1) && BracketMatches(ms, current, p, ep - 1) { + p = ep + continue + } + result = -1 + break + } + if IsDigit(next) { + s = MatchCapture(ms, s, next) + if s >= 0 { + p += 2 + continue + } + result = -1 + break + } + } + // Default: a single-character class with an optional suffix. + ep := ClassEnd(ms, p) + if ms.failed { result = -1; break } + matched := SingleMatch(ms, s, p, ep) + suffix: u8 = ifx ep < ms.pat.count then ms.pat[ep] else 0 + if suffix == #char "?" { + if matched { + r := DoMatch(ms, s + 1, ep + 1) + if r >= 0 { result = r; break } + if ms.failed { result = -1; break } + } + p = ep + 1 + continue + } + if suffix == #char "*" { + result = MaxExpand(ms, s, p, ep) + break + } + if suffix == #char "+" { + result = ifx matched then MaxExpand(ms, s + 1, p, ep) else -1 + break + } + if suffix == #char "-" { + result = MinExpand(ms, s, p, ep) + break + } + if !matched { result = -1; break } + s += 1 + p = ep + } + ms.depth -= 1 + return result +} + +CaptureValue :: (ms: *MatchState, i: s32, s: s64, e: s64) -> LuaValue { + L := ms.L + if i >= ms.level { + if i == 0 { return StringValue(Intern(L, ms.src[s:e])) } + MatchFail(ms, "invalid capture index") + return NilValue() + } + length := ms.capture_len[i] + start := ms.capture_start[i] + if length == CAP_UNFINISHED { + MatchFail(ms, "unfinished capture") + return NilValue() + } + if length == CAP_POSITION { return NumberValue(cast(float64)(start + 1)) } + return StringValue(Intern(L, ms.src[start:start + length])) +} + +// Push the captures (or the whole match when there are none). +PushCaptures :: (ms: *MatchState, s: s64, e: s64, whole: bool) -> s32 { + n := ms.level + if n == 0 && whole { n = 1 } + i: s32 = 0 + while i < n { + v := CaptureValue(ms, i, s, e) + if ms.failed { return -1 } + Push(ms.L, v) + i += 1 + } + return n +} + +HasSpecials :: (pattern: string) -> bool { + i: s64 = 0 + while i < pattern.count { + c := pattern[i] + if c == #char "^" || c == #char "$" || c == #char "*" || c == #char "+" || c == #char "?" || c == #char "." || c == #char "(" || c == #char ")" || c == #char "[" || c == #char "]" || c == #char "%" || c == #char "-" { return true } + i += 1 + } + return false +} + +PlainFind :: (subject: string, needle: string, from: s64) -> s64 { + if needle.count == 0 { return from } + last := subject.count - needle.count + i := from + first := needle[0] + while i <= last { + if subject[i] == first { + j: s64 = 1 + while j < needle.count && subject[i + j] == needle[j] { j += 1 } + if j == needle.count { return i } + } + i += 1 + } + return -1 +} + +InitMatch :: (ms: *MatchState, L: *LuaState, src: string, pat: string) { + ms.L = L + ms.src = src + ms.pat = pat + ms.level = 0 + ms.depth = 0 + ms.failed = false +} + +FindAux :: (L: *LuaState, find: bool) -> s32 { + s, ok1 := LuaCheckString(L, 1) + if !ok1 { return LUA_NATIVE_ERROR } + p, ok2 := LuaCheckString(L, 2) + if !ok2 { return LUA_NATIVE_ERROR } + init, ok3 := LuaOptInteger(L, 3, 1) + if !ok3 { return LUA_NATIVE_ERROR } + init = StringPosition(init, s.count) - 1 + if init < 0 { init = 0 } + if init > s.count { return ReturnNil(L) } + if find && (Truthy(Arg(L, 4)) || !HasSpecials(p)) { + position := PlainFind(s, p, init) + if position < 0 { return ReturnNil(L) } + Push(L, NumberValue(cast(float64)(position + 1))) + Push(L, NumberValue(cast(float64)(position + p.count))) + return 2 + } + ms: MatchState + pattern := p + anchor := pattern.count > 0 && pattern[0] == #char "^" + if anchor { pattern = pattern[1:] } + InitMatch(*ms, L, s, pattern) + at := init + while true { + ms.level = 0 + ms.depth = 0 + e := DoMatch(*ms, at, 0) + if ms.failed { return LUA_NATIVE_ERROR } + if e >= 0 { + if find { + Push(L, NumberValue(cast(float64)(at + 1))) + Push(L, NumberValue(cast(float64) e)) + n := PushCaptures(*ms, -1, -1, false) + if n < 0 { return LUA_NATIVE_ERROR } + return n + 2 + } + n := PushCaptures(*ms, at, e, true) + if n < 0 { return LUA_NATIVE_ERROR } + return n + } + at += 1 + if anchor || at > s.count { break } + } + return ReturnNil(L) +} + +StrFind :: (L: *LuaState) -> s32 { return FindAux(L, true) } +StrMatch :: (L: *LuaState) -> s32 { return FindAux(L, false) } + +// gmatch iterator: upvalues subject, pattern, next position. +GmatchStep :: (L: *LuaState) -> s32 { + sv := IndexValue(L, LuaUpvalueIndex(1)) + pv := IndexValue(L, LuaUpvalueIndex(2)) + position := SafeInteger(IndexValue(L, LuaUpvalueIndex(3)).n) + s := StrView(L, sv.h) + p := StrView(L, pv.h) + ms: MatchState + InitMatch(*ms, L, s, p) + at := position + while at <= s.count { + ms.level = 0 + ms.depth = 0 + e := DoMatch(*ms, at, 0) + if ms.failed { return LUA_NATIVE_ERROR } + if e >= 0 { + next := e + if e == at { next = e + 1 } + SetIndexValue(L, LuaUpvalueIndex(3), NumberValue(cast(float64) next)) + n := PushCaptures(*ms, at, e, true) + if n < 0 { return LUA_NATIVE_ERROR } + return n + } + at += 1 + } + return 0 +} + +StrGmatch :: (L: *LuaState) -> s32 { + s, ok1 := LuaCheckString(L, 1) + if !ok1 { return LUA_NATIVE_ERROR } + p, ok2 := LuaCheckString(L, 2) + if !ok2 { return LUA_NATIVE_ERROR } + Push(L, Arg(L, 1)) + Push(L, Arg(L, 2)) + Push(L, NumberValue(0.0)) + LuaPushNativeClosure(L, GmatchStep, 3, "gmatch_iterator") + return 1 +} + +// Append the replacement for one match to out. +AddReplacement :: (ms: *MatchState, out: *Vec(u8), s: s64, e: s64, repl: LuaValue) -> bool { + L := ms.L + if repl.t == LUA_TSTRING || repl.t == LUA_TNUMBER { + h, ok := ToStringHandle(L, repl) + text := StrView(L, h) + i: s64 = 0 + while i < text.count { + c := text[i] + if c == #char "%" && i + 1 < text.count { + i += 1 + d := text[i] + if !IsDigit(d) { + VecPush(< s32 { + s, ok1 := LuaCheckString(L, 1) + if !ok1 { return LUA_NATIVE_ERROR } + p, ok2 := LuaCheckString(L, 2) + if !ok2 { return LUA_NATIVE_ERROR } + repl := Arg(L, 3) + if repl.t != LUA_TNUMBER && repl.t != LUA_TSTRING && repl.t != LUA_TTABLE && repl.t != LUA_TFUNCTION { + return LuaArgError(L, 3, "string/function/table expected") + } + max_n, ok3 := LuaOptInteger(L, 4, s.count + 1) + if !ok3 { return LUA_NATIVE_ERROR } + // Keep the subject and pattern alive across replacement callbacks. + subject_h := Arg(L, 1).h + pattern := p + anchor := pattern.count > 0 && pattern[0] == #char "^" + if anchor { pattern = pattern[1:] } + ms: MatchState + InitMatch(*ms, L, s, pattern) + out: Vec(u8) + at: s64 = 0 + n: s64 = 0 + while n < max_n { + ms.level = 0 + ms.depth = 0 + e := DoMatch(*ms, at, 0) + if ms.failed { VecFree(out); return LUA_NATIVE_ERROR } + if e >= 0 { + n += 1 + if !AddReplacement(*ms, *out, at, e, repl) { VecFree(out); return LUA_NATIVE_ERROR } + } + if e >= 0 && e > at { + at = e + } else if at < s.count { + VecPush(out, s[at]) + at += 1 + } else { + break + } + if anchor { break } + } + if at < s.count { BuilderAppend(out, s[at:]) } + Push(L, StringValue(InternBytes(L, *out))) + Push(L, NumberValue(cast(float64) n)) + VecFree(out) + subject_h = subject_h + return 2 +} + +StrLength :: (L: *LuaState) -> s32 { + s, ok := LuaCheckString(L, 1) + if !ok { return LUA_NATIVE_ERROR } + return ReturnValue(L, NumberValue(cast(float64) s.count)) +} + +StrSub :: (L: *LuaState) -> s32 { + s, ok := LuaCheckString(L, 1) + if !ok { return LUA_NATIVE_ERROR } + i, ok2 := LuaOptInteger(L, 2, 1) + j, ok3 := LuaOptInteger(L, 3, -1) + if !ok2 || !ok3 { return LUA_NATIVE_ERROR } + l := s.count + start := StringPosition(i, l) + end := StringPosition(j, l) + if start < 1 { start = 1 } + if end > l { end = l } + if start > end { return ReturnValue(L, StringValue(Intern(L, ""))) } + if start == 1 && end == l { return ReturnValue(L, Arg(L, 1)) } + return ReturnValue(L, StringValue(Intern(L, s[start - 1:end]))) +} + +StrUpper :: (L: *LuaState) -> s32 { + s, ok := LuaCheckString(L, 1) + if !ok { return LUA_NATIVE_ERROR } + out: Vec(u8) + i: s64 = 0 + while i < s.count { + c := s[i] + VecPush(out, ifx IsLowerByte(c) then c - 32 else c) + i += 1 + } + Push(L, StringValue(InternBytes(L, *out))) + VecFree(out) + return 1 +} + +StrLower :: (L: *LuaState) -> s32 { + s, ok := LuaCheckString(L, 1) + if !ok { return LUA_NATIVE_ERROR } + out: Vec(u8) + i: s64 = 0 + while i < s.count { + c := s[i] + VecPush(out, ifx IsUpperByte(c) then c + 32 else c) + i += 1 + } + Push(L, StringValue(InternBytes(L, *out))) + VecFree(out) + return 1 +} + +StrRep :: (L: *LuaState) -> s32 { + s, ok := LuaCheckString(L, 1) + if !ok { return LUA_NATIVE_ERROR } + n, ok2 := LuaCheckInteger(L, 2) + if !ok2 { return LUA_NATIVE_ERROR } + sep, ok3 := LuaOptString(L, 3, "") + if !ok3 { return LUA_NATIVE_ERROR } + if n <= 0 { return ReturnValue(L, StringValue(Intern(L, ""))) } + total := (s.count + sep.count) * n + if total > 268435456 { return LuaErrorText(L, "resulting string too large") } + out: Vec(u8) + VecReserve(out, total) + i: s64 = 0 + while i < n { + if i > 0 { BuilderAppend(out, sep) } + BuilderAppend(out, s) + i += 1 + } + Push(L, StringValue(InternBytes(L, *out))) + VecFree(out) + return 1 +} + +StrReverse :: (L: *LuaState) -> s32 { + s, ok := LuaCheckString(L, 1) + if !ok { return LUA_NATIVE_ERROR } + out: Vec(u8) + i := s.count - 1 + while i >= 0 { VecPush(out, s[i]); i -= 1 } + Push(L, StringValue(InternBytes(L, *out))) + VecFree(out) + return 1 +} + +StrByte :: (L: *LuaState) -> s32 { + s, ok := LuaCheckString(L, 1) + if !ok { return LUA_NATIVE_ERROR } + i, ok2 := LuaOptInteger(L, 2, 1) + if !ok2 { return LUA_NATIVE_ERROR } + j, ok3 := LuaOptInteger(L, 3, i) + if !ok3 { return LUA_NATIVE_ERROR } + l := s.count + start := StringPosition(i, l) + end := StringPosition(j, l) + if start < 1 { start = 1 } + if end > l { end = l } + if start > end { return 0 } + n := end - start + 1 + if !EnsureStack(L, Top(L) + n + 1) { return LuaErrorText(L, "string slice too long") } + k := start + while k <= end { + Push(L, NumberValue(cast(float64) s[k - 1])) + k += 1 + } + return cast(s32) n +} + +StrChar :: (L: *LuaState) -> s32 { + n := ArgCount(L) + out: Vec(u8) + i: s32 = 1 + while i <= n { + c, ok := LuaCheckInteger(L, i) + if !ok { VecFree(out); return LUA_NATIVE_ERROR } + if c < 0 || c > 255 { VecFree(out); return LuaArgError(L, i, "invalid value") } + VecPush(out, cast(u8) c) + i += 1 + } + Push(L, StringValue(InternBytes(L, *out))) + VecFree(out) + return 1 +} + +StrDump :: (L: *LuaState) -> s32 { + return LuaErrorText(L, "unable to dump given function") +} + +AppendQuoted :: (out: *Vec(u8), s: string) { + VecPush(< 0 { + buffer[n] = digits[cast(s64)(v % base)] + v /= base + n += 1 + } + while n > 0 { + n -= 1 + VecPush(< s64 #inline { return SafeInteger(n) } + +// C99 %a: 0x1.hhhp+e, with the shortest exact digits unless a precision is given. +AppendHexFloat :: (out: *Vec(u8), x: float64, upper: bool, precision: s64, alt: bool, plus: bool, space: bool) { + bits: NumberBits + bits.f = x + negative := (bits.u >> 63) != 0 + if x != x { + BuilderAppend(<> 52) & 2047) + mantissa := bits.u & 0xFFFFFFFFFFFFF + lead: u64 = 1 + e := exponent_bits - 1023 + if exponent_bits == 0 { + lead = 0 + e = ifx mantissa == 0 then 0 else -1022 + } + nibbles: s64 = 13 + if precision >= 0 && precision < 13 { + drop := cast(u64)((13 - precision) * 4) + remainder := mantissa & ((cast(u64) 1 << drop) - 1) + half := cast(u64) 1 << (drop - 1) + mantissa >>= drop + if remainder > half || (remainder == half && (mantissa & 1) == 1) { mantissa += 1 } + if precision == 0 { + lead += mantissa + mantissa = 0 + } else if (mantissa >> cast(u64)(precision * 4)) != 0 { + lead += 1 + mantissa &= (cast(u64) 1 << cast(u64)(precision * 4)) - 1 + } + nibbles = precision + } else if precision < 0 { + while nibbles > 0 && (mantissa & 15) == 0 { + mantissa >>= 4 + nibbles -= 1 + } + } + digits := ifx upper then "0123456789ABCDEF" else "0123456789abcdef" + BuilderAppend(< 0 || alt { VecPush(<= 0 { + VecPush(<> cast(u64)(i * 4)) & 15)]) + i -= 1 + } + k := nibbles + while k < precision { VecPush(< s32 { + format, ok := LuaCheckString(L, 1) + if !ok { return LUA_NATIVE_ERROR } + out: Vec(u8) + body: Vec(u8) + arg: s32 = 1 + i: s64 = 0 + while i < format.count { + c := format[i] + if c != #char "%" { + VecPush(out, c) + i += 1 + continue + } + i += 1 + if i < format.count && format[i] == #char "%" { + VecPush(out, #char "%") + i += 1 + continue + } + left := false + plus := false + space := false + alt := false + zero := false + while i < format.count { + f := format[i] + if f == #char "-" { left = true } + else if f == #char "+" { plus = true } + else if f == #char " " { space = true } + else if f == #char "#" { alt = true } + else if f == #char "0" { zero = true } + else { break } + i += 1 + } + width: s64 = 0 + digits: s32 = 0 + while i < format.count && IsDigit(format[i]) { + width = width * 10 + cast(s64)(format[i] - #char "0") + i += 1 + digits += 1 + } + precision: s64 = -1 + if i < format.count && format[i] == #char "." { + i += 1 + precision = 0 + while i < format.count && IsDigit(format[i]) { + precision = precision * 10 + cast(s64)(format[i] - #char "0") + i += 1 + digits += 1 + } + } + if digits > 4 || i >= format.count { + VecFree(out) + VecFree(body) + return LuaErrorText(L, "invalid format (repeated flags)") + } + conv := format[i] + i += 1 + arg += 1 + VecClear(body) + prefix: s64 = 0 + if conv == #char "d" || conv == #char "i" { + n, okn := LuaCheckNumber(L, arg) + if !okn { VecFree(out); VecFree(body); return LUA_NATIVE_ERROR } + v := NumberToS64(n) + if v < 0 { VecPush(body, #char "-"); prefix = 1 } + else if plus { VecPush(body, #char "+"); prefix = 1 } + else if space { VecPush(body, #char " "); prefix = 1 } + magnitude: u64 = ifx v < 0 then cast(u64)(-(v + 1)) + 1 else cast(u64) v + digits_text: Vec(u8) + AppendUnsigned(*digits_text, magnitude, 10, false) + if precision >= 0 { + k := digits_text.count + while k < precision { VecPush(body, #char "0"); k += 1 } + if precision == 0 && magnitude == 0 { VecClear(digits_text) } + } + BuilderAppend(body, BytesView(*digits_text)) + VecFree(digits_text) + AppendPadded(*out, *body, width, left, zero && precision < 0, prefix) + } else if conv == #char "u" || conv == #char "o" || conv == #char "x" || conv == #char "X" { + n, okn := LuaCheckNumber(L, arg) + if !okn { VecFree(out); VecFree(body); return LUA_NATIVE_ERROR } + v := cast(u64) NumberToS64(n) + base: u64 = 10 + if conv == #char "o" { base = 8 } + if conv == #char "x" || conv == #char "X" { base = 16 } + if alt && base == 16 && v != 0 { + BuilderAppend(body, ifx conv == #char "x" then "0x" else "0X") + prefix = 2 + } + if alt && base == 8 { VecPush(body, #char "0") } + digits_text: Vec(u8) + AppendUnsigned(*digits_text, v, base, conv == #char "X") + if precision >= 0 { + k := digits_text.count + while k < precision { VecPush(body, #char "0"); k += 1 } + } + BuilderAppend(body, BytesView(*digits_text)) + VecFree(digits_text) + AppendPadded(*out, *body, width, left, zero && precision < 0, prefix) + } else if conv == #char "c" { + n, okn := LuaCheckNumber(L, arg) + if !okn { VecFree(out); VecFree(body); return LUA_NATIVE_ERROR } + VecPush(body, cast(u8)(NumberToS64(n) & 255)) + AppendPadded(*out, *body, width, left, false, 0) + } else if conv == #char "e" || conv == #char "E" || conv == #char "f" || conv == #char "F" || conv == #char "g" || conv == #char "G" { + n, okn := LuaCheckNumber(L, arg) + if !okn { VecFree(out); VecFree(body); return LUA_NATIVE_ERROR } + FormatFloat(*body, n, conv, cast(s32)(ifx precision < 0 then 6 else precision), alt, plus, space) + if body.count > 0 && (body[0] == #char "-" || body[0] == #char "+" || body[0] == #char " ") { prefix = 1 } + finite := n == n && n - n == 0.0 + AppendPadded(*out, *body, width, left, zero && finite, prefix) + } else if conv == #char "a" || conv == #char "A" { + n, okn := LuaCheckNumber(L, arg) + if !okn { VecFree(out); VecFree(body); return LUA_NATIVE_ERROR } + AppendHexFloat(*body, n, conv == #char "A", precision, alt, plus, space) + if body.count > 0 && (body[0] == #char "-" || body[0] == #char "+" || body[0] == #char " ") { prefix = 1 } + AppendPadded(*out, *body, width, left, false, prefix) + } else if conv == #char "q" { + s, oks := LuaCheckString(L, arg) + if !oks { VecFree(out); VecFree(body); return LUA_NATIVE_ERROR } + AppendQuoted(*out, s) + } else if conv == #char "s" { + if arg > ArgCount(L) { + VecFree(out) + VecFree(body) + return LuaArgError(L, arg, "no value") + } + text: LuaValue + if !ToStringMeta(L, Arg(L, arg), *text) { VecFree(out); VecFree(body); return LUA_NATIVE_ERROR } + if text.t == LUA_TSTRING { + view := StrView(L, text.h) + if precision >= 0 && precision < view.count { view = view[0:precision] } + BuilderAppend(body, view) + } else { + AppendValueText(L, *body, text) + } + AppendPadded(*out, *body, width, left, false, 0) + } else { + message: Vec(u8) + BuilderAppend(message, "invalid option '%") + VecPush(message, conv) + BuilderAppend(message, "' to 'format'") + VecFree(out) + VecFree(body) + result := LuaErrorText(L, BytesView(*message)) + VecFree(message) + return result + } + } + Push(L, StringValue(InternBytes(L, *out))) + VecFree(out) + VecFree(body) + return 1 +} + +OpenString :: (L: *LuaState) { + t := NewTable(L, 0, 16) + RegisterLibrary(L, "string", t) + SetNative(L, t, "len", StrLength) + SetNative(L, t, "sub", StrSub) + SetNative(L, t, "upper", StrUpper) + SetNative(L, t, "lower", StrLower) + SetNative(L, t, "rep", StrRep) + SetNative(L, t, "reverse", StrReverse) + SetNative(L, t, "byte", StrByte) + SetNative(L, t, "char", StrChar) + SetNative(L, t, "format", StrFormat) + SetNative(L, t, "find", StrFind) + SetNative(L, t, "match", StrMatch) + SetNative(L, t, "gmatch", StrGmatch) + SetNative(L, t, "gfind", StrGmatch) + SetNative(L, t, "gsub", StrGsub) + SetNative(L, t, "dump", StrDump) + meta := NewTable(L, 0, 1) + SetStr(L, meta, L.tm_names[TM_INDEX], TableValue(t)) + L.type_meta[LUA_TSTRING] = meta +} diff --git a/src/lib_table.zi b/src/lib_table.zi new file mode 100644 index 0000000..7eb9eef --- /dev/null +++ b/src/lib_table.zi @@ -0,0 +1,288 @@ +// Table library of Lua 5.1: raw access by position like ltablib.c. + +#scope_module + +TableArg :: (L: *LuaState, n: s32) -> s32 { + v := Arg(L, n) + if v.t != LUA_TTABLE { LuaTypeError(L, n, "table"); return -1 } + return v.h +} + +TabInsert :: (L: *LuaState) -> s32 { + t := TableArg(L, 1) + if t < 0 { return LUA_NATIVE_ERROR } + e := TableLength(L, t) + 1 + n := ArgCount(L) + if n == 2 { + SetInt(L, t, e, Arg(L, 2)) + return 0 + } + if n != 3 { return LuaErrorText(L, "wrong number of arguments to 'insert'") } + position, ok := LuaCheckInteger(L, 2) + if !ok { return LUA_NATIVE_ERROR } + if position > e { e = position } + i := e + while i > position { + SetInt(L, t, i, GetInt(L, t, i - 1)) + i -= 1 + } + SetInt(L, t, position, Arg(L, 3)) + return 0 +} + +TabRemove :: (L: *LuaState) -> s32 { + t := TableArg(L, 1) + if t < 0 { return LUA_NATIVE_ERROR } + e := TableLength(L, t) + position, ok := LuaOptInteger(L, 2, e) + if !ok { return LUA_NATIVE_ERROR } + if e == 0 { return 0 } + result := GetInt(L, t, position) + i := position + while i < e { + SetInt(L, t, i, GetInt(L, t, i + 1)) + i += 1 + } + SetInt(L, t, e, NilValue()) + return ReturnValue(L, result) +} + +TabConcat :: (L: *LuaState) -> s32 { + t := TableArg(L, 1) + if t < 0 { return LUA_NATIVE_ERROR } + sep, ok1 := LuaOptString(L, 2, "") + if !ok1 { return LUA_NATIVE_ERROR } + first, ok2 := LuaOptInteger(L, 3, 1) + if !ok2 { return LUA_NATIVE_ERROR } + last: s64 = 0 + if Arg(L, 4).t == LUA_TNIL { + last = TableLength(L, t) + } else { + value, ok3 := LuaCheckInteger(L, 4) + if !ok3 { return LUA_NATIVE_ERROR } + last = value + } + out: Vec(u8) + i := first + while i <= last { + v := GetInt(L, t, i) + if v.t == LUA_TSTRING { + BuilderAppend(out, StrView(L, v.h)) + } else if v.t == LUA_TNUMBER { + AppendNumber(*out, v.n) + } else { + VecFree(out) + message: Vec(u8) + BuilderAppend(message, "invalid value (at index ") + Append(*message, i) + BuilderAppend(message, ") in table for 'concat'") + result := LuaErrorText(L, BytesView(*message)) + VecFree(message) + return result + } + if i < last { BuilderAppend(out, sep) } + i += 1 + } + Push(L, StringValue(InternBytes(L, *out))) + VecFree(out) + return 1 +} + +TabMaxn :: (L: *LuaState) -> s32 { + t := TableArg(L, 1) + if t < 0 { return LUA_NATIVE_ERROR } + best := 0.0 + key := NilValue() + while true { + k: LuaValue + v: LuaValue + found, ok := TableNext(L, t, key, *k, *v) + if !ok || !found { break } + if k.t == LUA_TNUMBER && k.n > best { best = k.n } + key = k + } + return ReturnValue(L, NumberValue(best)) +} + +TabGetn :: (L: *LuaState) -> s32 { + t := TableArg(L, 1) + if t < 0 { return LUA_NATIVE_ERROR } + return ReturnValue(L, NumberValue(cast(float64) TableLength(L, t))) +} + +TabSetn :: (L: *LuaState) -> s32 { + return LuaErrorText(L, "'setn' is obsolete") +} + +// Call f(k, v) for each pair until it returns non-nil. +TabForeach :: (L: *LuaState) -> s32 { + t := TableArg(L, 1) + if t < 0 { return LUA_NATIVE_ERROR } + f := Arg(L, 2) + if f.t != LUA_TFUNCTION { return LuaTypeError(L, 2, "function") } + th := L.cur + key := NilValue() + while true { + k: LuaValue + v: LuaValue + found, ok := TableNext(L, t, key, *k, *v) + if !ok { return LuaErrorText(L, "invalid key to 'next'") } + if !found { break } + func := L.threads[th].top + Push(L, f) + Push(L, k) + Push(L, v) + if !CallValue(L, func, 2, 1) { return LUA_NATIVE_ERROR } + result := L.threads[th].stack[func] + L.threads[th].top = func + if result.t != LUA_TNIL { return ReturnValue(L, result) } + key = k + } + return 0 +} + +TabForeachi :: (L: *LuaState) -> s32 { + t := TableArg(L, 1) + if t < 0 { return LUA_NATIVE_ERROR } + f := Arg(L, 2) + if f.t != LUA_TFUNCTION { return LuaTypeError(L, 2, "function") } + th := L.cur + n := TableLength(L, t) + i: s64 = 1 + while i <= n { + func := L.threads[th].top + Push(L, f) + Push(L, NumberValue(cast(float64) i)) + Push(L, GetInt(L, t, i)) + if !CallValue(L, func, 2, 1) { return LUA_NATIVE_ERROR } + result := L.threads[th].stack[func] + L.threads[th].top = func + if result.t != LUA_TNIL { return ReturnValue(L, result) } + i += 1 + } + return 0 +} + +SortState :: struct { + L: *LuaState + t: s32 + comp: LuaValue + failed: bool +} + +// a < b by the comparator or the < operator. +SortLess :: (ss: *SortState, a: LuaValue, b: LuaValue) -> bool { + L := ss.L + if ss.comp.t == LUA_TNIL { + less := false + if !LessThan(L, a, b, *less) { ss.failed = true; return false } + return less + } + th := L.cur + func := L.threads[th].top + Push(L, ss.comp) + Push(L, a) + Push(L, b) + if !CallValue(L, func, 2, 1) { ss.failed = true; return false } + result := L.threads[th].stack[func] + L.threads[th].top = func + return Truthy(result) +} + +SortSwap :: (ss: *SortState, i: s64, j: s64) { + a := GetInt(ss.L, ss.t, i) + b := GetInt(ss.L, ss.t, j) + SetInt(ss.L, ss.t, i, b) + SetInt(ss.L, ss.t, j, a) +} + +SortFail :: (ss: *SortState) -> bool { + if !ss.failed { + ss.failed = true + LuaErrorText(ss.L, "invalid order function for sorting") + } + return false +} + +// The quicksort of ltablib.c: median of three, recursion on the smaller half. +AuxSort :: (ss: *SortState, lo_in: s64, up_in: s64) -> bool { + L := ss.L + t := ss.t + lo := lo_in + up := up_in + while lo < up { + // Sort elements lo, (lo+up)/2 and up. + if SortLess(ss, GetInt(L, t, up), GetInt(L, t, lo)) { SortSwap(ss, lo, up) } + if ss.failed { return false } + if up - lo == 1 { break } + i := (lo + up) / 2 + if SortLess(ss, GetInt(L, t, i), GetInt(L, t, lo)) { + SortSwap(ss, i, lo) + } else { + if ss.failed { return false } + if SortLess(ss, GetInt(L, t, up), GetInt(L, t, i)) { SortSwap(ss, i, up) } + } + if ss.failed { return false } + if up - lo == 2 { break } + pivot := GetInt(L, t, i) + SortSwap(ss, i, up - 1) + // Invariant: a[lo] <= P == a[up-1] <= a[up]. + i = lo + j := up - 1 + while true { + i += 1 + while SortLess(ss, GetInt(L, t, i), pivot) { + if i > up { return SortFail(ss) } + i += 1 + } + if ss.failed { return false } + j -= 1 + while SortLess(ss, pivot, GetInt(L, t, j)) { + if j < lo { return SortFail(ss) } + j -= 1 + } + if ss.failed { return false } + if j < i { break } + SortSwap(ss, i, j) + } + SortSwap(ss, up - 1, i) + // a[lo..i-1] <= a[i] == P <= a[i+1..up]; recurse into the smaller part. + if i - lo < up - i { + if !AuxSort(ss, lo, i - 1) { return false } + lo = i + 1 + } else { + if !AuxSort(ss, i + 1, up) { return false } + up = i - 1 + } + } + return true +} + +TabSort :: (L: *LuaState) -> s32 { + t := TableArg(L, 1) + if t < 0 { return LUA_NATIVE_ERROR } + n := TableLength(L, t) + comp := Arg(L, 2) + if comp.t != LUA_TNIL && comp.t != LUA_TFUNCTION { return LuaTypeError(L, 2, "function") } + ss: SortState + ss.L = L + ss.t = t + ss.comp = comp + ss.failed = false + if !AuxSort(*ss, 1, n) { return LUA_NATIVE_ERROR } + return 0 +} + +OpenTable :: (L: *LuaState) { + t := NewTable(L, 0, 12) + RegisterLibrary(L, "table", t) + SetNative(L, t, "insert", TabInsert) + SetNative(L, t, "remove", TabRemove) + SetNative(L, t, "concat", TabConcat) + SetNative(L, t, "sort", TabSort) + SetNative(L, t, "maxn", TabMaxn) + SetNative(L, t, "getn", TabGetn) + SetNative(L, t, "setn", TabSetn) + SetNative(L, t, "foreach", TabForeach) + SetNative(L, t, "foreachi", TabForeachi) +} diff --git a/src/number.zi b/src/number.zi new file mode 100644 index 0000000..ca1a24c --- /dev/null +++ b/src/number.zi @@ -0,0 +1,460 @@ +// Number arithmetic helpers, Lua number parsing and exact printf-style +// decimal formatting (%.14g for tostring, %e/%f/%g for string.format). + +#scope_module + +TWO52 :: 4503599627370496.0; + +Floor :: (x: float64) -> float64 #inline { + if !(x > -TWO52 && x < TWO52) { return x } + i := cast(s64) x + f := cast(float64) i + if f > x { return f - 1.0 } + return f +} + +Ceil :: (x: float64) -> float64 #inline { + if !(x > -TWO52 && x < TWO52) { return x } + i := cast(s64) x + f := cast(float64) i + if f < x { return f + 1.0 } + return f +} + +Trunc :: (x: float64) -> float64 #inline { + if !(x > -TWO52 && x < TWO52) { return x } + return cast(float64) cast(s64) x +} + +// x truncated toward zero as an s64: NaN gives 0, out-of-range values clamp. +// Ziran's float casts trap on those, so all Lua number to integer +// conversions go through here. +SafeInteger :: (x: float64) -> s64 #inline { + if x >= -9223372036854775808.0 && x < 9223372036854775808.0 { return cast(s64) x } + if x != x { return 0 } + if x > 0.0 { return 9223372036854775807 } + return -9223372036854775807 - 1 +} + +LuaMod :: (a: float64, b: float64) -> float64 #inline { + return a - Floor(a / b) * b +} + +LuaPow :: (a: float64, b: float64) -> float64 { + if b == 2.0 { return a * a } + if b == 0.5 { return Sqrt(a) } + return Pow(a, b) +} + +Fmod :: (a: float64, b: float64) -> float64 { + if b == 0.0 || a != a || b != b { return NotANumber() } + if a == Infinity() || a == -Infinity() { return NotANumber() } + if b == Infinity() || b == -Infinity() { return a } + // Exact remainder: subtract b scaled by powers of two (each step exact). + r := ifx a < 0.0 then -a else a + m := ifx b < 0.0 then -b else b + if r < m { return a } + t := m + while t * 2.0 <= r { t *= 2.0 } + while t >= m { + if r >= t { r -= t } + t /= 2.0 + } + return ifx a < 0.0 then -r else r +} + +IsWhitespaceByte :: (c: u8) -> bool #inline { return c == 32 || (c >= 9 && c <= 13) } + +// Parse a Lua numeric literal or tonumber() text (surrounding whitespace +// allowed). Accepts decimal with optional fraction/exponent and 0x hex. +ParseNumberText :: (text: string) -> (value: float64, ok: bool) { + start: s64 = 0 + end := text.count + while start < end && IsWhitespaceByte(text[start]) { start += 1 } + while end > start && IsWhitespaceByte(text[end - 1]) { end -= 1 } + if start >= end { return 0.0, false } + negative := false + at := start + if text[at] == #char "-" { negative = true; at += 1 } + else if text[at] == #char "+" { at += 1 } + if at + 1 < end && text[at] == #char "0" && (text[at + 1] == #char "x" || text[at + 1] == #char "X") { + at += 2 + if at >= end { return 0.0, false } + value: float64 = 0.0 + any := false + while at < end && HexDigitValue(text[at]) >= 0 { + value = value * 16.0 + cast(float64) HexDigitValue(text[at]) + at += 1 + any = true + } + scale: s32 = 0 + if at < end && text[at] == #char "." { + at += 1 + while at < end && HexDigitValue(text[at]) >= 0 { + value = value * 16.0 + cast(float64) HexDigitValue(text[at]) + scale -= 4 + at += 1 + any = true + } + } + if !any { return 0.0, false } + if at < end && (text[at] == #char "p" || text[at] == #char "P") { + at += 1 + exp_negative := false + if at < end && (text[at] == #char "+" || text[at] == #char "-") { exp_negative = text[at] == #char "-"; at += 1 } + if at >= end { return 0.0, false } + e: s32 = 0 + while at < end && IsDigit(text[at]) { + if e < 100000 { e = e * 10 + cast(s32)(text[at] - #char "0") } + at += 1 + } + scale += ifx exp_negative then -e else e + } + if at != end { return 0.0, false } + if scale != 0 { value = ScaleByPowerOfTwo(value, scale) } + return ifx negative then -value else value, true + } + // Decimal: digits [. digits] [e [sign] digits], at least one digit. + builder: Vec(u8) + if negative { VecPush(builder, #char "-") } + int_digits: s64 = 0 + while at < end && IsDigit(text[at]) { VecPush(builder, text[at]); at += 1; int_digits += 1 } + if int_digits == 0 { VecPush(builder, #char "0") } + frac_digits: s64 = 0 + if at < end && text[at] == #char "." { + at += 1 + VecPush(builder, #char ".") + while at < end && IsDigit(text[at]) { VecPush(builder, text[at]); at += 1; frac_digits += 1 } + if frac_digits == 0 { VecPush(builder, #char "0") } + } + if int_digits == 0 && frac_digits == 0 { VecFree(builder); return 0.0, false } + if at < end && (text[at] == #char "e" || text[at] == #char "E") { + at += 1 + VecPush(builder, #char "e") + if at < end && (text[at] == #char "+" || text[at] == #char "-") { VecPush(builder, text[at]); at += 1 } + exp_digits: s64 = 0 + while at < end && IsDigit(text[at]) { VecPush(builder, text[at]); at += 1; exp_digits += 1 } + if exp_digits == 0 { VecFree(builder); return 0.0, false } + } + if at != end { VecFree(builder); return 0.0, false } + value, ok := ParseFloat64(BytesView(*builder)) + VecFree(builder) + return value, ok +} + +// ---------------------------------------------------------------- bignum + +BIG_WORDS :: 90; + +Big :: struct { + words: [90]u32 + count: s32 +} + +BigSet :: (a: *Big, value: u64) { + a.count = 0 + v := value + while v != 0 { + a.words[a.count] = cast(u32)(v & 0xFFFFFFFF) + a.count += 1 + v >>= 32 + } +} + +BigMulSmall :: (a: *Big, factor: u32) { + carry: u64 = 0 + i: s32 = 0 + while i < a.count { + product := cast(u64) a.words[i] * cast(u64) factor + carry + a.words[i] = cast(u32)(product & 0xFFFFFFFF) + carry = product >> 32 + i += 1 + } + if carry != 0 && a.count < BIG_WORDS { + a.words[a.count] = cast(u32) carry + a.count += 1 + } +} + +BigShiftLeft :: (a: *Big, bits: s32) { + if a.count == 0 { return } + words := bits / 32 + rest := bits % 32 + if rest != 0 { + carry: u32 = 0 + i: s32 = 0 + while i < a.count { + word := a.words[i] + a.words[i] = (word << cast(u32) rest) | carry + carry = word >> cast(u32)(32 - rest) + i += 1 + } + if carry != 0 { a.words[a.count] = carry; a.count += 1 } + } + if words > 0 { + i := a.count - 1 + while i >= 0 { a.words[i + words] = a.words[i]; i -= 1 } + i = 0 + while i < words { a.words[i] = 0; i += 1 } + a.count += words + } +} + +BigMulPow10 :: (a: *Big, power: s32) { + p := power + while p >= 9 { BigMulSmall(a, 1000000000); p -= 9 } + factor: u32 = 1 + while p > 0 { factor *= 10; p -= 1 } + if factor != 1 { BigMulSmall(a, factor) } +} + +BigCompare :: (a: *Big, b: *Big) -> s32 { + if a.count != b.count { return ifx a.count < b.count then -1 else 1 } + i := a.count - 1 + while i >= 0 { + if a.words[i] != b.words[i] { return ifx a.words[i] < b.words[i] then -1 else 1 } + i -= 1 + } + return 0 +} + +// a -= b, requires a >= b. +BigSub :: (a: *Big, b: *Big) { + borrow: s64 = 0 + i: s32 = 0 + while i < a.count { + word := cast(s64) a.words[i] - borrow + if i < b.count { word -= cast(s64) b.words[i] } + if word < 0 { word += 4294967296; borrow = 1 } else { borrow = 0 } + a.words[i] = cast(u32) word + i += 1 + } + while a.count > 0 && a.words[a.count - 1] == 0 { a.count -= 1 } +} + +// 2*a compared with b. +BigCompareDouble :: (a: *Big, b: *Big) -> s32 { + doubled := < s32 { + VecClear(<> 52) & 0x7FF) + mantissa := bits.u & 0xFFFFFFFFFFFFF + e: s32 + if exponent_bits == 0 { e = -1074 } else { mantissa |= cast(u64) 1 << 52; e = exponent_bits - 1075 } + N: Big + D: Big + BigSet(*N, mantissa) + BigSet(*D, 1) + if e >= 0 { BigShiftLeft(*N, e) } else { BigShiftLeft(*D, -e) } + // Estimate k = floor(log10 x). + k := cast(s32) Floor(Log10(x)) + if k >= 0 { BigMulPow10(*D, k) } else { BigMulPow10(*N, -k) } + // Normalize N/D into [1, 10). + if BigCompare(*N, *D) < 0 { + BigMulSmall(*N, 10) + k -= 1 + } else { + ten := D + BigMulSmall(*ten, 10) + if BigCompare(*N, *ten) >= 0 { + BigMulSmall(*D, 10) + k += 1 + } + } + wanted: s32 = count + if mode == 1 { wanted = k + 1 + count } + if wanted <= 0 { + // Everything rounds away below the last kept place. + if wanted == 0 { + // Value / 10^(k+1) in [0.1, 1): round to 1 unit when > 0.5. + five := D + BigMulSmall(*five, 5) + cmp := BigCompare(*N, *five) + if cmp > 0 { + VecPush(< 800 { wanted = 800 } + i: s32 = 0 + while i < wanted { + digit: u8 = 0 + while BigCompare(*N, *D) >= 0 { BigSub(*N, *D); digit += 1 } + VecPush(< 0 || (cmp == 0 && (((<= 0 { + if (< with precision (no width/flags +// except alt '#' and forced sign). +FormatFloat :: (out: *Vec(u8), x: float64, conv: u8, precision: s32, alt: bool, plus: bool, space: bool) { + upper := conv == #char "E" || conv == #char "G" || conv == #char "F" + if x != x { + BuilderAppend(< 0 || alt { VecPush(< 0 || alt { VecPush(< 0 || alt { VecPush(< 1 && digits[digits.count - 1] == #char "0" { VecResize(digits, digits.count - 1) } + } + if k < -4 || k >= p { + VecPush(< 1 || alt { VecPush(< 0 || alt { VecPush(<= digits.count { + VecPush(< -1e14 && x < 1e14 { + i := cast(s64) x + if cast(float64) i == x && !(i == 0 && IsNegativeZero(x)) { + Append(out, i) + return + } + } + FormatFloat(out, x, #char "g", 14, false, false, false) +} diff --git a/src/parser.zi b/src/parser.zi new file mode 100644 index 0000000..71e6340 --- /dev/null +++ b/src/parser.zi @@ -0,0 +1,740 @@ +// Lua 5.1 parser (plus LuaJIT goto/labels) producing a flat AST whose nodes +// refer to each other by index. Lists are chained through `next`. + +#scope_module + +E_NIL :: 1; +E_TRUE :: 2; +E_FALSE :: 3; +E_NUMBER :: 4; +E_STRING :: 5; +E_VARARG :: 6; +E_FUNCTION :: 7; +E_TABLE :: 8; +E_BINOP :: 9; +E_UNOP :: 10; +E_NAME :: 11; +E_INDEX :: 12; +E_CALL :: 13; +E_METHOD :: 14; +E_PAREN :: 15; +E_AND :: 16; +E_OR :: 17; +F_ITEM :: 18; +F_PAIR :: 19; +N_DECL :: 20; +S_LOCAL :: 30; +S_ASSIGN :: 31; +S_CALL :: 32; +S_DO :: 33; +S_WHILE :: 34; +S_REPEAT :: 35; +S_IF :: 36; +S_NUMFOR :: 37; +S_GENFOR :: 38; +S_FUNCTION :: 39; +S_LOCALFUNC :: 40; +S_RETURN :: 41; +S_BREAK :: 42; +S_GOTO :: 43; +S_LABEL :: 44; + +// Binary operators. +OPR_ADD :: 0; +OPR_SUB :: 1; +OPR_MUL :: 2; +OPR_DIV :: 3; +OPR_MOD :: 4; +OPR_POW :: 5; +OPR_CONCAT :: 6; +OPR_NE :: 7; +OPR_EQ :: 8; +OPR_LT :: 9; +OPR_LE :: 10; +OPR_GT :: 11; +OPR_GE :: 12; +OPR_AND :: 13; +OPR_OR :: 14; +OPR_NONE :: 15; +// Unary operators. +OPR_MINUS :: 0; +OPR_NOT :: 1; +OPR_LEN :: 2; + +UNARY_PRIORITY :: 8; + +// Exported only because Ziran cannot yet index a Vec of a module-scope +// record from another #load file; not part of the API. +#scope_export +LuaSyntaxNode :: struct { + kind: u8 + op: u8 + line: s32 + a: s32 + b: s32 + c: s32 + d: s32 + e: s32 + next: s32 + num: float64 + str: s32 +} +#scope_module + +Parser :: struct { + lx: Lexer + nodes: Vec(LuaSyntaxNode) + depth: s32 +} + +AddNode :: (p: *Parser, kind: u8, line: s32) -> s32 { + at := p.nodes.count + VecResize(p.nodes, at + 1) + p.nodes[at].kind = kind + p.nodes[at].line = line + p.nodes[at].a = -1 + p.nodes[at].b = -1 + p.nodes[at].c = -1 + p.nodes[at].d = -1 + p.nodes[at].e = -1 + p.nodes[at].next = -1 + p.nodes[at].str = -1 + return cast(s32) at +} + +Failed :: (p: *Parser) -> bool #inline { return p.lx.failed } + +SyntaxError :: (p: *Parser, message: string) { LexError(*p.lx, message, true) } + +Check :: (p: *Parser, kind: s32) -> bool { + if p.lx.tok.kind != kind { + text: Vec(u8) + VecPush(text, #char "'") + TokenText(kind, *text) + BuilderAppend(text, "' expected") + SyntaxError(p, BytesView(*text)) + VecFree(text) + return false + } + return true +} + +Accept :: (p: *Parser, kind: s32) -> bool { + if p.lx.tok.kind == kind { NextToken(*p.lx); return true } + return false +} + +Expect :: (p: *Parser, kind: s32) -> bool { + if !Check(p, kind) { return false } + NextToken(*p.lx) + return true +} + +// Expect a closing token that matches an opener on another line. +ExpectMatch :: (p: *Parser, what: s32, who: s32, line: s32) -> bool { + if p.lx.tok.kind == what { NextToken(*p.lx); return true } + if line == p.lx.line { + return Expect(p, what) + } + text: Vec(u8) + VecPush(text, #char "'") + TokenText(what, *text) + BuilderAppend(text, "' expected (to close '") + TokenText(who, *text) + BuilderAppend(text, "' at line ") + Append(*text, cast(s64) line) + VecPush(text, #char ")") + SyntaxError(p, BytesView(*text)) + VecFree(text) + return false +} + +ExpectName :: (p: *Parser) -> s32 { + if !Check(p, TK_NAME) { return -1 } + h := p.lx.tok.str + NextToken(*p.lx) + return h +} + +BlockFollow :: (kind: s32) -> bool { + return kind == TK_ELSE || kind == TK_ELSEIF || kind == TK_END || kind == TK_UNTIL || kind == TK_EOS +} + +// Parse statements until a block terminator; returns the first statement. +ParseBlock :: (p: *Parser) -> s32 { + first: s32 = -1 + last: s32 = -1 + p.depth += 1 + if p.depth > 200 { SyntaxError(p, "chunk has too many syntax levels"); return -1 } + while !BlockFollow(p.lx.tok.kind) && !Failed(p) { + if p.lx.tok.kind == TK_RETURN { + s := ParseReturn(p) + if first < 0 { first = s } else { p.nodes[last].next = s } + last = s + break + } + if p.lx.tok.kind == TK_BREAK { + s := AddNode(p, S_BREAK, p.lx.tok.line) + NextToken(*p.lx) + Accept(p, #char ";") + if first < 0 { first = s } else { p.nodes[last].next = s } + last = s + // Lua 5.1 requires break to end its block; LuaJIT allows more. + continue + } + s := ParseStatement(p) + if s >= 0 { + if first < 0 { first = s } else { p.nodes[last].next = s } + last = s + } + Accept(p, #char ";") + } + p.depth -= 1 + return first +} + +ParseReturn :: (p: *Parser) -> s32 { + s := AddNode(p, S_RETURN, p.lx.tok.line) + NextToken(*p.lx) + if !BlockFollow(p.lx.tok.kind) && p.lx.tok.kind != #char ";" { + p.nodes[s].a = ParseExprList(p) + } + Accept(p, #char ";") + return s +} + +ParseStatement :: (p: *Parser) -> s32 { + line := p.lx.tok.line + kind := p.lx.tok.kind + if kind == TK_IF { return ParseIf(p, line) } + if kind == TK_WHILE { + NextToken(*p.lx) + s := AddNode(p, S_WHILE, line) + cond := ParseExpr(p) + p.nodes[s].a = cond + Expect(p, TK_DO) + body := ParseBlock(p) + p.nodes[s].b = body + ExpectMatch(p, TK_END, TK_WHILE, line) + return s + } + if kind == TK_DO { + NextToken(*p.lx) + s := AddNode(p, S_DO, line) + body := ParseBlock(p) + p.nodes[s].a = body + ExpectMatch(p, TK_END, TK_DO, line) + return s + } + if kind == TK_FOR { return ParseFor(p, line) } + if kind == TK_REPEAT { + NextToken(*p.lx) + s := AddNode(p, S_REPEAT, line) + body := ParseBlock(p) + p.nodes[s].a = body + ExpectMatch(p, TK_UNTIL, TK_REPEAT, line) + cond := ParseExpr(p) + p.nodes[s].b = cond + return s + } + if kind == TK_FUNCTION { + NextToken(*p.lx) + s := AddNode(p, S_FUNCTION, line) + // funcname: Name {'.' Name} [':' Name] + name := ExpectName(p) + if name < 0 { return s } + target := AddNode(p, E_NAME, line) + p.nodes[target].str = name + method := false + while p.lx.tok.kind == #char "." || p.lx.tok.kind == #char ":" { + is_method := p.lx.tok.kind == #char ":" + NextToken(*p.lx) + key_name := ExpectName(p) + if key_name < 0 { return s } + key := AddNode(p, E_STRING, line) + p.nodes[key].str = key_name + index := AddNode(p, E_INDEX, line) + p.nodes[index].a = target + p.nodes[index].b = key + target = index + if is_method { method = true; break } + } + p.nodes[s].a = target + function := ParseFunctionBody(p, method, line) + p.nodes[s].b = function + return s + } + if kind == TK_LOCAL { + NextToken(*p.lx) + if Accept(p, TK_FUNCTION) { + s := AddNode(p, S_LOCALFUNC, line) + name := ExpectName(p) + decl := AddNode(p, N_DECL, line) + p.nodes[decl].str = name + p.nodes[s].a = decl + function := ParseFunctionBody(p, false, line) + p.nodes[s].b = function + return s + } + s := AddNode(p, S_LOCAL, line) + first: s32 = -1 + last: s32 = -1 + while true { + name := ExpectName(p) + if name < 0 { return s } + decl := AddNode(p, N_DECL, line) + p.nodes[decl].str = name + if first < 0 { first = decl } else { p.nodes[last].next = decl } + last = decl + if !Accept(p, #char ",") { break } + } + p.nodes[s].a = first + if Accept(p, #char "=") { + exprs := ParseExprList(p) + p.nodes[s].b = exprs + } + return s + } + if kind == #char ":" && LookAhead(*p.lx) == #char ":" { + // ::label:: + NextToken(*p.lx) + NextToken(*p.lx) + s := AddNode(p, S_LABEL, line) + p.nodes[s].str = ExpectName(p) + if Expect(p, #char ":") { Expect(p, #char ":") } + return s + } + if kind == TK_NAME && p.lx.tok.str == GotoName(p) && LookAhead(*p.lx) == TK_NAME { + NextToken(*p.lx) + s := AddNode(p, S_GOTO, line) + p.nodes[s].str = ExpectName(p) + return s + } + return ParseExprStatement(p) +} + +GotoName :: (p: *Parser) -> s32 { return p.lx.L.name_goto } + +ParseIf :: (p: *Parser, line: s32) -> s32 { + // if cond then block {elseif cond then block} [else block] end + NextToken(*p.lx) + s := AddNode(p, S_IF, line) + cond := ParseExpr(p) + p.nodes[s].a = cond + Expect(p, TK_THEN) + body := ParseBlock(p) + p.nodes[s].b = body + current := s + while p.lx.tok.kind == TK_ELSEIF && !Failed(p) { + elif_line := p.lx.tok.line + NextToken(*p.lx) + branch := AddNode(p, S_IF, elif_line) + branch_cond := ParseExpr(p) + p.nodes[branch].a = branch_cond + Expect(p, TK_THEN) + branch_body := ParseBlock(p) + p.nodes[branch].b = branch_body + p.nodes[current].c = branch + current = branch + } + if Accept(p, TK_ELSE) { + block := AddNode(p, S_DO, p.lx.tok.line) + else_body := ParseBlock(p) + p.nodes[block].a = else_body + p.nodes[current].c = block + } + ExpectMatch(p, TK_END, TK_IF, line) + return s +} + +ParseFor :: (p: *Parser, line: s32) -> s32 { + NextToken(*p.lx) + name := ExpectName(p) + if name < 0 { return -1 } + decl := AddNode(p, N_DECL, line) + p.nodes[decl].str = name + if p.lx.tok.kind == #char "=" { + NextToken(*p.lx) + s := AddNode(p, S_NUMFOR, line) + p.nodes[s].a = decl + start := ParseExpr(p) + p.nodes[s].b = start + Expect(p, #char ",") + limit := ParseExpr(p) + p.nodes[s].c = limit + if Accept(p, #char ",") { + step := ParseExpr(p) + p.nodes[s].d = step + } + Expect(p, TK_DO) + body := ParseBlock(p) + p.nodes[s].e = body + ExpectMatch(p, TK_END, TK_FOR, line) + return s + } + if p.lx.tok.kind == #char "," || p.lx.tok.kind == TK_IN { + s := AddNode(p, S_GENFOR, line) + last := decl + while Accept(p, #char ",") { + other := ExpectName(p) + if other < 0 { return s } + next := AddNode(p, N_DECL, line) + p.nodes[next].str = other + p.nodes[last].next = next + last = next + } + p.nodes[s].a = decl + Expect(p, TK_IN) + exprs := ParseExprList(p) + p.nodes[s].b = exprs + Expect(p, TK_DO) + body := ParseBlock(p) + p.nodes[s].c = body + ExpectMatch(p, TK_END, TK_FOR, line) + return s + } + SyntaxError(p, "'=' or 'in' expected") + return -1 +} + +ParseExprStatement :: (p: *Parser) -> s32 { + line := p.lx.tok.line + first := ParseSuffixedExpr(p) + if Failed(p) { return -1 } + if p.lx.tok.kind == #char "=" || p.lx.tok.kind == #char "," { + s := AddNode(p, S_ASSIGN, line) + p.nodes[s].a = first + last := first + if !IsAssignable(p, first) { SyntaxError(p, "syntax error"); return s } + while Accept(p, #char ",") { + target := ParseSuffixedExpr(p) + if Failed(p) { return s } + if !IsAssignable(p, target) { SyntaxError(p, "syntax error"); return s } + p.nodes[last].next = target + last = target + } + Expect(p, #char "=") + exprs := ParseExprList(p) + p.nodes[s].b = exprs + return s + } + kind := p.nodes[first].kind + if kind != E_CALL && kind != E_METHOD { + SyntaxError(p, "syntax error") + return -1 + } + s := AddNode(p, S_CALL, line) + p.nodes[s].a = first + return s +} + +IsAssignable :: (p: *Parser, node: s32) -> bool { + kind := p.nodes[node].kind + return kind == E_NAME || kind == E_INDEX +} + +ParseExprList :: (p: *Parser) -> s32 { + first := ParseExpr(p) + last := first + while Accept(p, #char ",") && !Failed(p) { + next := ParseExpr(p) + if last >= 0 { p.nodes[last].next = next } + last = next + } + return first +} + +ParsePrimaryExpr :: (p: *Parser) -> s32 { + line := p.lx.tok.line + if p.lx.tok.kind == TK_NAME { + node := AddNode(p, E_NAME, line) + p.nodes[node].str = p.lx.tok.str + NextToken(*p.lx) + return node + } + if p.lx.tok.kind == #char "(" { + NextToken(*p.lx) + inner := ParseExpr(p) + ExpectMatch(p, #char ")", #char "(", line) + node := AddNode(p, E_PAREN, line) + p.nodes[node].a = inner + return node + } + SyntaxError(p, "unexpected symbol") + return -1 +} + +ParseSuffixedExpr :: (p: *Parser) -> s32 { + expr := ParsePrimaryExpr(p) + while !Failed(p) { + kind := p.lx.tok.kind + line := p.lx.tok.line + if kind == #char "." { + NextToken(*p.lx) + name := ExpectName(p) + key := AddNode(p, E_STRING, line) + p.nodes[key].str = name + index := AddNode(p, E_INDEX, line) + p.nodes[index].a = expr + p.nodes[index].b = key + expr = index + } else if kind == #char "[" { + NextToken(*p.lx) + key := ParseExpr(p) + Expect(p, #char "]") + index := AddNode(p, E_INDEX, line) + p.nodes[index].a = expr + p.nodes[index].b = key + expr = index + } else if kind == #char ":" { + if LookAhead(*p.lx) == #char ":" { return expr } + NextToken(*p.lx) + name := ExpectName(p) + call := AddNode(p, E_METHOD, line) + p.nodes[call].a = expr + p.nodes[call].str = name + args := ParseCallArgs(p, line) + p.nodes[call].b = args + expr = call + } else if kind == #char "(" || kind == TK_STRING || kind == #char "{" { + call := AddNode(p, E_CALL, line) + p.nodes[call].a = expr + args := ParseCallArgs(p, line) + p.nodes[call].b = args + expr = call + } else { + return expr + } + } + return expr +} + +ParseCallArgs :: (p: *Parser, line: s32) -> s32 { + kind := p.lx.tok.kind + if kind == TK_STRING { + node := AddNode(p, E_STRING, p.lx.tok.line) + p.nodes[node].str = p.lx.tok.str + NextToken(*p.lx) + return node + } + if kind == #char "{" { return ParseTable(p) } + if kind != #char "(" { SyntaxError(p, "function arguments expected"); return -1 } + if line != p.lx.tok.line { + SyntaxError(p, "ambiguous syntax (function call x new statement)") + return -1 + } + NextToken(*p.lx) + if p.lx.tok.kind == #char ")" { NextToken(*p.lx); return -1 } + args := ParseExprList(p) + ExpectMatch(p, #char ")", #char "(", line) + return args +} + +ParseTable :: (p: *Parser) -> s32 { + line := p.lx.tok.line + table := AddNode(p, E_TABLE, line) + Expect(p, #char "{") + first: s32 = -1 + last: s32 = -1 + while p.lx.tok.kind != #char "}" && !Failed(p) { + field: s32 = -1 + if p.lx.tok.kind == TK_NAME && LookAhead(*p.lx) == #char "=" { + field = AddNode(p, F_PAIR, p.lx.tok.line) + key := AddNode(p, E_STRING, p.lx.tok.line) + p.nodes[key].str = p.lx.tok.str + NextToken(*p.lx) + NextToken(*p.lx) + value := ParseExpr(p) + p.nodes[field].a = key + p.nodes[field].b = value + } else if p.lx.tok.kind == #char "[" { + field = AddNode(p, F_PAIR, p.lx.tok.line) + NextToken(*p.lx) + key := ParseExpr(p) + Expect(p, #char "]") + Expect(p, #char "=") + value := ParseExpr(p) + p.nodes[field].a = key + p.nodes[field].b = value + } else { + field = AddNode(p, F_ITEM, p.lx.tok.line) + value := ParseExpr(p) + p.nodes[field].a = value + } + if first < 0 { first = field } else { p.nodes[last].next = field } + last = field + if !Accept(p, #char ",") && !Accept(p, #char ";") { break } + } + ExpectMatch(p, #char "}", #char "{", line) + p.nodes[table].a = first + return table +} + +// function body: (params) block end. Returns an E_FUNCTION node with +// a = first parameter decl, b = body, c = 1 when vararg, e = end line. +ParseFunctionBody :: (p: *Parser, method: bool, line: s32) -> s32 { + node := AddNode(p, E_FUNCTION, line) + first: s32 = -1 + last: s32 = -1 + if method { + self := AddNode(p, N_DECL, line) + p.nodes[self].str = Intern(p.lx.L, "self") + first = self + last = self + } + p.nodes[node].c = 0 + Expect(p, #char "(") + if p.lx.tok.kind != #char ")" { + while !Failed(p) { + if p.lx.tok.kind == TK_DOTS { + NextToken(*p.lx) + p.nodes[node].c = 1 + break + } + name := ExpectName(p) + if name < 0 { return node } + decl := AddNode(p, N_DECL, line) + p.nodes[decl].str = name + if first < 0 { first = decl } else { p.nodes[last].next = decl } + last = decl + if !Accept(p, #char ",") { break } + } + } + Expect(p, #char ")") + body := ParseBlock(p) + p.nodes[node].a = first + p.nodes[node].b = body + p.nodes[node].e = p.lx.tok.line + ExpectMatch(p, TK_END, TK_FUNCTION, line) + return node +} + +ParseSimpleExpr :: (p: *Parser) -> s32 { + line := p.lx.tok.line + kind := p.lx.tok.kind + if kind == TK_NUMBER { + node := AddNode(p, E_NUMBER, line) + p.nodes[node].num = p.lx.tok.num + NextToken(*p.lx) + return node + } + if kind == TK_STRING { + node := AddNode(p, E_STRING, line) + p.nodes[node].str = p.lx.tok.str + NextToken(*p.lx) + return node + } + if kind == TK_NIL { NextToken(*p.lx); return AddNode(p, E_NIL, line) } + if kind == TK_TRUE { NextToken(*p.lx); return AddNode(p, E_TRUE, line) } + if kind == TK_FALSE { NextToken(*p.lx); return AddNode(p, E_FALSE, line) } + if kind == TK_DOTS { NextToken(*p.lx); return AddNode(p, E_VARARG, line) } + if kind == #char "{" { return ParseTable(p) } + if kind == TK_FUNCTION { + NextToken(*p.lx) + return ParseFunctionBody(p, false, line) + } + return ParseSuffixedExpr(p) +} + +BinaryOperator :: (kind: s32) -> s32 { + if kind == #char "+" { return OPR_ADD } + if kind == #char "-" { return OPR_SUB } + if kind == #char "*" { return OPR_MUL } + if kind == #char "/" { return OPR_DIV } + if kind == #char "%" { return OPR_MOD } + if kind == #char "^" { return OPR_POW } + if kind == TK_CONCAT { return OPR_CONCAT } + if kind == TK_NE { return OPR_NE } + if kind == TK_EQ { return OPR_EQ } + if kind == #char "<" { return OPR_LT } + if kind == TK_LE { return OPR_LE } + if kind == #char ">" { return OPR_GT } + if kind == TK_GE { return OPR_GE } + if kind == TK_AND { return OPR_AND } + if kind == TK_OR { return OPR_OR } + return OPR_NONE +} + +LeftPriority :: (op: s32) -> s32 { + if op <= OPR_SUB { return 6 } + if op <= OPR_MOD { return 7 } + if op == OPR_POW { return 10 } + if op == OPR_CONCAT { return 5 } + if op <= OPR_GE { return 3 } + if op == OPR_AND { return 2 } + return 1 +} + +RightPriority :: (op: s32) -> s32 { + if op == OPR_POW { return 9 } + if op == OPR_CONCAT { return 4 } + return LeftPriority(op) +} + +ParseExpr :: (p: *Parser) -> s32 { return ParseSubExpr(p, 0) } + +// subexpr -> (simpleexp | unop subexpr) { binop subexpr }, folding numbers. +ParseSubExpr :: (p: *Parser, limit: s32) -> s32 { + p.depth += 1 + if p.depth > 200 { SyntaxError(p, "chunk has too many syntax levels"); return -1 } + left: s32 = -1 + line := p.lx.tok.line + kind := p.lx.tok.kind + if kind == TK_NOT || kind == #char "-" || kind == #char "#" { + NextToken(*p.lx) + operand := ParseSubExpr(p, UNARY_PRIORITY) + if Failed(p) { p.depth -= 1; return -1 } + op: s32 = ifx kind == TK_NOT then OPR_NOT else (ifx kind == #char "-" then OPR_MINUS else OPR_LEN) + if op == OPR_MINUS && p.nodes[operand].kind == E_NUMBER { + p.nodes[operand].num = -p.nodes[operand].num + left = operand + } else { + left = AddNode(p, E_UNOP, line) + p.nodes[left].op = cast(u8) op + p.nodes[left].a = operand + } + } else { + left = ParseSimpleExpr(p) + } + while !Failed(p) { + op := BinaryOperator(p.lx.tok.kind) + if op == OPR_NONE || LeftPriority(op) <= limit { break } + op_line := p.lx.tok.line + NextToken(*p.lx) + right := ParseSubExpr(p, RightPriority(op)) + if Failed(p) { break } + folded := FoldConstant(p, op, left, right) + if folded >= 0 { left = folded; continue } + node: s32 + if op == OPR_AND { + node = AddNode(p, E_AND, op_line) + } else if op == OPR_OR { + node = AddNode(p, E_OR, op_line) + } else { + node = AddNode(p, E_BINOP, op_line) + p.nodes[node].op = cast(u8) op + } + p.nodes[node].a = left + p.nodes[node].b = right + left = node + } + p.depth -= 1 + return left +} + +FoldConstant :: (p: *Parser, op: s32, left: s32, right: s32) -> s32 { + if op > OPR_POW { return -1 } + if p.nodes[left].kind != E_NUMBER || p.nodes[right].kind != E_NUMBER { return -1 } + a := p.nodes[left].num + b := p.nodes[right].num + r: float64 + if op == OPR_ADD { r = a + b } + else if op == OPR_SUB { r = a - b } + else if op == OPR_MUL { r = a * b } + else if op == OPR_DIV { if b == 0.0 { return -1 } r = a / b } + else if op == OPR_MOD { if b == 0.0 { return -1 } r = LuaMod(a, b) } + else { r = LuaPow(a, b) } + if r != r { return -1 } + p.nodes[left].num = r + return left +} diff --git a/src/table.zi b/src/table.zi new file mode 100644 index 0000000..a3f2bde --- /dev/null +++ b/src/table.zi @@ -0,0 +1,300 @@ +// Lua tables: a dense array part for keys 1..n plus an open-addressed hash +// part with linear probing. Assigning nil keeps the key as a dead entry so +// `next` keeps working during traversal; a rehash drops dead keys. + +#scope_module + +NumberBits :: union { f: float64; u: u64; } + +MixHash :: (x: u64) -> u64 #inline { + h := x * 0x9E3779B97F4A7C15 + return h ^ (h >> 29) +} + +// Integral value of n when it is a whole number in s64 range. +AsInteger :: (n: float64) -> (value: s64, ok: bool) #inline { + if n >= -9007199254740992.0 && n <= 9007199254740992.0 { + i := cast(s64) n + if cast(float64) i == n { return i, true } + } + return 0, false +} + +KeyHash :: (key: LuaValue) -> u64 #inline { + if key.t == LUA_TSTRING { return MixHash(cast(u64) key.h + 0x51) } + if key.t == LUA_TNUMBER || key.t == LUA_TLIGHTUSERDATA { + i, ok := AsInteger(key.n) + if ok { return MixHash(cast(u64) i) } + bits: NumberBits + bits.f = key.n + return MixHash(bits.u) + } + return MixHash((cast(u64) key.t << 32) ^ cast(u64) key.h) +} + +// Slot holding `key`, or -1. +FindSlot :: (L: *LuaState, t: s32, key: LuaValue) -> s64 { + count := L.tables[t].nodes.count + if count == 0 { return -1 } + mask := count - 1 + slot := cast(s64)(KeyHash(key) & cast(u64) mask) + while true { + k := L.tables[t].nodes[slot].key + if k.t == LUA_TNIL { return -1 } + if RawEqual(k, key) { return slot } + slot = (slot + 1) & mask + } + return -1 +} + +// Fast string-key lookup (strings are interned, so handles compare). +FindStringSlot :: (L: *LuaState, t: s32, h: s32) -> s64 #inline { + count := L.tables[t].nodes.count + if count == 0 { return -1 } + mask := count - 1 + slot := cast(s64)(MixHash(cast(u64) h + 0x51) & cast(u64) mask) + while true { + k := *L.tables[t].nodes[slot].key + if k.t == LUA_TSTRING && k.h == h { return slot } + if k.t == LUA_TNIL { return -1 } + slot = (slot + 1) & mask + } + return -1 +} + +GetStr :: (L: *LuaState, t: s32, h: s32) -> LuaValue #inline { + slot := FindStringSlot(L, t, h) + if slot < 0 { return NilValue() } + return L.tables[t].nodes[slot].value +} + +GetInt :: (L: *LuaState, t: s32, i: s64) -> LuaValue #inline { + if i >= 1 && i <= L.tables[t].arr.count { return L.tables[t].arr[i - 1] } + if L.tables[t].nodes.count == 0 { return NilValue() } + slot := FindSlot(L, t, NumberValue(cast(float64) i)) + if slot < 0 { return NilValue() } + return L.tables[t].nodes[slot].value +} + +RawGet :: (L: *LuaState, t: s32, key: LuaValue) -> LuaValue { + if key.t == LUA_TSTRING { return GetStr(L, t, key.h) } + if key.t == LUA_TNUMBER { + i, ok := AsInteger(key.n) + if ok && i >= 1 && i <= L.tables[t].arr.count { return L.tables[t].arr[i - 1] } + } + if key.t == LUA_TNIL { return NilValue() } + slot := FindSlot(L, t, key) + if slot < 0 { return NilValue() } + return L.tables[t].nodes[slot].value +} + +// Insert a key known to be absent into a table with room. +InsertNew :: (L: *LuaState, t: s32, key: LuaValue, value: LuaValue) { + mask := L.tables[t].nodes.count - 1 + slot := cast(s64)(KeyHash(key) & cast(u64) mask) + while L.tables[t].nodes[slot].key.t != LUA_TNIL { slot = (slot + 1) & mask } + L.tables[t].nodes[slot].key = key + L.tables[t].nodes[slot].value = value + L.tables[t].used += 1 +} + +// Rebuild the hash part with room for `extra` more keys, dropping dead keys. +Rehash :: (L: *LuaState, t: s32, extra: s64) { + live: s64 = 0 + i: s64 = 0 + while i < L.tables[t].nodes.count { + if L.tables[t].nodes[i].key.t != LUA_TNIL && L.tables[t].nodes[i].value.t != LUA_TNIL { live += 1 } + i += 1 + } + needed := live + extra + size: s64 = 4 + while size * 3 < needed * 4 { size *= 2 } + old: Vec(LuaNode) + VecSwap(old, L.tables[t].nodes) + VecResize(L.tables[t].nodes, size) + L.tables[t].used = 0 + L.allocated += (size - old.count) * 32 + i = 0 + while i < old.count { + if old[i].key.t != LUA_TNIL && old[i].value.t != LUA_TNIL { + InsertNew(L, t, old[i].key, old[i].value) + } + i += 1 + } + VecFree(old) +} + +// Move keys n+1, n+2, ... from the hash part onto the end of the array. +MigrateToArray :: (L: *LuaState, t: s32) { + while L.tables[t].nodes.count > 0 { + next := cast(float64)(L.tables[t].arr.count + 1) + slot := FindSlot(L, t, NumberValue(next)) + if slot < 0 || L.tables[t].nodes[slot].value.t == LUA_TNIL { return } + value := L.tables[t].nodes[slot].value + // Leave a dead key behind so probing chains stay intact. + L.tables[t].nodes[slot].value = NilValue() + VecPush(L.tables[t].arr, value) + L.allocated += 16 + } +} + +// Assign t[key] = value without metamethods. The key must not be nil/NaN. +RawSet :: (L: *LuaState, t: s32, key: LuaValue, value: LuaValue) { + L.tables[t].absent = 0 + if key.t == LUA_TNUMBER { + i, ok := AsInteger(key.n) + if ok { + SetInt(L, t, i, value) + return + } + } + SetHash(L, t, key, value) +} + +SetHash :: (L: *LuaState, t: s32, key: LuaValue, value: LuaValue) { + slot: s64 + if key.t == LUA_TSTRING { slot = FindStringSlot(L, t, key.h) } else { slot = FindSlot(L, t, key) } + if slot >= 0 { + L.tables[t].nodes[slot].value = value + return + } + if value.t == LUA_TNIL { return } + if (L.tables[t].used + 1) * 4 > L.tables[t].nodes.count * 3 { Rehash(L, t, 1) } + InsertNew(L, t, key, value) +} + +SetInt :: (L: *LuaState, t: s32, i: s64, value: LuaValue) { + L.tables[t].absent = 0 + count := L.tables[t].arr.count + if i >= 1 && i <= count { + L.tables[t].arr[i - 1] = value + return + } + key := NumberValue(cast(float64) i) + if i == count + 1 && value.t != LUA_TNIL { + slot: s64 = -1 + if L.tables[t].nodes.count > 0 { slot = FindSlot(L, t, key) } + if slot < 0 { + VecPush(L.tables[t].arr, value) + L.allocated += 16 + if L.tables[t].nodes.count > 0 { MigrateToArray(L, t) } + return + } + L.tables[t].nodes[slot].value = value + return + } + SetHash(L, t, key, value) +} + +SetStr :: (L: *LuaState, t: s32, h: s32, value: LuaValue) { + L.tables[t].absent = 0 + SetHash(L, t, StringValue(h), value) +} + +// A border of the table (Lua's # operator). +TableLength :: (L: *LuaState, t: s32) -> s64 { + n := L.tables[t].arr.count + if n > 0 && L.tables[t].arr[n - 1].t == LUA_TNIL { + // Binary search for a border inside the array. + low: s64 = 0 + high := n + while high - low > 1 { + middle := (low + high) / 2 + if L.tables[t].arr[middle - 1].t == LUA_TNIL { high = middle } else { low = middle } + } + return low + } + if L.tables[t].nodes.count == 0 { return n } + // Unbound search in the hash part. + i := n + j := n + 1 + while GetInt(L, t, j).t != LUA_TNIL { + i = j + if j > 4611686018427387903 / 2 { + // Pathological: linear scan. + k: s64 = 1 + while GetInt(L, t, k).t != LUA_TNIL { k += 1 } + return k - 1 + } + j *= 2 + } + while j - i > 1 { + middle := (i + j) / 2 + if GetInt(L, t, middle).t == LUA_TNIL { j = middle } else { i = middle } + } + return i +} + +// Iteration: position 0..arr.count-1 is the array, then hash slots. +// Returns the next position with a non-nil value at or after `from`, or -1. +NextPosition :: (L: *LuaState, t: s32, from: s64) -> s64 { + i := from + n := L.tables[t].arr.count + while i < n { + if L.tables[t].arr[i].t != LUA_TNIL { return i } + i += 1 + } + count := L.tables[t].nodes.count + while i - n < count { + slot := i - n + if L.tables[t].nodes[slot].key.t != LUA_TNIL && L.tables[t].nodes[slot].value.t != LUA_TNIL { return i } + i += 1 + } + return -1 +} + +// Position just after `key`, or -2 when the key is not in the table. +PositionAfter :: (L: *LuaState, t: s32, key: LuaValue) -> s64 { + if key.t == LUA_TNIL { return 0 } + if key.t == LUA_TNUMBER { + i, ok := AsInteger(key.n) + if ok && i >= 1 && i <= L.tables[t].arr.count { return i } + } + slot := FindSlot(L, t, key) + if slot < 0 { return -2 } + return L.tables[t].arr.count + slot + 1 +} + +PositionKey :: (L: *LuaState, t: s32, position: s64) -> LuaValue #inline { + n := L.tables[t].arr.count + if position < n { return NumberValue(cast(float64)(position + 1)) } + return L.tables[t].nodes[position - n].key +} + +PositionValue :: (L: *LuaState, t: s32, position: s64) -> LuaValue #inline { + n := L.tables[t].arr.count + if position < n { return L.tables[t].arr[position] } + return L.tables[t].nodes[position - n].value +} + +// next(t, key): writes the following pair; false at the end. Returns +// ok=false (with done=false) when the key is invalid. +TableNext :: (L: *LuaState, t: s32, key: LuaValue, out_key: *LuaValue, out_value: *LuaValue) -> (found: bool, ok: bool) { + from := PositionAfter(L, t, key) + if from == -2 { return false, false } + position := NextPosition(L, t, from) + if position < 0 { return false, true } + < LuaValue #inline { + if mt < 0 { return NilValue() } + if (L.tables[mt].absent & (cast(u32) 1 << cast(u32) event)) != 0 { return NilValue() } + v := GetStr(L, mt, L.tm_names[event]) + if v.t == LUA_TNIL { L.tables[mt].absent |= cast(u32) 1 << cast(u32) event } + return v +} + +MetatableOf :: (L: *LuaState, v: LuaValue) -> s32 { + if v.t == LUA_TTABLE { return L.tables[v.h].meta } + if v.t == LUA_TUSERDATA { return L.userdata[v.h].meta } + if v.t <= LUA_TLIGHTUSERDATA { return L.type_meta[v.t] } + return -1 +} + +GetTM :: (L: *LuaState, v: LuaValue, event: s32) -> LuaValue { + return FastTM(L, MetatableOf(L, v), event) +} diff --git a/src/value.zi b/src/value.zi new file mode 100644 index 0000000..aa60378 --- /dev/null +++ b/src/value.zi @@ -0,0 +1,618 @@ +// Core value and object model: tagged values, VM-owned object arenas and +// interned strings. Objects are referenced by s32 handles into per-kind +// arenas held inline in the state, so cyclic Lua graphs need no owning +// pointers. Never keep a pointer to an arena element across an allocation +// of the same kind: the arena may move its elements when it grows. + +#scope_export + +// Value tags. FALSE and TRUE are separate tags so truthiness is one compare. +LUA_TNIL :: 0; +LUA_TFALSE :: 1; +LUA_TTRUE :: 2; +LUA_TNUMBER :: 3; +LUA_TSTRING :: 4; +LUA_TTABLE :: 5; +LUA_TFUNCTION :: 6; +LUA_TUSERDATA :: 7; +LUA_TTHREAD :: 8; +LUA_TLIGHTUSERDATA :: 9; +// Internal: a mutable cell holding a captured local. +LUA_TBOX :: 10; + +// Status codes returned by calls and loads. +LUA_OK :: 0; +LUA_YIELD :: 1; +LUA_ERRRUN :: 2; +LUA_ERRSYNTAX :: 3; +LUA_ERRMEM :: 4; +LUA_ERRERR :: 5; +LUA_ERRFILE :: 6; + +// A native returns its result count, or one of these. +LUA_NATIVE_ERROR :: -1; +LUA_NATIVE_YIELD :: -2; + +LUA_MULTRET :: -1; + +LuaValue :: struct { + n: float64 + h: s32 + t: u8 +} + +// A native Ziran function callable from Lua. It reads its arguments at +// stack indices 1..LuaGetTop(L), pushes results and returns their count, +// or returns LuaRaise(L) / LuaErrorText(L, ...) to raise an error. +LuaNative :: #type (L: *LuaState) -> s32; + +// Called every `count` VM checkpoints (calls and backward jumps). Return +// true to continue, false to raise an error (the message is the value on +// top of the stack when the hook pushed one, else "instruction limit"). +LuaHook :: #type (L: *LuaState) -> bool; + +// Called when a userdata created with a finalizer is collected. +LuaFinalizer :: #type (L: *LuaState, data: *void, tag: s64) -> void; + +// Receives print() output; null writes to standard output. +LuaPrintSink :: #type (context: *void, text: string) -> void; + +LuaLimits :: struct { + // Estimated live heap bytes before allocation raises "not enough + // memory"; 0 means unlimited. + max_memory: s64 + // Maximum nested native re-entry depth (natives calling back into Lua). + max_native_depth: s32 + // Maximum Lua call frames per thread. + max_frames: s32 +} + +LuaDefaultLimits :: () -> LuaLimits { + limits: LuaLimits + limits.max_memory = 0 + limits.max_native_depth = 190 + limits.max_frames = 200000 + return limits +} + +#scope_module + +NilValue :: () -> LuaValue #inline { v: LuaValue; return v } +BoolValue :: (b: bool) -> LuaValue #inline { v: LuaValue; v.t = ifx b then cast(u8) LUA_TTRUE else cast(u8) LUA_TFALSE; return v } +NumberValue :: (n: float64) -> LuaValue #inline { v: LuaValue; v.t = LUA_TNUMBER; v.n = n; return v } +ObjectValue :: (t: u8, h: s32) -> LuaValue #inline { v: LuaValue; v.t = t; v.h = h; return v } +StringValue :: (h: s32) -> LuaValue #inline { v: LuaValue; v.t = LUA_TSTRING; v.h = h; return v } +TableValue :: (h: s32) -> LuaValue #inline { v: LuaValue; v.t = LUA_TTABLE; v.h = h; return v } +FunctionValue :: (h: s32) -> LuaValue #inline { v: LuaValue; v.t = LUA_TFUNCTION; v.h = h; return v } + +Truthy :: (v: LuaValue) -> bool #inline { return v.t >= LUA_TTRUE } + +RawEqual :: (a: LuaValue, b: LuaValue) -> bool #inline { + if a.t != b.t { return false } + if a.t == LUA_TNUMBER || a.t == LUA_TLIGHTUSERDATA { return a.n == b.n } + if a.t <= LUA_TTRUE { return true } + return a.h == b.h +} + +// The object records live in the state's arenas. They are exported with +// LuaState (whose fields hold them) but are not part of the stable API. +#scope_export + +LuaString :: struct { + bytes: Vec(u8) + hash: u32 + mark: u8 + // Reserved word index + 1 for the lexer, 0 otherwise. + reserved: u8 + live: bool +} + +LuaNode :: struct { + key: LuaValue + value: LuaValue +} + +LuaTable :: struct { + arr: Vec(LuaValue) + nodes: Vec(LuaNode) + // Occupied slots in nodes, including dead nil-valued keys. + used: s64 + meta: s32 + mark: u8 + live: bool + // Bit i set: metamethod i is known absent (cleared on any raw write). + absent: u32 +} + +LuaUpvalDesc :: struct { + // true: capture the parent's local register (which holds a box); + // false: capture the parent's upvalue at `index`. + from_local: bool + index: s32 +} + +LuaLocVar :: struct { + name: s32 + reg: s32 + start_pc: s32 + end_pc: s32 +} + +LuaInstr :: struct { + op: u8 + a: s32 + b: s32 + c: s32 +} + +LuaProto :: struct { + code: Vec(LuaInstr) + lines: Vec(s32) + constants: Vec(LuaValue) + protos: Vec(s32) + upvals: Vec(LuaUpvalDesc) + upval_names: Vec(s32) + locvars: Vec(LuaLocVar) + num_params: s32 + is_vararg: bool + max_stack: s32 + line_defined: s32 + last_line: s32 + source: s32 + mark: u8 + live: bool +} + +LuaClosure :: struct { + // >= 0: a Lua function's prototype; -1: a native function. + proto: s32 + native: LuaNative + // Lua closures: box handles. + upvals: Vec(s32) + // Native closures: their upvalue values. + native_upvals: Vec(LuaValue) + env: s32 + // Native name for tracebacks ("print", "format", ...), or -1. + name: s32 + mark: u8 + live: bool +} + +LuaBox :: struct { + value: LuaValue + mark: u8 + live: bool +} + +LuaUserdata :: struct { + data: *void + tag: s64 + meta: s32 + env: s32 + finalizer: LuaFinalizer + has_finalizer: bool + mark: u8 + live: bool + finalized: bool +} + +LuaFrame :: struct { + closure: s32 + // Stack index of the called function value; results go here. + func: s64 + // Register 0 (Lua) or argument 1 (native). + base: s64 + pc: s64 + // Requested result count, LUA_MULTRET for all. + want: s32 + native: bool + // Extra arguments of a vararg function live at [vararg, vararg + nvarargs). + vararg: s64 + nvarargs: s32 + // Number of tail calls that replaced this frame (for tracebacks). + tail: s32 +} + +LuaHandler :: struct { + handler: LuaValue + // Frames at or above this level are guarded by the handler. + frame_level: s64 +} + +THREAD_SUSPENDED :: 0; +THREAD_RUNNING :: 1; +THREAD_NORMAL :: 2; +THREAD_DEAD :: 3; + +LuaThread :: struct { + stack: Vec(LuaValue) + frames: Vec(LuaFrame) + // Protected-call handlers for xpcall, innermost last. + handlers: Vec(LuaHandler) + top: s64 + status: u8 + mark: u8 + live: bool + // Nested interpreter entries on this thread (natives calling back). + nesting: s32 + // A yield is pending: resume values land at yield_func with yield_want. + yield_func: s64 + yield_want: s32 + started: bool + env: s32 +} + +#scope_module + +// Metamethod indices. +TM_INDEX :: 0; +TM_NEWINDEX :: 1; +TM_GC :: 2; +TM_MODE :: 3; +TM_EQ :: 4; +TM_ADD :: 5; +TM_SUB :: 6; +TM_MUL :: 7; +TM_DIV :: 8; +TM_MOD :: 9; +TM_POW :: 10; +TM_UNM :: 11; +TM_LEN :: 12; +TM_LT :: 13; +TM_LE :: 14; +TM_CONCAT :: 15; +TM_CALL :: 16; +TM_TOSTRING :: 17; +TM_METATABLE :: 18; +TM_NAME :: 19; +TM_COUNT :: 20; + +#scope_export + +// One Lua universe. The host owns this record (a global or a long-lived +// local) and passes its address to every API call; LuaOpen initializes it +// and LuaClose releases everything it holds. +LuaState :: struct { + strings: Vec(LuaString) + string_free: Vec(s32) + intern: Vec(s32) + intern_used: s64 + + tables: Vec(LuaTable) + table_free: Vec(s32) + closures: Vec(LuaClosure) + closure_free: Vec(s32) + protos: Vec(LuaProto) + proto_free: Vec(s32) + boxes: Vec(LuaBox) + box_free: Vec(s32) + userdata: Vec(LuaUserdata) + userdata_free: Vec(s32) + threads: Vec(LuaThread) + thread_free: Vec(s32) + + // The running thread. + cur: s32 + main: s32 + globals: s32 + registry: s32 + // Type metatables for strings and other non-table values, by tag. + type_meta: [11]s32 + tm_names: [20]s32 + // Common interned names. + name_n: s32 + name_goto: s32 + name_self: s32 + name_loaded: s32 + // The base `next` function and the ipairs iterator, for loop fast paths. + next_fn: s32 + inext_fn: s32 + // Extra frames and native levels allowed while an error handler runs. + handler_slack: s32 + // Weak tables found while marking. + weak: Vec(s32) + + // Pending error object while an error propagates. + error: LuaValue + // The pending error already went through its xpcall handler. + error_traced: bool + // Host refs: free registry array slots. + ref_free: Vec(s32) + + // Garbage collector accounting (estimated bytes). + allocated: s64 + threshold: s64 + gray: Vec(LuaValue) + pending_finalize: Vec(s32) + collecting: bool + // Threads on the resume chain, for GC roots. + resumers: Vec(s32) + // Native depth across threads. + native_depth: s32 + limits: LuaLimits + open: bool + + hook: LuaHook + hook_set: bool + hook_count: s64 + hook_left: s64 + print_sink: LuaPrintSink + print_sink_set: bool + print_context: *void + // Directory prefix for dofile/loadfile/io.open; empty disables files. + file_root: Vec(u8) + random_state: u64 + // Monotonic nanoseconds at open, the zero of os.clock. + clock_start: s64 + // Environment name prefixes os.getenv may read, separated by 0 bytes. + env_allow: Vec(u8) + // Metatable shared by io file handles. + file_meta: s32 + // Scratch byte buffers for building strings. + scratch: Vec(u8) + scratch2: Vec(u8) + // Host context pointer for embedding applications. + host: *void +} + +#scope_module + +// String bytes as a borrowed view. Valid until the string is collected; +// the bytes never move while the string lives. +// Ziran has no portable way to borrow a Vec(u8) held behind a pointer as a +// string whose lifetime the checker can follow, so the VM builds the string +// descriptor itself, the way std/byte_text_linux.zi does (C target). +RawText :: struct { data: *u8; length: u64; } + +ViewOf :: (first: *u8, count: s64) -> string #inline { + result: string = "" + if count <= 0 { return result } + descriptor: *RawText = cast(*RawText)(*result) + descriptor.data = first + descriptor.length = cast(u64) count + return result +} + +StrView :: (L: *LuaState, h: s32) -> string #inline { + count := L.strings[h].bytes.count + if count == 0 { return "" } + return ViewOf(*L.strings[h].bytes[0], count) +} + +StrLen :: (L: *LuaState, h: s32) -> s64 #inline { return L.strings[h].bytes.count } + +BytesView :: (bytes: *Vec(u8)) -> string #inline { + if bytes.count == 0 { return "" } + return ViewOf(*(< u32 { + // FNV-1a; long strings hash a sample like Lua 5.1 does. + h: u32 = 2166136261 ^ cast(u32) text.count + step: s64 = (text.count >> 5) + 1 + i := text.count + while i >= step { + h = (h ^ cast(u32) text[i - 1]) * 16777619 + i -= step + } + return h +} + +GrowIntern :: (L: *LuaState) { + old_count := L.intern.count + capacity: s64 = ifx old_count == 0 then 1024 else old_count * 2 + fresh: Vec(s32) + VecResize(fresh, capacity) + i: s64 = 0 + while i < capacity { fresh[i] = -1; i += 1 } + mask := capacity - 1 + i = 0 + while i < old_count { + h := L.intern[i] + if h >= 0 { + slot := cast(s64) L.strings[h].hash & mask + while fresh[slot] >= 0 { slot = (slot + 1) & mask } + fresh[slot] = h + } + i += 1 + } + VecSwap(fresh, L.intern) + VecFree(fresh) +} + +SameBytes :: (L: *LuaState, h: s32, text: string) -> bool { + if L.strings[h].bytes.count != text.count { return false } + i: s64 = 0 + while i < text.count { + if L.strings[h].bytes[i] != text[i] { return false } + i += 1 + } + return true +} + +// Intern bytes and return the string handle. `text` must not view the +// string arena's own bytes of a string that could be collected. +Intern :: (L: *LuaState, text: string) -> s32 { + if (L.intern_used + 1) * 2 > L.intern.count { GrowIntern(L) } + hash := HashBytes(text) + mask := L.intern.count - 1 + slot := cast(s64) hash & mask + while true { + h := L.intern[slot] + if h < 0 { break } + if L.strings[h].hash == hash && SameBytes(L, h, text) { return h } + slot = (slot + 1) & mask + } + handle: s32 + if L.string_free.count > 0 { + handle = L.string_free[L.string_free.count - 1] + VecResize(L.string_free, L.string_free.count - 1) + } else { + handle = cast(s32) L.strings.count + VecResize(L.strings, L.strings.count + 1) + } + VecClear(L.strings[handle].bytes) + BuilderAppend(L.strings[handle].bytes, text) + L.strings[handle].hash = hash + L.strings[handle].mark = 0 + L.strings[handle].reserved = 0 + L.strings[handle].live = true + L.intern[slot] = handle + L.intern_used += 1 + L.allocated += 40 + text.count + return handle +} + +InternBytes :: (L: *LuaState, bytes: *Vec(u8)) -> s32 { + return Intern(L, BytesView(bytes)) +} + +// Remove a dead string from the intern table (backward-shift deletion). +Unintern :: (L: *LuaState, h: s32) { + mask := L.intern.count - 1 + slot := cast(s64) L.strings[h].hash & mask + while L.intern[slot] != h { slot = (slot + 1) & mask } + hole := slot + next := (hole + 1) & mask + while L.intern[next] >= 0 { + other := L.intern[next] + home := cast(s64) L.strings[other].hash & mask + distance_next := (next - home) & mask + distance_hole := (hole - home) & mask + if distance_hole < distance_next { + L.intern[hole] = other + hole = next + } + next = (next + 1) & mask + } + L.intern[hole] = -1 + L.intern_used -= 1 +} + +TakeSlot :: (free_list: *Vec(s32), count: s64) -> s32 { + if free_list.count > 0 { + handle := (< s32 { + handle := TakeSlot(*L.table_free, 0) + if handle < 0 { + handle = cast(s32) L.tables.count + VecResize(L.tables, L.tables.count + 1) + } + L.tables[handle].meta = -1 + L.tables[handle].mark = 0 + L.tables[handle].live = true + L.tables[handle].absent = 0 + L.tables[handle].used = 0 + if narr > 0 { VecReserve(L.tables[handle].arr, narr) } + if nhash > 0 { + size: s64 = 4 + while size * 3 < nhash * 4 { size *= 2 } + VecResize(L.tables[handle].nodes, size) + } + L.allocated += 80 + narr * 16 + L.tables[handle].nodes.count * 32 + return handle +} + +NewBox :: (L: *LuaState, value: LuaValue) -> s32 { + handle := TakeSlot(*L.box_free, 0) + if handle < 0 { + handle = cast(s32) L.boxes.count + VecResize(L.boxes, L.boxes.count + 1) + } + L.boxes[handle].value = value + L.boxes[handle].mark = 0 + L.boxes[handle].live = true + L.allocated += 32 + return handle +} + +NewClosureObject :: (L: *LuaState) -> s32 { + handle := TakeSlot(*L.closure_free, 0) + if handle < 0 { + handle = cast(s32) L.closures.count + VecResize(L.closures, L.closures.count + 1) + } + L.closures[handle].proto = -1 + L.closures[handle].name = -1 + L.closures[handle].env = L.globals + L.closures[handle].mark = 0 + L.closures[handle].live = true + L.allocated += 64 + return handle +} + +NewProtoObject :: (L: *LuaState) -> s32 { + handle := TakeSlot(*L.proto_free, 0) + if handle < 0 { + handle = cast(s32) L.protos.count + VecResize(L.protos, L.protos.count + 1) + } + L.protos[handle].source = -1 + L.protos[handle].mark = 0 + L.protos[handle].live = true + L.allocated += 160 + return handle +} + +NewUserdataObject :: (L: *LuaState) -> s32 { + handle := TakeSlot(*L.userdata_free, 0) + if handle < 0 { + handle = cast(s32) L.userdata.count + VecResize(L.userdata, L.userdata.count + 1) + } + L.userdata[handle].data = null + L.userdata[handle].tag = 0 + L.userdata[handle].meta = -1 + L.userdata[handle].env = -1 + L.userdata[handle].has_finalizer = false + L.userdata[handle].mark = 0 + L.userdata[handle].live = true + L.userdata[handle].finalized = false + L.allocated += 64 + return handle +} + +NewThreadObject :: (L: *LuaState) -> s32 { + handle := TakeSlot(*L.thread_free, 0) + if handle < 0 { + handle = cast(s32) L.threads.count + VecResize(L.threads, L.threads.count + 1) + } + L.threads[handle].env = L.globals + L.threads[handle].top = 0 + L.threads[handle].status = THREAD_SUSPENDED + L.threads[handle].mark = 0 + L.threads[handle].live = true + L.threads[handle].nesting = 0 + L.threads[handle].started = false + VecResize(L.threads[handle].stack, 64) + L.allocated += 64 * 16 + 160 + return handle +} + +// Make sure the running thread's stack has at least `at` slots. +EnsureStack :: (L: *LuaState, at: s64) -> bool #inline { + if at <= L.threads[L.cur].stack.count { return true } + return GrowStack(L, L.cur, at) +} + +GrowStack :: (L: *LuaState, thread: s32, at: s64) -> bool #cold { + size := L.threads[thread].stack.count * 2 + if size < 64 { size = 64 } + while size < at { size *= 2 } + if size > 8000000 { return false } + old := L.threads[thread].stack.count + L.allocated += (size - old) * 16 + return VecResize(L.threads[thread].stack, size) +} + +EnsureStackOf :: (L: *LuaState, thread: s32, at: s64) -> bool #inline { + if at <= L.threads[thread].stack.count { return true } + return GrowStack(L, thread, at) +} diff --git a/src/vm.zi b/src/vm.zi new file mode 100644 index 0000000..d948727 --- /dev/null +++ b/src/vm.zi @@ -0,0 +1,32 @@ +// A Lua 5.1 virtual machine in Ziran, following the LuaJIT dialect that +// Luanti mods use: lexer, parser, register compiler, interpreter, garbage +// collector, the standard libraries (base, coroutine, string, table, math, +// a sandboxed os/io subset, bit, debug) and an embedding API modeled on the +// C API. docs/API.md documents the embedding API. + +#import "vec" +#import "std/math" +#import "std/format" +#import "std/float_text" +#import "std/file" +#import "std/environment_linux" +#import "std/date_time_types" +#import "std/date_time_linux" +#import "std/timer_linux" + +#load "value.zi"; +#load "number.zi"; +#load "table.zi"; +#load "lexer.zi"; +#load "parser.zi"; +#load "compiler.zi"; +#load "interp.zi"; +#load "gc.zi"; +#load "api.zi"; +#load "lib_base.zi"; +#load "lib_string.zi"; +#load "lib_table.zi"; +#load "lib_math.zi"; +#load "lib_os.zi"; +#load "lib_bit.zi"; +#load "lib_debug.zi"; diff --git a/ziran.lock b/ziran.lock new file mode 100644 index 0000000..f33a85d --- /dev/null +++ b/ziran.lock @@ -0,0 +1,15 @@ +{ + "format": 1, + "packages": [ + + ], + "root": { + "dependencies": {}, + "name": "lua" + }, + "toolchain": { + "commit": "6dfa969c4764745cbfcbfbbf1153fb02cb9f1fa1", + "ref": "master", + "url": "https://github.com/ziranlang/ziran.git" + } +} diff --git a/ziran.toml b/ziran.toml new file mode 100644 index 0000000..55fe234 --- /dev/null +++ b/ziran.toml @@ -0,0 +1,10 @@ +[package] +name = "lua" +module_roots = ["src", "tests"] + +[toolchain] +git = "https://github.com/ziranlang/ziran.git" +ref = "master" + +[exports] +vm = "src/vm.zi"