From 474bd085da8afbc4f83efe43d707e1f8d9df7071 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 02:30:34 -0800 Subject: [PATCH 1/3] chore(quest): claim quest/m2/wasm/ts-consumers.md Quest-Claim: 174d31b602ca5a86 From db1394573435291f47d30325a93fa479de625a2d Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 03:45:58 -0800 Subject: [PATCH 2/3] Define Symbol.dispose where the engine lacks it, and check WebKit and noImplicitOverride Both runtimes define Symbol.dispose as Symbol.for("Symbol.dispose") when the engine lacks it, so a consumer's using runs the Rust drop on stable Safari. just ffi browsers runs the web binding's test in WebKit too, with using native and lowered by tsc and esbuild. rust2-ts's output and runtime type-check under noImplicitOverride. Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/nightly.yml | 2 +- ffi/README.md | 4 +- ffi/justfile | 2 +- ffi/runtime/rt.ts | 5 +++ ffi/tests/api.ts | 11 ++++- ffi/tests/browser.ts | 69 +++++++++++++++++++++++++++----- ffi/tests/dispose.ts | 39 ++++++++++++++++++ ffi/tests/fixtures.rs | 37 ++++++++++++----- flake.nix | 33 +++++++++++---- quest/m2/wasm/ts-consumers.md | 29 -------------- ts/README.md | 4 +- ts/fixtures/lang/drops/caller.ts | 14 +++++++ ts/runtime/rs.ts | 1 + ts/runtime/rs/dispose.ts | 4 ++ ts/runtime/rs/tokio.ts | 2 +- ts/runtime/tsconfig.json | 1 + ts/src/check.rs | 1 + ts/src/program.rs | 1 + ts/tests/dispose.ts | 39 ++++++++++++++++++ ts/tests/runtime.rs | 13 ++++++ 20 files changed, 248 insertions(+), 63 deletions(-) create mode 100644 ffi/tests/dispose.ts delete mode 100644 quest/m2/wasm/ts-consumers.md create mode 100644 ts/runtime/rs/dispose.ts create mode 100644 ts/tests/dispose.ts diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index f28208923..573c0bf89 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -211,7 +211,7 @@ jobs: - name: Clang run: nix develop .#clang --command bash -c 'export CC=gcc; just ffi test cpp && just ffi moq-cpp' - # The api fixture's web test in headless Chromium and Firefox, which only the bench shell + # The api fixture's web test in headless Chromium, Firefox, and WebKit, which only the bench shell # carries: a job of its own, so a browser's failure hides no other result. ffi-web: name: Web binding in browsers diff --git a/ffi/README.md b/ffi/README.md index fa002c4d9..773350153 100644 --- a/ffi/README.md +++ b/ffi/README.md @@ -1391,7 +1391,7 @@ target there. payload costs 0.4 µs a call at any length, against a copy's 0.5 µs at 100 B, 1.1 µs at 1 KiB, and 97 µs at 1 MiB; [the benchmark](../bench/ffi/README.md#lending-returned-bytes) has each engine's. -- **Objects** are an `rt.Handle`, disposed by `[Symbol.dispose]`, as `using` does. Of a +- **Objects** are an `rt.Handle`, disposed by `[Symbol.dispose]`, as `using` does; where the engine lacks that symbol, as stable Safari does, `rt` defines it as `Symbol.for("Symbol.dispose")`, which esbuild's `using` falls back to too. Of a checked type, disposing it drops the value through Rust's own `_drop`, which fails while a call borrows it; of any other, it throws while a call holds it. The handle is freed once disposed and no call holds it, so one disposed while a later argument lowers fails the @@ -1425,7 +1425,7 @@ just ffi moq-swift # the same export, running only moq/moq.swift just ffi moq-api # stage moq's API on another target into target/moq-api, which the exports above merge just ffi census # census each into target/census just ffi shapes # round-trip every sampled type shape in every language but KNOWN's, as the nightly does -nix develop .#bench --command just ffi browsers # api's TypeScript in headless Chromium and Firefox, as the nightly runs it +nix develop .#bench --command just ffi browsers # api's TypeScript in headless Chromium, Firefox, and WebKit, lowering `using` three ways for WebKit, as the nightly runs it nix develop .#android --command just ffi android # the Kotlin test, shrunk by R8, on the Android device adb reaches nix develop .#bench --command just ffi bench # the binding benchmark: bench/ffi/README.md's cases from Rust, and through the export from C, C++, Kotlin, Python, Swift, Go, and Dart nix develop .#bench --command just ffi codspeed # after bench-build, each single-threaded case once under CodSpeed's CPU simulation, as the CodSpeed workflow runs it diff --git a/ffi/justfile b/ffi/justfile index 4d1712aca..644294351 100644 --- a/ffi/justfile +++ b/ffi/justfile @@ -41,7 +41,7 @@ test *args: shapes: cargo test --locked --test fixtures shapes::nightly -- --ignored -# Run the api fixture's web test in headless Chromium and Firefox, in the bench shell, which carries them: nix develop .#bench. +# Run the api fixture's web test in headless Chromium, Firefox, and WebKit, in the bench shell, which carries them: nix develop .#bench. browsers: cargo test --locked --test fixtures -- --ignored --exact api_browsers diff --git a/ffi/runtime/rt.ts b/ffi/runtime/rt.ts index 46b88da98..9492560ad 100644 --- a/ffi/runtime/rt.ts +++ b/ffi/runtime/rt.ts @@ -3,6 +3,11 @@ // past 32 bits, futures as promises, what JavaScript implements for Rust, and the web APIs // that stand in for what the module's std imports. +// `Symbol.dispose` where the engine lacks it, as stable Safari does: the registry's symbol, +// which esbuild's `using` helper falls back to too, though TypeScript's throws without one. +// It runs before any class below keys a method on it. +if (!Symbol.dispose) Object.defineProperty(Symbol, "dispose", { value: Symbol.for("Symbol.dispose") }); + declare const brand: unique symbol; /** A `u64` past 2^53: its high and low 32 bits, each a uint32. */ diff --git a/ffi/tests/api.ts b/ffi/tests/api.ts index 9d0b4d8ec..c9466fd6e 100644 --- a/ffi/tests/api.ts +++ b/ffi/tests/api.ts @@ -1348,11 +1348,18 @@ async function owned(): Promise { close(token); check(api.dropped() === before + 1, "disposing again frees nothing"); closed(() => Token.idGet(token), "Token", "a disposed token refuses a read"); + // `using` disposes at the end of its scope, as stable Safari, which lacks `Symbol.dispose`, + // needs the runtime's own symbol for, however the bundler lowers it. + { + using scoped = Token.new(2); + check(api.dropped() === before + 1 && Token.idGet(scoped) === 2, "a `using` object is open in its scope"); + } + check(api.dropped() === before + 2, "a `using` object frees at the end of its scope"); unclosed(); - await collect(() => api.dropped() >= before + 2, "the garbage collector frees what nobody disposed"); + await collect(() => api.dropped() >= before + 3, "the garbage collector frees what nobody disposed"); await settle(); - check(api.dropped() === before + 2, "the garbage collector frees each once"); + check(api.dropped() === before + 3, "the garbage collector frees each once"); // An implementation an object the garbage collector frees held is closed. const log = new CountLog(); diff --git a/ffi/tests/browser.ts b/ffi/tests/browser.ts index 22bf61c4f..08fa36d32 100644 --- a/ffi/tests/browser.ts +++ b/ffi/tests/browser.ts @@ -1,26 +1,73 @@ -// Runs tests/api.ts's cases in one headless browser, Chromium or Firefox, as Node runs -// them: Bun bundles the script and its binding for the page, and each case runs in a +// Runs tests/api.ts's cases in one headless browser, Chromium, Firefox, or WebKit, as Node +// runs them: the script and its binding are bundled for the page, and each case runs in a // frame of its own, a fresh realm, against a `process` that serves the module's bytes, the // case, and the garbage collector where the browser exposes it. Each case posts whether it // finished and what it printed, which this prints as a line of JSON. // -// usage: bun browser.ts ... +// How `using` in the script reaches the page is the bundle's: `bun` is Bun's bundler, which +// lowers it; `native` leaves it to the engine; `esbuild` and `tsc` lower it as a consumer's +// build would, to the helper that falls back to `Symbol.for("Symbol.dispose")` and to the one +// that throws without `Symbol.dispose`, which stable Safari lacks. +// +// usage: bun browser.ts ... // where a case is `-` for the transcript. import { mkdir, rm } from "node:fs/promises"; import { join, resolve } from "node:path"; -const [browser, dirArg, wasmPath, outArg, ...cases] = process.argv.slice(2); -if (!browser || !dirArg || !wasmPath || !outArg || cases.length === 0) { - throw new Error("usage: browser.ts ..."); +const [browser, lowering, dirArg, wasmPath, outArg, ...cases] = process.argv.slice(2); +if (!browser || !lowering || !dirArg || !wasmPath || !outArg || cases.length === 0) { + throw new Error("usage: browser.ts ..."); } const out = resolve(outArg); await rm(out, { recursive: true, force: true }); await mkdir(out, { recursive: true }); -const bundled = await Bun.build({ entrypoints: [join(dirArg, "api.ts")], target: "browser", format: "esm" }); -if (!bundled.success) throw new AggregateError(bundled.logs, "bundling api.ts failed"); -await Bun.write(join(out, "api.js"), bundled.outputs[0]!); +/** Runs a build tool, failing with its output. */ +async function build(...command: string[]): Promise { + const tool = Bun.spawn(command, { stdout: "pipe", stderr: "pipe" }); + const [stdout, stderr, code] = await Promise.all([tool.stdout.text(), tool.stderr.text(), tool.exited]); + if (code !== 0) throw new Error(`${command.join(" ")} exited with ${code}:\n${stdout}${stderr}`); +} + +const entry = join(dirArg, "api.ts"); +const bundle = join(out, "api.js"); +switch (lowering) { + case "bun": { + const bundled = await Bun.build({ entrypoints: [entry], target: "browser", format: "esm" }); + if (!bundled.success) throw new AggregateError(bundled.logs, "bundling api.ts failed"); + await Bun.write(bundle, bundled.outputs[0]!); + break; + } + case "native": + await build("esbuild", entry, "--bundle", "--format=esm", "--target=esnext", `--outfile=${bundle}`); + break; + case "esbuild": + await build("esbuild", entry, "--bundle", "--format=esm", "--target=es2022", `--outfile=${bundle}`); + break; + case "tsc": { + // The script's own `tsc` emit, lowered to ES2022 as a project's build would, then bundled. + const emitted = join(out, "tsc"); + await build( + "tsc", + "-p", + dirArg, + "--noEmit", + "false", + "--outDir", + emitted, + "--target", + "es2022", + "--rewriteRelativeImportExtensions", + "--allowImportingTsExtensions", + "false", + ); + await build("esbuild", join(emitted, "api.js"), "--bundle", "--format=esm", "--target=esnext", `--outfile=${bundle}`); + break; + } + default: + throw new Error(`no lowering ${lowering}`); +} // The frame of one case: a `process` as api.ts reads Node's, then the script. What it // printed, and whether it finished, go back once it settles; an exit or a throw ends it. @@ -133,6 +180,10 @@ const command = (() => { ]; case "firefox": return ["firefox", "--headless", "--no-remote", "--profile", profile, server.url.href]; + // The `webkit-headless` the bench shell carries: Playwright's WPE build, which exposes + // no garbage collector, as Firefox does not. + case "webkit": + return ["webkit-headless", server.url.href]; default: throw new Error(`no browser ${browser}`); } diff --git a/ffi/tests/dispose.ts b/ffi/tests/dispose.ts new file mode 100644 index 000000000..303e990af --- /dev/null +++ b/ffi/tests/dispose.ts @@ -0,0 +1,39 @@ +// An engine without `Symbol.dispose`, as stable Safari is: the runtime, bundled and run in a +// context whose `Symbol` lacks it, defines it as the registry's `Symbol.for("Symbol.dispose")`, +// which esbuild's `using` helper falls back to, before any class keys a method on it. +// +// usage: node dispose.ts + +import { execFileSync } from "node:child_process"; +import vm from "node:vm"; + +const entry = process.argv[2]; +if (!entry) throw new Error("usage: dispose.ts "); +const code = execFileSync("esbuild", [entry, "--bundle", "--format=iife", "--global-name=runtime", "--target=es2022"], { + encoding: "utf8", +}); + +// The built-in `Symbol`, but for `dispose` and `asyncDispose`, which cannot be deleted from it. +const FakeSymbol = Object.defineProperties( + (description?: string) => Symbol(description), + Object.fromEntries(Reflect.ownKeys(Symbol).filter((key) => key !== "dispose" && key !== "asyncDispose").map((key) => [key, Object.getOwnPropertyDescriptor(Symbol, key)!])), +); + +// What a browser gives the runtime that a bare context lacks. +const { TextEncoder, TextDecoder, URL, console, queueMicrotask, setTimeout, clearTimeout, performance } = globalThis; +const context = vm.createContext({ Symbol: FakeSymbol, TextEncoder, TextDecoder, URL, console, queueMicrotask, setTimeout, clearTimeout, performance }); +if (vm.runInContext("typeof Symbol.dispose", context) !== "undefined") throw new Error("the context's Symbol still has dispose"); +vm.runInContext(`${code}\nglobalThis.runtime = runtime;`, context); + +const registry = Symbol.for("Symbol.dispose"); +const defined = vm.runInContext("Symbol.dispose", context); +if (defined !== registry) throw new Error(`Symbol.dispose is ${String(defined)}, not the registry's`); + +// Each class that disposes does so under that symbol, and none under the string "undefined". +let disposing = 0; +for (const [name, value] of Object.entries(vm.runInContext("runtime", context) as Record)) { + if (typeof value !== "function" || !value.prototype) continue; + if (Object.hasOwn(value.prototype, "undefined")) throw new Error(`${name} keys a method on "undefined"`); + if (Object.getOwnPropertySymbols(value.prototype).includes(registry)) disposing++; +} +if (disposing === 0) throw new Error("no exported class disposes under the registry's symbol"); diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index bbb48737d..a166bbf4c 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -1495,30 +1495,48 @@ fn api_web() { ); } -/// `api_web`'s checks in headless Chromium and Firefox, which only the bench shell carries: -/// `tests/browser.ts` bundles the script with Bun and runs each case in a frame of its own. -/// Firefox exposes no garbage collector to a page, so it runs neither `owned` nor `bytes`. +/// Where the engine lacks `Symbol.dispose`, as stable Safari does, the web runtime defines it +/// as the registry's symbol before its classes key a method on it, which `dispose.ts` checks. +#[test] +fn web_without_dispose() { + run(Command::new("node") + .arg(manifest_dir().join("tests").join("dispose.ts")) + .arg(manifest_dir().join("runtime").join("rt.ts"))); +} + +/// `api_web`'s checks in headless Chromium, Firefox, and WebKit, which only the bench shell +/// carries: `tests/browser.ts` bundles the script and runs each case in a frame of its own. +/// Firefox and WebKit expose no garbage collector to a page, so they run neither `owned` nor +/// `bytes`. The script's `using` runs in WebKit as the engine has it, and lowered as `tsc` and +/// esbuild lower it, each of which keys on `Symbol.dispose`. Playwright's WebKit has the symbol, +/// which stable Safari lacks: `web_without_dispose` covers its absence. #[test] #[ignore = "the nightly's, in the bench shell: just ffi browsers"] fn api_browsers() { let web = web(); - for browser in ["chromium", "firefox"] { + for (browser, lowering) in [ + ("chromium", "bun"), + ("firefox", "bun"), + ("webkit", "native"), + ("webkit", "esbuild"), + ("webkit", "tsc"), + ] { let cases: Vec<&str> = match browser { - "firefox" => WEB_CASES + "chromium" => WEB_CASES.to_vec(), + _ => WEB_CASES .into_iter() .filter(|c| !matches!(*c, "owned" | "bytes")) .collect(), - _ => WEB_CASES.to_vec(), }; let all = std::iter::once("-") .chain(cases.iter().copied()) .chain(WEB_BROKEN.iter().map(|(case, _)| *case)); let output = run(Command::new("bun") .arg(manifest_dir().join("tests").join("browser.ts")) - .arg(browser) + .args([browser, lowering]) .arg(&web.dir) .arg(&web.wasm) - .arg(scratch().join("api").join(browser)) + .arg(scratch().join("api").join(format!("{browser}-{lowering}"))) .args(all)); let mut runs: std::collections::HashMap = String::from_utf8_lossy(&output.stdout) .lines() @@ -1533,7 +1551,7 @@ fn api_browsers() { (text("case"), ran) }) .collect(); - web_checks(browser, &cases, &mut |case| { + web_checks(&format!("{browser} ({lowering})"), &cases, &mut |case| { let case = case.unwrap_or("-"); runs.remove(case).unwrap_or_else(|| panic!("{browser} ran no {case}")) }); @@ -1547,6 +1565,7 @@ const TSCONFIG: &str = r#"{ "strict": true, "noEmit": true, "pretty": false, + "noImplicitOverride": true, "noUnusedLocals": true, "noUnusedParameters": true, "target": "es2024", diff --git a/flake.nix b/flake.nix index 041d46d98..9280fc427 100644 --- a/flake.nix +++ b/flake.nix @@ -57,6 +57,21 @@ overlays = [ (import rust-overlay) ]; }; toolchain = pkgs.rust-bin.fromRustupToolchainFile ./rust-toolchain.toml; + # Playwright's WPE build of WebKit, headless over Mesa's software EGL, so a host + # with no GPU or display runs it: `webkit-headless `. Its tip-of-tree engine + # stands in for Safari, which has no Linux build. + webkit-headless = + let + browsers = pkgs.playwright-driver.browsers; + webkit = pkgs.lib.findFirst ( + name: pkgs.lib.hasPrefix "webkit-" name + ) (throw "playwright-driver ships no WebKit") (builtins.attrNames browsers.passthru.entries); + in + pkgs.writeShellScriptBin "webkit-headless" '' + export LIBGL_ALWAYS_SOFTWARE=1 + export __EGL_VENDOR_LIBRARY_DIRS=${pkgs.mesa}/share/glvnd/egl_vendor.d + exec ${browsers.passthru.entries.${webkit}}/minibrowser-wpe/MiniBrowser --headless "$@" + ''; # The benchmark's nightly levers (--jobs-frontend, cranelift, self-profile). # Bumping the date is a benchmark corpus change: numbers before and # after it do not compare. @@ -299,14 +314,18 @@ ''; }; # `just ts bench` adds Chrome and Firefox as engines, and `just ffi browsers` runs the - # web binding's test in them. Apart for their size. Binaryen's wasm2js lowers the - # bench's wasm32 build to JavaScript for its wasm2js route. + # web binding's test in them, and in WebKit, which stands in for Safari. Apart for + # their size. Binaryen's wasm2js lowers the bench's wasm32 build to JavaScript for its + # wasm2js route. devShells.bench = self.devShells.${system}.default.overrideAttrs (old: { - nativeBuildInputs = old.nativeBuildInputs ++ [ - pkgs.chromium - pkgs.firefox - pkgs.binaryen - ]; + nativeBuildInputs = + old.nativeBuildInputs + ++ [ + pkgs.chromium + pkgs.firefox + pkgs.binaryen + ] + ++ pkgs.lib.optional pkgs.stdenv.hostPlatform.isLinux webkit-headless; # `just ffi bench` builds moq's rs/moq-c, whose VAAPI bindings run bindgen. LIBCLANG_PATH = "${pkgs.llvmPackages.libclang.lib}/lib"; # ... and its programs over instrument-hooks, for CodSpeed. diff --git a/quest/m2/wasm/ts-consumers.md b/quest/m2/wasm/ts-consumers.md deleted file mode 100644 index 33478a305..000000000 --- a/quest/m2/wasm/ts-consumers.md +++ /dev/null @@ -1,29 +0,0 @@ -# [S] Both TypeScript routes work in Safari and strict projects - -## Goal - -- Both runtimes, rust2-ffi's web `rt.ts` and rust2-ts's, define `Symbol.dispose` as - `Symbol.for("Symbol.dispose")` when the engine lacks it, at module evaluation before any - consumer code runs, and key disposal on it. So a consumer's `using` runs the Rust drop on - stable Safari, which lacks `Symbol.dispose`, whether native or downleveled: TypeScript's - `__addDisposableResource` throws when `Symbol.dispose` is absent rather than falling back, - while esbuild's helper falls back to `Symbol.for("Symbol.dispose")`, so a key fallback - alone would not do. `ffi/tests/api.ts` and a translated fixture's caller use `using`, and - the WebKit run below covers it native, downleveled by `tsc`, and downleveled by esbuild. -- `just ffi browsers` runs the web binding's test in WebKit too (Playwright's WebKit or - WPE `cog` from nixpkgs), nightly beside Chromium and Firefox. -- rust2-ts's output type-checks under `noImplicitOverride` (`ts/src/check.rs:23`), which - moq's tsconfig sets and the runtime fails today at `ts/runtime/rs/tokio.ts:580`. - -## Plan - -Found by the 2026-11-18 language audit: stable Safari still leaves `Symbol.dispose` -undefined (only [Technology Preview 250](https://webkit.org/blog/18191/release-notes-for-safari-technology-preview-250/) -enables it, [logtape#255](https://github.com/dahlia/logtape/issues/255)), so methods keyed -on it land under the string `"undefined"` (`ffi/runtime/rt.ts:164`, `:383`, `:818`, -`:1085`). Bun stands in for JavaScriptCore in the benchmark and ships the symbol, which hid -it. Safari, iOS's every browser included, is a browser moq's route must reach. - -A child of this epic since both routes share the API and the gate reads both. - -Public API: none; disposal works where it silently did not. diff --git a/ts/README.md b/ts/README.md index 0922d0fda..b98a88ab0 100644 --- a/ts/README.md +++ b/ts/README.md @@ -134,7 +134,7 @@ crate translation reaches is refused, and so are two versions of one crate it re | `dyn Iterator`, `dyn DoubleEndedIterator`, `dyn ExactSizeIterator`, `dyn FusedIterator` | `rs.Iter`: `rs.iterDyn` of the iterator it was made of | | constant | its value, inlined as Rust inlines it, so each use of one holding a cell is a cell of its own; one with no value tree, or holding a cell, read from the memory rustc evaluated | | `static` | a module's value, named for the static, that every use shares, read from the memory rustc evaluated; one that reads another static or a class is an `rs.LazyCell` of it, made on first use, since that may not be made yet when its module is. A `static mut`, and a pointer in one into memory the translation can't name, fail translation | -| a type that drops | a class with `[Symbol.dispose]`: its `Drop` impl, then its fields | +| a type that drops | a class with `[Symbol.dispose]`: its `Drop` impl, then its fields; where the engine lacks that symbol, as stable Safari does, the runtime defines it as `Symbol.for("Symbol.dispose")` before any class keys a method on it, so a consumer's `using` runs the drop, native or lowered by `tsc` or esbuild | | a type's function | a function of the type's module, taking `self` first: `Decoder.slice(dec, 4)` after `import * as Decoder` | | `Arc`, `Rc`, `Weak`, `Mutex` | `rs.Arc` for either, of what a `Box` is for a slice or `str`, with its strong and weak counts, an `Arc<[T; N]>` unsized to an `Arc<[T]>` an `rs.ArcDyn` of the slice of its array, sharing its count, an `Arc<[u8]>` of an `Arc`'s bytes sharing its count, and `new_cyclic`'s `Weak` upgrading only once its value is made, `get_mut` lending its value only while no other `Arc` or `Weak` shares it, `make_mut` cloning it into a new `rs.Arc` while another `Arc` shares it, or moving it there while only `Weak`s do, which then dangle, as a copy where pointers to it compare, `as_ptr` and `into_raw` pointing where a reference to its value does, or at its place where JS copies it, as a pointer the body shows made from a reference to that value does, which `from_raw`, `increment_strong_count`, and `decrement_strong_count` take back to its `rs.Arc` and count, refused for one the body shows a borrow made, and aborting, as std's debug checks of unsafe preconditions do, on another pointer no `as_ptr` or `into_raw` of that type of `Arc` gave, or one whose value dropped, which Rust leaves undefined, and refused for one to a slice or bytes, which JS makes anew each time, and `ptr::addr_eq` comparing what `ptr::eq` compares, of one pointee type, and `into_inner` giving it only from the last strong `Arc`, as a copy where pointers to it compare, after which its `Weak`s no longer upgrade; `rs.Weak`, counted in its `rs.Arc` until it drops, and of no `Arc` once made by `Weak::new`, its `as_ptr` pointing where its `Arc`'s does whether or not a strong one is left, or at std's dangling address, wasm32's `usize::MAX`, for a `Weak::new`'s, and refused for a slice, which JS keeps no length of for a `Weak::new` unsized to one, and for a value JS keeps as an object of a type the program makes by `new_cyclic` too, which has no object to point at until its closure returns; `rs.Mutex`, its own guard, which a lock gives as `Ok` and the guard's drop unlocks: locking it again while held panics and `try_lock` gives `WouldBlock`, as wasm32's do, and a guard's `map` and `filter_map` make `rs.MutexMap`s, each where the part it lends is, which hold the mutex locked until they drop, and a panic aborts, so nothing poisons it and `thread::panicking` is `false`; a `Mutex`'s, a `RefCell`'s, and an `RwLock`'s `into_inner` gives its value and `get_mut` lends it, or an `rs.Place` of it where JS copies it | | `PoisonError`, `TryLockError` | the `T` it holds; `rs.TryLockError`, tagged as `Bound` is | @@ -1489,4 +1489,4 @@ workloads still settle into one of two speeds per worker, up to 2x apart, so on their A/A stayed 6-35% wide while the median workload's was 1-3%. The report's A/A line also gives the noise of a family's geometric mean, the steadier gauge. -The bench shell adds Chromium, Firefox, and Binaryen. +The bench shell adds Chromium, Firefox, WebKit, and Binaryen. diff --git a/ts/fixtures/lang/drops/caller.ts b/ts/fixtures/lang/drops/caller.ts index 6538e9060..d6715db85 100644 --- a/ts/fixtures/lang/drops/caller.ts +++ b/ts/fixtures/lang/drops/caller.ts @@ -1,6 +1,8 @@ // The inputs `drops`' cases name, which run with the generated ones. +import { Logged } from "./drops.Logged.ts"; import { op } from "./lang.ts"; +import * as rs from "./rs.ts"; export { ops, run } from "./lang.ts"; @@ -11,3 +13,15 @@ const dropsCases = Array.from({ length: 12 * 16 * 12 }, (_, i) => Uint8Array.of( const ifLetsCases = Array.from({ length: 3 * 5 }, (_, i) => Uint8Array.of(...op("drops::if_lets"), i % 3, Math.floor(i / 3))); export const cases: Uint8Array[] = [...dropsCases, ...ifLetsCases]; + +// A consumer's `using` runs the drop the translation defines, as `Symbol.dispose` is on an engine +// that has it and on one that lacks it, as stable Safari does: a drop at the end of the block, once. +{ + const log = new rs.RefCell(new rs.ByteVec()); + const logged = (): number => log.value.length; + { + using _logged = new Logged(7, log); + if (logged() !== 0) throw new Error("a `using` value dropped before its scope ended"); + } + if (logged() !== 1 || log.value.data[0] !== 7) throw new Error("a `using` value did not drop at the end of its scope"); +} diff --git a/ts/runtime/rs.ts b/ts/runtime/rs.ts index fa0ac7a6d..1f0a2d6a1 100644 --- a/ts/runtime/rs.ts +++ b/ts/runtime/rs.ts @@ -5,6 +5,7 @@ // left only where a call dispatches on its receiver: an iterator's `next`, a writer's // `writeStr` and `writeChar`, a future's `poll`, a waker's, and `[Symbol.dispose]`. +import "./rs/dispose.ts"; import type { Shared } from "./rs/bytes.ts"; import type { Ordering } from "./rs/collections.ts"; import type { ParseFloatError } from "./rs/float.ts"; diff --git a/ts/runtime/rs/dispose.ts b/ts/runtime/rs/dispose.ts new file mode 100644 index 000000000..c19bc7026 --- /dev/null +++ b/ts/runtime/rs/dispose.ts @@ -0,0 +1,4 @@ +// `Symbol.dispose` where the engine lacks it, as stable Safari does: the registry's symbol, +// which esbuild's `using` helper falls back to too, though TypeScript's throws without one. +// `rs.ts` imports this first, so it runs before any class below keys a method on it. +if (!Symbol.dispose) Object.defineProperty(Symbol, "dispose", { value: Symbol.for("Symbol.dispose") }); diff --git a/ts/runtime/rs/tokio.ts b/ts/runtime/rs/tokio.ts index bc6a2e778..a2157a5e8 100644 --- a/ts/runtime/rs/tokio.ts +++ b/ts/runtime/rs/tokio.ts @@ -577,7 +577,7 @@ export class MpscPermits extends Iter> implements Disposable { } /** `ExactSizeIterator::len`. */ - len(): number { + override len(): number { return this.n; } diff --git a/ts/runtime/tsconfig.json b/ts/runtime/tsconfig.json index 887d2c98e..5ad9eda9f 100644 --- a/ts/runtime/tsconfig.json +++ b/ts/runtime/tsconfig.json @@ -2,6 +2,7 @@ "compilerOptions": { "strict": true, "noEmit": true, + "noImplicitOverride": true, "noUnusedLocals": true, "noUnusedParameters": true, "target": "es2022", diff --git a/ts/src/check.rs b/ts/src/check.rs index 5b502f899..66e658a73 100644 --- a/ts/src/check.rs +++ b/ts/src/check.rs @@ -26,6 +26,7 @@ fn tsconfig(files: &[String]) -> String { r#"{{ "compilerOptions": {{ "strict": true, + "noImplicitOverride": true, "noEmit": true, "pretty": false, "target": "es2022", diff --git a/ts/src/program.rs b/ts/src/program.rs index 43684161c..4cd100b1a 100644 --- a/ts/src/program.rs +++ b/ts/src/program.rs @@ -21,6 +21,7 @@ pub(crate) const RUNTIME: &[(&str, &str)] = &[ ("rs/bytes.ts", include_str!("../runtime/rs/bytes.ts")), ("rs/char.ts", include_str!("../runtime/rs/char.ts")), ("rs/collections.ts", include_str!("../runtime/rs/collections.ts")), + ("rs/dispose.ts", include_str!("../runtime/rs/dispose.ts")), ("rs/float.ts", include_str!("../runtime/rs/float.ts")), ("rs/hash.ts", include_str!("../runtime/rs/hash.ts")), ("rs/hook.ts", include_str!("../runtime/rs/hook.ts")), diff --git a/ts/tests/dispose.ts b/ts/tests/dispose.ts new file mode 100644 index 000000000..303e990af --- /dev/null +++ b/ts/tests/dispose.ts @@ -0,0 +1,39 @@ +// An engine without `Symbol.dispose`, as stable Safari is: the runtime, bundled and run in a +// context whose `Symbol` lacks it, defines it as the registry's `Symbol.for("Symbol.dispose")`, +// which esbuild's `using` helper falls back to, before any class keys a method on it. +// +// usage: node dispose.ts + +import { execFileSync } from "node:child_process"; +import vm from "node:vm"; + +const entry = process.argv[2]; +if (!entry) throw new Error("usage: dispose.ts "); +const code = execFileSync("esbuild", [entry, "--bundle", "--format=iife", "--global-name=runtime", "--target=es2022"], { + encoding: "utf8", +}); + +// The built-in `Symbol`, but for `dispose` and `asyncDispose`, which cannot be deleted from it. +const FakeSymbol = Object.defineProperties( + (description?: string) => Symbol(description), + Object.fromEntries(Reflect.ownKeys(Symbol).filter((key) => key !== "dispose" && key !== "asyncDispose").map((key) => [key, Object.getOwnPropertyDescriptor(Symbol, key)!])), +); + +// What a browser gives the runtime that a bare context lacks. +const { TextEncoder, TextDecoder, URL, console, queueMicrotask, setTimeout, clearTimeout, performance } = globalThis; +const context = vm.createContext({ Symbol: FakeSymbol, TextEncoder, TextDecoder, URL, console, queueMicrotask, setTimeout, clearTimeout, performance }); +if (vm.runInContext("typeof Symbol.dispose", context) !== "undefined") throw new Error("the context's Symbol still has dispose"); +vm.runInContext(`${code}\nglobalThis.runtime = runtime;`, context); + +const registry = Symbol.for("Symbol.dispose"); +const defined = vm.runInContext("Symbol.dispose", context); +if (defined !== registry) throw new Error(`Symbol.dispose is ${String(defined)}, not the registry's`); + +// Each class that disposes does so under that symbol, and none under the string "undefined". +let disposing = 0; +for (const [name, value] of Object.entries(vm.runInContext("runtime", context) as Record)) { + if (typeof value !== "function" || !value.prototype) continue; + if (Object.hasOwn(value.prototype, "undefined")) throw new Error(`${name} keys a method on "undefined"`); + if (Object.getOwnPropertySymbols(value.prototype).includes(registry)) disposing++; +} +if (disposing === 0) throw new Error("no exported class disposes under the registry's symbol"); diff --git a/ts/tests/runtime.rs b/ts/tests/runtime.rs index 537a4d5f7..17dd9b9d1 100644 --- a/ts/tests/runtime.rs +++ b/ts/tests/runtime.rs @@ -522,3 +522,16 @@ fn pointers_apart() { .expect("running node, which the dev shell provides"); assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr)); } + +/// Where the engine lacks `Symbol.dispose`, as stable Safari does, the runtime defines it as +/// the registry's symbol before its classes key a method on it, which `dispose.ts` checks. +#[test] +fn dispose_absent() { + let tests = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests"); + let output = Command::new("node") + .arg(tests.join("dispose.ts")) + .arg(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("runtime").join("rs.ts")) + .output() + .expect("running node, which the dev shell provides"); + assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr)); +} From 96416c61f4ac3c678a43a299c535a40d5626f42e Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 03:56:34 -0800 Subject: [PATCH 3/3] Run the using check in a case WebKit runs Co-Authored-By: Claude Sonnet 5.5 --- ffi/tests/api.ts | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/ffi/tests/api.ts b/ffi/tests/api.ts index c9466fd6e..ab5284c20 100644 --- a/ffi/tests/api.ts +++ b/ffi/tests/api.ts @@ -1348,18 +1348,11 @@ async function owned(): Promise { close(token); check(api.dropped() === before + 1, "disposing again frees nothing"); closed(() => Token.idGet(token), "Token", "a disposed token refuses a read"); - // `using` disposes at the end of its scope, as stable Safari, which lacks `Symbol.dispose`, - // needs the runtime's own symbol for, however the bundler lowers it. - { - using scoped = Token.new(2); - check(api.dropped() === before + 1 && Token.idGet(scoped) === 2, "a `using` object is open in its scope"); - } - check(api.dropped() === before + 2, "a `using` object frees at the end of its scope"); unclosed(); - await collect(() => api.dropped() >= before + 3, "the garbage collector frees what nobody disposed"); + await collect(() => api.dropped() >= before + 2, "the garbage collector frees what nobody disposed"); await settle(); - check(api.dropped() === before + 3, "the garbage collector frees each once"); + check(api.dropped() === before + 2, "the garbage collector frees each once"); // An implementation an object the garbage collector frees held is closed. const log = new CountLog(); @@ -1407,6 +1400,16 @@ async function closedObjects(): Promise { const c = Counter.new("c", 1); close(c); closed(() => Counter.get(c), "Counter", "a method of a disposed object"); + // `using` disposes at the end of its scope, as stable Safari, which lacks `Symbol.dispose`, + // needs the runtime's own symbol for, however the bundler lowers it. No garbage collector + // is involved, so every browser runs it. + let scoped: ReturnType | undefined; + { + using inner = Counter.new("u", 3); + scoped = inner; + check(Counter.get(inner) === 3, "a `using` object is open in its scope"); + } + closed(() => Counter.get(scoped!), "Counter", "a `using` object after its scope"); closed(() => Counter.clone(c), "Counter", "clone of a disposed object"); closed(() => Counter.debug(c), "Counter", "debug of a disposed object"); const url = unwrap(Url.parse("https://example.com"));