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.
This commit is contained in:
commit
e3223e466d
20 files changed
+10536
No files matched your search
@@ -0,0 +1,3 @@
|
||||
build/
|
||||
backup/
|
||||
ziran.local.toml
|
||||
+1161
File diff suppressed because it is too large.
Load diff
+1397
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,433 @@
|
||||
// Stop-the-world mark and sweep. Collection only starts at interpreter safe
|
||||
// points (allocation-heavy instructions and native returns) or on request,
|
||||
// so natives may hold object handles in locals while they run, as long as
|
||||
// they do not call back into Lua. Weak tables (__mode) and userdata __gc
|
||||
// finalizers follow Lua 5.1: strings are never removed from weak tables and
|
||||
// a finalized userdata is freed by the following cycle.
|
||||
|
||||
#scope_module
|
||||
|
||||
// Gray-stack tag for prototypes.
|
||||
LUA_TPROTO :: 11;
|
||||
|
||||
MarkString :: (L: *LuaState, h: s32) #inline {
|
||||
if h >= 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
|
||||
}
|
||||
+1579
File diff suppressed because it is too large.
Load diff
+421
@@ -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(<<out, cast(u8) kind)
|
||||
return
|
||||
}
|
||||
if kind < 257 + RESERVED_COUNT {
|
||||
words := ReservedWords()
|
||||
BuilderAppend(<<out, words[kind - 257])
|
||||
return
|
||||
}
|
||||
if kind == TK_CONCAT { BuilderAppend(<<out, ".."); return }
|
||||
if kind == TK_DOTS { BuilderAppend(<<out, "..."); return }
|
||||
if kind == TK_EQ { BuilderAppend(<<out, "=="); return }
|
||||
if kind == TK_GE { BuilderAppend(<<out, ">="); return }
|
||||
if kind == TK_LE { BuilderAppend(<<out, "<="); return }
|
||||
if kind == TK_NE { BuilderAppend(<<out, "~="); return }
|
||||
if kind == TK_NUMBER { BuilderAppend(<<out, "<number>"); return }
|
||||
if kind == TK_NAME { BuilderAppend(<<out, "<name>"); return }
|
||||
if kind == TK_STRING { BuilderAppend(<<out, "<string>"); return }
|
||||
BuilderAppend(<<out, "<eof>")
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
+743
@@ -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(<<out, StrView(L, piece.h))
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
LoadResult :: (L: *LuaState, status: s32, env: LuaValue) -> 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(<<out, path)
|
||||
return true
|
||||
}
|
||||
BuilderAppend(<<out, root)
|
||||
if root.count > 0 && root[root.count - 1] != #char "/" { VecPush(<<out, #char "/") }
|
||||
BuilderAppend(<<out, path)
|
||||
return true
|
||||
}
|
||||
|
||||
LoadFileChunk :: (L: *LuaState, path: string) -> 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)) }
|
||||
}
|
||||
+146
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
+289
@@ -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
|
||||
}
|
||||
+595
@@ -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)
|
||||
<<ok = false
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
OsTime :: (L: *LuaState) -> 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(<<out, pad)
|
||||
VecPush(<<out, cast(u8)(#char "0" + value))
|
||||
return
|
||||
}
|
||||
Append(out, value)
|
||||
}
|
||||
|
||||
AppendDateField :: (out: *Vec(u8), conv: u8, when: LocalDateTime, utc: bool) -> bool {
|
||||
wday := WeekDay(when)
|
||||
if conv == #char "a" { BuilderAppend(<<out, DAY_NAMES[wday * 3:wday * 3 + 3]) }
|
||||
else if conv == #char "A" { BuilderAppend(<<out, DayFullName(wday)) }
|
||||
else if conv == #char "b" || conv == #char "h" {
|
||||
m := cast(s64)(when.month - 1)
|
||||
BuilderAppend(<<out, MONTH_NAMES[m * 3:m * 3 + 3])
|
||||
}
|
||||
else if conv == #char "B" { BuilderAppend(<<out, MonthFullName(cast(s64) when.month)) }
|
||||
else if conv == #char "c" {
|
||||
AppendDateField(out, #char "a", when, utc)
|
||||
VecPush(<<out, #char " ")
|
||||
AppendDateField(out, #char "b", when, utc)
|
||||
VecPush(<<out, #char " ")
|
||||
AppendTwo(out, cast(s64) when.day, #char " ")
|
||||
VecPush(<<out, #char " ")
|
||||
AppendDateField(out, #char "X", when, utc)
|
||||
VecPush(<<out, #char " ")
|
||||
Append(out, cast(s64) when.year)
|
||||
}
|
||||
else if conv == #char "d" { AppendTwo(out, cast(s64) when.day, #char "0") }
|
||||
else if conv == #char "e" { AppendTwo(out, cast(s64) when.day, #char " ") }
|
||||
else if conv == #char "D" || conv == #char "x" {
|
||||
AppendTwo(out, cast(s64) when.month, #char "0")
|
||||
VecPush(<<out, #char "/")
|
||||
AppendTwo(out, cast(s64) when.day, #char "0")
|
||||
VecPush(<<out, #char "/")
|
||||
AppendTwo(out, cast(s64)(when.year % 100), #char "0")
|
||||
}
|
||||
else if conv == #char "F" {
|
||||
Append(out, cast(s64) when.year)
|
||||
VecPush(<<out, #char "-")
|
||||
AppendTwo(out, cast(s64) when.month, #char "0")
|
||||
VecPush(<<out, #char "-")
|
||||
AppendTwo(out, cast(s64) when.day, #char "0")
|
||||
}
|
||||
else if conv == #char "H" { AppendTwo(out, cast(s64) when.hour, #char "0") }
|
||||
else if conv == #char "I" {
|
||||
h := cast(s64) when.hour % 12
|
||||
AppendTwo(out, ifx h == 0 then 12 else h, #char "0")
|
||||
}
|
||||
else if conv == #char "j" {
|
||||
yday := cast(s64) when.day_of_year + 1
|
||||
if yday < 100 { VecPush(<<out, #char "0") }
|
||||
if yday < 10 { VecPush(<<out, #char "0") }
|
||||
Append(out, yday)
|
||||
}
|
||||
else if conv == #char "m" { AppendTwo(out, cast(s64) when.month, #char "0") }
|
||||
else if conv == #char "M" { AppendTwo(out, cast(s64) when.minute, #char "0") }
|
||||
else if conv == #char "n" { VecPush(<<out, 10) }
|
||||
else if conv == #char "p" { BuilderAppend(<<out, ifx when.hour < 12 then "AM" else "PM") }
|
||||
else if conv == #char "S" { AppendTwo(out, cast(s64) when.second, #char "0") }
|
||||
else if conv == #char "t" { VecPush(<<out, 9) }
|
||||
else if conv == #char "T" || conv == #char "X" {
|
||||
AppendTwo(out, cast(s64) when.hour, #char "0")
|
||||
VecPush(<<out, #char ":")
|
||||
AppendTwo(out, cast(s64) when.minute, #char "0")
|
||||
VecPush(<<out, #char ":")
|
||||
AppendTwo(out, cast(s64) when.second, #char "0")
|
||||
}
|
||||
else if conv == #char "w" { Append(out, wday) }
|
||||
else if conv == #char "y" { AppendTwo(out, cast(s64)(when.year % 100), #char "0") }
|
||||
else if conv == #char "Y" { Append(out, cast(s64) when.year) }
|
||||
else if conv == #char "Z" { BuilderAppend(<<out, ifx utc then "UTC" else "") }
|
||||
else if conv == #char "%" { VecPush(<<out, #char "%") }
|
||||
else { return false }
|
||||
return true
|
||||
}
|
||||
|
||||
OsDate :: (L: *LuaState) -> 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 { <<out = StringValue(Intern(L, "")); return true }
|
||||
end := position + count
|
||||
if end > data.count { end = data.count }
|
||||
<<out = StringValue(Intern(L, data[position:end]))
|
||||
SetInt(L, state, FILE_POSITION, NumberValue(cast(float64) end))
|
||||
return true
|
||||
}
|
||||
spec := ifx format.t == LUA_TSTRING then StrView(L, format.h) else "*l"
|
||||
if spec.count > 0 && spec[0] == #char "*" { spec = spec[1:] }
|
||||
kind: u8 = ifx spec.count > 0 then spec[0] else #char "l"
|
||||
if kind == #char "a" {
|
||||
<<out = StringValue(Intern(L, data[position:]))
|
||||
SetInt(L, state, FILE_POSITION, NumberValue(cast(float64) data.count))
|
||||
return true
|
||||
}
|
||||
if kind == #char "n" {
|
||||
at := position
|
||||
while at < data.count && IsSpace(data[at]) { at += 1 }
|
||||
end := at
|
||||
while end < data.count && !IsSpace(data[end]) { end += 1 }
|
||||
value, ok := ParseNumberText(data[at:end])
|
||||
if !ok { return false }
|
||||
<<out = NumberValue(value)
|
||||
SetInt(L, state, FILE_POSITION, NumberValue(cast(float64) end))
|
||||
return true
|
||||
}
|
||||
if position >= 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 }
|
||||
<<out = StringValue(Intern(L, data[position:line_end]))
|
||||
next := ifx end < data.count then end + 1 else end
|
||||
SetInt(L, state, FILE_POSITION, NumberValue(cast(float64) next))
|
||||
return true
|
||||
}
|
||||
|
||||
ReadFormats :: (L: *LuaState, state: s32, first: s32) -> 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
|
||||
}
|
||||
}
|
||||
+1007
File diff suppressed because it is too large.
Load diff
@@ -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)
|
||||
}
|
||||
+460
@@ -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 := <<a
|
||||
BigShiftLeft(*doubled, 1)
|
||||
return BigCompare(*doubled, b)
|
||||
}
|
||||
|
||||
// Decimal digits of positive finite x. mode 0: `count` significant digits;
|
||||
// mode 1: digits through 10^-count (fixed). Writes digits (no leading
|
||||
// zeros except a lone "0") and returns the decimal exponent of the first
|
||||
// digit. Rounds half to even on the exact binary value.
|
||||
DecimalDigits :: (x: float64, mode: s32, count: s32, digits: *Vec(u8)) -> s32 {
|
||||
VecClear(<<digits)
|
||||
bits: NumberBits
|
||||
bits.f = x
|
||||
exponent_bits := cast(s32)((bits.u >> 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(<<digits, #char "1")
|
||||
return k + 1
|
||||
}
|
||||
}
|
||||
VecPush(<<digits, #char "0")
|
||||
return ifx mode == 1 then -count else k
|
||||
}
|
||||
if wanted > 800 { wanted = 800 }
|
||||
i: s32 = 0
|
||||
while i < wanted {
|
||||
digit: u8 = 0
|
||||
while BigCompare(*N, *D) >= 0 { BigSub(*N, *D); digit += 1 }
|
||||
VecPush(<<digits, #char "0" + digit)
|
||||
BigMulSmall(*N, 10)
|
||||
i += 1
|
||||
}
|
||||
// N now holds remainder * 10; compare remainder with D / 2.
|
||||
tenD := D
|
||||
BigMulSmall(*tenD, 5)
|
||||
cmp := BigCompare(*N, *tenD)
|
||||
round_up := cmp > 0 || (cmp == 0 && (((<<digits)[digits.count - 1] - #char "0") & 1) == 1)
|
||||
if round_up {
|
||||
j := digits.count - 1
|
||||
while j >= 0 {
|
||||
if (<<digits)[j] == #char "9" {
|
||||
(<<digits)[j] = #char "0"
|
||||
j -= 1
|
||||
} else {
|
||||
(<<digits)[j] += 1
|
||||
break
|
||||
}
|
||||
}
|
||||
if j < 0 {
|
||||
// 99..9 rounded to 100..0.
|
||||
VecPush(<<digits, #char "0")
|
||||
(<<digits)[0] = #char "1"
|
||||
k += 1
|
||||
if mode == 0 { VecResize(<<digits, digits.count - 1) }
|
||||
}
|
||||
}
|
||||
return k
|
||||
}
|
||||
|
||||
AppendExponent :: (out: *Vec(u8), exponent: s32, upper: bool) {
|
||||
VecPush(<<out, ifx upper then #char "E" else #char "e")
|
||||
e := exponent
|
||||
if e < 0 { VecPush(<<out, #char "-"); e = -e } else { VecPush(<<out, #char "+") }
|
||||
if e < 10 { VecPush(<<out, #char "0") }
|
||||
Append(out, cast(s64) e)
|
||||
}
|
||||
|
||||
// Append x formatted like C printf %<conv> 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(<<out, ifx upper then "NAN" else "nan")
|
||||
return
|
||||
}
|
||||
negative := x < 0.0 || IsNegativeZero(x)
|
||||
value := ifx negative then -x else x
|
||||
if negative { VecPush(<<out, #char "-") }
|
||||
else if plus { VecPush(<<out, #char "+") }
|
||||
else if space { VecPush(<<out, #char " ") }
|
||||
if value == Infinity() {
|
||||
BuilderAppend(<<out, ifx upper then "INF" else "inf")
|
||||
return
|
||||
}
|
||||
digits: Vec(u8)
|
||||
lower := conv | 32
|
||||
if lower == #char "f" {
|
||||
if value == 0.0 {
|
||||
VecPush(<<out, #char "0")
|
||||
if precision > 0 || alt { VecPush(<<out, #char ".") }
|
||||
i: s32 = 0
|
||||
while i < precision { VecPush(<<out, #char "0"); i += 1 }
|
||||
VecFree(digits)
|
||||
return
|
||||
}
|
||||
k := DecimalDigits(value, 1, precision, *digits)
|
||||
AppendFixed(out, *digits, k, precision, alt)
|
||||
VecFree(digits)
|
||||
return
|
||||
}
|
||||
if lower == #char "e" {
|
||||
if value == 0.0 {
|
||||
VecPush(<<out, #char "0")
|
||||
if precision > 0 || alt { VecPush(<<out, #char ".") }
|
||||
i: s32 = 0
|
||||
while i < precision { VecPush(<<out, #char "0"); i += 1 }
|
||||
AppendExponent(out, 0, upper)
|
||||
VecFree(digits)
|
||||
return
|
||||
}
|
||||
k := DecimalDigits(value, 0, precision + 1, *digits)
|
||||
VecPush(<<out, digits[0])
|
||||
if precision > 0 || alt { VecPush(<<out, #char ".") }
|
||||
i: s64 = 1
|
||||
while i < digits.count { VecPush(<<out, digits[i]); i += 1 }
|
||||
AppendExponent(out, k, upper)
|
||||
VecFree(digits)
|
||||
return
|
||||
}
|
||||
// %g
|
||||
p := precision
|
||||
if p == 0 { p = 1 }
|
||||
if value == 0.0 {
|
||||
VecPush(<<out, #char "0")
|
||||
if alt {
|
||||
VecPush(<<out, #char ".")
|
||||
i: s32 = 1
|
||||
while i < p { VecPush(<<out, #char "0"); i += 1 }
|
||||
}
|
||||
VecFree(digits)
|
||||
return
|
||||
}
|
||||
k := DecimalDigits(value, 0, p, *digits)
|
||||
if !alt {
|
||||
// Strip trailing zeros of the significand.
|
||||
while digits.count > 1 && digits[digits.count - 1] == #char "0" { VecResize(digits, digits.count - 1) }
|
||||
}
|
||||
if k < -4 || k >= p {
|
||||
VecPush(<<out, digits[0])
|
||||
if digits.count > 1 || alt { VecPush(<<out, #char ".") }
|
||||
i: s64 = 1
|
||||
while i < digits.count { VecPush(<<out, digits[i]); i += 1 }
|
||||
if alt {
|
||||
while i < p { VecPush(<<out, #char "0"); i += 1 }
|
||||
}
|
||||
AppendExponent(out, k, upper)
|
||||
} else {
|
||||
// Fixed notation with p - 1 - k decimals (trailing zeros removed).
|
||||
frac := cast(s32)(digits.count) - 1 - k
|
||||
if alt { frac = p - 1 - k }
|
||||
if frac < 0 { frac = 0 }
|
||||
AppendFixed(out, *digits, k, frac, alt)
|
||||
}
|
||||
VecFree(digits)
|
||||
}
|
||||
|
||||
// Write digits whose first digit has exponent k with `frac` decimals.
|
||||
AppendFixed :: (out: *Vec(u8), digits: *Vec(u8), k: s32, frac: s32, alt: bool) {
|
||||
// Integer part.
|
||||
if k < 0 {
|
||||
VecPush(<<out, #char "0")
|
||||
} else {
|
||||
i: s32 = 0
|
||||
while i <= k {
|
||||
VecPush(<<out, ifx i < digits.count then (<<digits)[i] else #char "0")
|
||||
i += 1
|
||||
}
|
||||
}
|
||||
if frac > 0 || alt { VecPush(<<out, #char ".") }
|
||||
j: s32 = 0
|
||||
while j < frac {
|
||||
position := k + 1 + j
|
||||
if position < 0 || position >= digits.count {
|
||||
VecPush(<<out, #char "0")
|
||||
} else {
|
||||
VecPush(<<out, (<<digits)[position])
|
||||
}
|
||||
j += 1
|
||||
}
|
||||
}
|
||||
|
||||
// Lua's tostring for numbers: "%.14g".
|
||||
AppendNumber :: (out: *Vec(u8), x: float64) {
|
||||
// %.14g switches to exponent form from 1e14 up.
|
||||
if x > -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)
|
||||
}
|
||||
+740
@@ -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
|
||||
}
|
||||
+300
@@ -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 }
|
||||
<<out_key = PositionKey(L, t, position)
|
||||
<<out_value = PositionValue(L, t, position)
|
||||
return true, true
|
||||
}
|
||||
|
||||
// Metamethod lookup on a metatable with the absent-bit cache.
|
||||
FastTM :: (L: *LuaState, mt: s32, event: s32) -> 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)
|
||||
}
|
||||
+618
@@ -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(*(<<bytes)[0], bytes.count)
|
||||
}
|
||||
|
||||
HashBytes :: (text: string) -> 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 := (<<free_list)[free_list.count - 1]
|
||||
VecResize(<<free_list, free_list.count - 1)
|
||||
return handle
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
NewTable :: (L: *LuaState, narr: s64, nhash: s64) -> 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)
|
||||
}
|
||||
@@ -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";
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"format": 1,
|
||||
"packages": [
|
||||
|
||||
],
|
||||
"root": {
|
||||
"dependencies": {},
|
||||
"name": "lua"
|
||||
},
|
||||
"toolchain": {
|
||||
"commit": "6dfa969c4764745cbfcbfbbf1153fb02cb9f1fa1",
|
||||
"ref": "master",
|
||||
"url": "https://github.com/ziranlang/ziran.git"
|
||||
}
|
||||
}
|
||||
+10
@@ -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"
|
||||
Reference in new issue
Block a user