diff --git a/Makefile b/Makefile index 4075414..a76ff88 100644 --- a/Makefile +++ b/Makefile @@ -1,10 +1,20 @@ ZIRAN ?= ziran LOCKED := $(if $(wildcard ziran.local.toml),,--locked) BUILD := $(ZIRAN) build --project $(LOCKED) --target=c --exe -o build/tests -RUN := env -u DISPLAY -u WAYLAND_DISPLAY +RUN := env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY -u DBUS_SESSION_BUS_ADDRESS -.PHONY: test unit conformance katalis -test: unit conformance katalis +# The wasm32 check: Ziran writes the C for the web platform, Emscripten from +# emsdk compiles it (zi2c's own link passes `-x none`, which emcc misreads), +# and a private headless Chromium runs it (fresh profile under build/, no +# display). Chromium's socket path must stay short, so its TMPDIR is build/t. +EMCC ?= $(HOME)/emsdk/upstream/emscripten/emcc +CHROMIUM ?= chromium +# Compiler runs outside ziran go through the shared build queue when present. +QUEUE := $(if $(shell command -v build-queue),build-queue --,) +WASM_LDFLAGS := -sSINGLE_FILE=1 -sWASM_ASYNC_COMPILATION=0 -sALLOW_MEMORY_GROWTH=1 -sENVIRONMENT=web -sSTACK_SIZE=1048576 + +.PHONY: test unit conformance katalis wasm +test: unit conformance katalis wasm unit: $(BUILD) --entry vm_test:Main tests/vm_test.zi @@ -17,3 +27,21 @@ conformance: katalis: $(BUILD) --entry katalis_mods_test:Main tests/katalis_mods_test.zi $(RUN) build/tests/katalis_mods_test + +wasm: + @if ! test -x "$(EMCC)" || ! command -v "$(CHROMIUM)" >/dev/null; then \ + echo "SKIP wasm32: needs EMCC ($(EMCC)) and CHROMIUM ($(CHROMIUM))"; exit 0; fi; \ + set -e; \ + rm -rf build/wasm build/t; mkdir -p build/wasm build/t; \ + env CFLAGS=-O0 $(ZIRAN) build --project $(LOCKED) --target=c --define PLATFORM_WEB --exe -o build/wasm --entry wasm_test:Main tests/wasm_test.zi; \ + $(ZIRAN) compile-commands --project -o build/wasm/commands.json build/wasm; \ + include=$$(sed -n 's/^ *"-I\(.*\)",*$$/\1/p' build/wasm/commands.json | grep -v '/build/wasm$$' | head -1); \ + $(QUEUE) "$(EMCC)" -std=c99 -O2 -w -I build/wasm -I "$$include" build/wasm/*.c -lm $(WASM_LDFLAGS) -o build/wasm/wasm_test.js; \ + cp tests/wasm_page.html build/wasm/index.html; \ + $(RUN) TMPDIR="$(CURDIR)/build/t" timeout 120 "$(CHROMIUM)" --headless --no-first-run \ + --no-default-browser-check --disable-extensions --use-gl=disabled --disable-gpu \ + --user-data-dir="$(CURDIR)/build/t/profile" \ + --dump-dom "file://$(CURDIR)/build/wasm/index.html" > build/wasm/page.txt 2> build/wasm/chromium.log || true; \ + rm -rf build/t; \ + if grep -q 'wasm32 strings ok' build/wasm/page.txt; then echo "wasm32 strings ok"; \ + else echo "FAIL wasm32:"; cat build/wasm/page.txt; tail -5 build/wasm/chromium.log; exit 1; fi diff --git a/README.md b/README.md index cae3946..376bf1a 100644 --- a/README.md +++ b/README.md @@ -59,4 +59,6 @@ make test This runs the API unit tests, the Lua scripts in `tests/lua`, and loads every `.lua` file of the Katalis mods (set `KATALIS_MODS` to another -folder; it is skipped when missing). +folder; it is skipped when missing). `make wasm` (part of `make test`) builds +the VM for wasm32 with Emscripten and runs it in a private headless Chromium; +set `EMCC` and `CHROMIUM` if they are elsewhere (it is skipped without them). diff --git a/docs/API.md b/docs/API.md index 9c7005e..c3a565c 100644 --- a/docs/API.md +++ b/docs/API.md @@ -3,9 +3,9 @@ `#import "lua/vm"` gives a Lua 5.1 virtual machine (LuaJIT dialect) written in Ziran. The API follows the shape of the Lua C API: a host owns a `LuaState` record, values move through a stack, and natives are plain Ziran -procedures. Names below are stable; records not listed here (`LuaTable`, -`LuaClosure` and the other object records exported with `LuaState`) are -internal and may change. +procedures. Names below are stable. Use `LuaState` only through them: its +fields are internal, and the object records they hold are private to the +package. ## State diff --git a/src/parser.zi b/src/parser.zi index 71e6340..22721bd 100644 --- a/src/parser.zi +++ b/src/parser.zi @@ -63,9 +63,6 @@ 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 @@ -79,7 +76,6 @@ LuaSyntaxNode :: struct { num: float64 str: s32 } -#scope_module Parser :: struct { lx: Lexer diff --git a/src/value.zi b/src/value.zi index aa60378..ebaf9b0 100644 --- a/src/value.zi +++ b/src/value.zi @@ -94,9 +94,7 @@ RawEqual :: (a: LuaValue, b: LuaValue) -> bool #inline { 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 +// The object records live in the state's arenas. LuaString :: struct { bytes: Vec(u8) @@ -242,8 +240,6 @@ LuaThread :: struct { env: s32 } -#scope_module - // Metamethod indices. TM_INDEX :: 0; TM_NEWINDEX :: 1; @@ -358,19 +354,12 @@ LuaState :: struct { #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; } - +// the bytes never move while the string lives. std's BytesFromPointer +// borrows them with the target's own slice layout (size_t lengths on +// wasm32 too). 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 + if count <= 0 { return "" } + return TextView(BytesFromPointer(first, cast(u64) count)) } StrView :: (L: *LuaState, h: s32) -> string #inline { diff --git a/src/vm.zi b/src/vm.zi index d948727..d6b235f 100644 --- a/src/vm.zi +++ b/src/vm.zi @@ -10,6 +10,7 @@ #import "std/float_text" #import "std/file" #import "std/environment_linux" +#import "std/byte_text_linux" #import "std/date_time_types" #import "std/date_time_linux" #import "std/timer_linux" diff --git a/tests/wasm_page.html b/tests/wasm_page.html new file mode 100644 index 0000000..6feff53 --- /dev/null +++ b/tests/wasm_page.html @@ -0,0 +1,17 @@ + + +lua wasm32 test +

+
+
diff --git a/tests/wasm_test.zi b/tests/wasm_test.zi
new file mode 100644
index 0000000..2ac815e
--- /dev/null
+++ b/tests/wasm_test.zi
@@ -0,0 +1,73 @@
+// Runs the VM on wasm32 (Emscripten, in a headless browser; see `make
+// wasm`): strings, numbers and error messages must survive the VM's string
+// views, whose length is size_t there.
+#import "vec"
+#import "vm"
+
+state: LuaState;
+failures: s64 = 0;
+
+Contains :: (text: string, part: string) -> bool {
+    i: s64 = 0
+    while i + part.count <= text.count {
+        j: s64 = 0
+        while j < part.count && text[i + j] == part[j] { j += 1 }
+        if j == part.count { return true }
+        i += 1
+    }
+    return false
+}
+
+ExpectString :: (L: *LuaState, source: string, expected: string) {
+    status := LuaDoString(L, source, "=wasm")
+    text, ok := LuaToString(L, -1)
+    if status != LUA_OK || !ok || text != expected {
+        print("FAIL % -> status % '%' (expected '%')\n", source, status, text, expected)
+        failures += 1
+    }
+    LuaSetTop(L, 0)
+}
+
+ExpectNumber :: (L: *LuaState, source: string, expected: float64) {
+    status := LuaDoString(L, source, "=wasm")
+    if status != LUA_OK || LuaType(L, -1) != LUA_TYPE_NUMBER || LuaToNumber(L, -1) != expected {
+        text, ok := LuaToString(L, -1)
+        print("FAIL % -> status % '%'\n", source, status, text)
+        failures += 1
+    }
+    LuaSetTop(L, 0)
+}
+
+ExpectError :: (L: *LuaState, source: string, part: string) {
+    status := LuaDoString(L, source, "=wasm")
+    text, ok := LuaToString(L, -1)
+    if status == LUA_OK || !Contains(text, part) {
+        print("FAIL % -> status % '%' (expected an error with '%')\n", source, status, text, part)
+        failures += 1
+    }
+    LuaSetTop(L, 0)
+}
+
+Main :: () -> s32 {
+    L := *state
+    LuaOpen(L)
+    ExpectString(L, "return 'abc'", "abc")
+    ExpectNumber(L, "return 1 + 2", 3.0)
+    ExpectString(L, "return tostring(12)", "12")
+    ExpectString(L, "return ('x'):rep(3, ',') .. #'hello'", "x,x,x5")
+    ExpectString(L, "local t = {} for w in ('a b c'):gmatch('%a') do t[#t + 1] = w:upper() end return table.concat(t)", "ABC")
+    ExpectString(L, "return string.format('%5.2f|%d|%s|%x', 3.14159, 42, 'ok', 255)", " 3.14|42|ok|ff")
+    ExpectString(L, "local t = setmetatable({}, {__index = function(_, k) return k .. '!' end}) return t.hey", "hey!")
+    ExpectNumber(L, "return bit.band(0xff00, 0x0ff0) + tonumber('0x10')", 3856.0)
+    ExpectNumber(L, "local co = coroutine.wrap(function(a) local b = coroutine.yield(a + 1) return b * 2 end) co(1) return co(21)", 42.0)
+    ExpectError(L, "error('xyz')", "wasm:1: xyz")
+    ExpectError(L, "local t = nil; return t.x", "attempt to index local 't' (a nil value)")
+    ExpectError(L, "return +", "wasm:1:")
+    LuaClose(L)
+    if failures > 0 {
+        print("wasm32: % failed\n", failures)
+        return 1
+    }
+    print("wasm32 strings ok\n")
+    return 0
+}
diff --git a/ziran.lock b/ziran.lock
index f33a85d..d4759bd 100644
--- a/ziran.lock
+++ b/ziran.lock
@@ -8,7 +8,7 @@
     "name": "lua"
   },
   "toolchain": {
-    "commit": "6dfa969c4764745cbfcbfbbf1153fb02cb9f1fa1",
+    "commit": "88b505bf5f2342d46ed857c2d9160d5da9bec3a2",
     "ref": "master",
     "url": "https://github.com/ziranlang/ziran.git"
   }