From 347f36cc24d33d761728e28a19e3af4dd58d0f74 Mon Sep 17 00:00:00 2001 From: Alex Tiernan-Berry Date: Sat, 21 Nov 2026 17:16:19 +0000 Subject: [PATCH 1/8] xtask: an ENGINE list, so engine crates reach no browser crate phase-7.md's boundary says engine crates depend on no browser crate and that cargo xtask check enforces it through an ENGINE list next to PLACES. The list did not exist. It names the clazel-js crates, rejects any path (direct or through another crate) to a browser crate, and fails on a clazel-js* crate missing from the list. clazel-js is placed in the Renderer component. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 4 ++ xtask/src/main.rs | 13 ++++++ xtask/src/status.rs | 111 +++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 127 insertions(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index c8972623b..32f30af26 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -388,6 +388,10 @@ dependencies = [ "vstd", ] +[[package]] +name = "clazel-js" +version = "0.0.0" + [[package]] name = "clazel-js-lexer" version = "0.0.0" diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 0feed1485..d77e30887 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -342,6 +342,19 @@ fn static_checks(r: &mut Runner, crates: &[Crate], pins: &Pins) { "every crate placed in the status images", outcome(status::placement_problems(&names), Vec::new()), ); + let engine_deps: Vec<(String, Vec)> = crates + .iter() + .map(|c| { + ( + c.name.clone(), + c.deps_normal().into_iter().map(|(n, _)| n).collect(), + ) + }) + .collect(); + r.step( + "engine crates depend on no browser crate", + outcome(status::engine_problems(&engine_deps), Vec::new()), + ); // Unreviewed specs are not a failure (agents must be able to edit // them), but every run lists them. let review_notes: Vec = review_status diff --git a/xtask/src/status.rs b/xtask/src/status.rs index 95f092639..6e316807e 100644 --- a/xtask/src/status.rs +++ b/xtask/src/status.rs @@ -72,6 +72,7 @@ const PLACES: &[(&str, Place)] = &[ ("clazel-css", Place::Renderer), ("clazel-selectors", Place::Renderer), ("clazel-js-lexer", Place::Renderer), + ("clazel-js", Place::Renderer), ("clazel-js-vm", Place::Renderer), ("clazel-js-syntax", Place::Renderer), ("clazel-style", Place::Renderer), @@ -100,6 +101,31 @@ const PLACES: &[(&str, Place)] = &[ ("clazel-sys", Place::Os), ]; +/// The engine crates (phase-7.md, "The engine as a library"): a program other +/// than the browser can embed them, so none may depend, directly or through +/// other crates, on a crate in [`BROWSER`]. `cargo xtask check` enforces this. +/// `clazel-js*` crates not listed here fail the check too, so a new engine +/// crate cannot skip the rule by being left out. +const ENGINE: &[&str] = &[ + "clazel-js", + "clazel-js-lexer", + "clazel-js-regexp", + "clazel-js-syntax", + "clazel-js-vm", +]; + +/// The crates an engine crate must never reach (phase-7.md, "The boundary"). +const BROWSER: &[&str] = &[ + "clazel-dom", + "clazel-webidl", + "clazel-web", + "clazel-ipc", + "clazel-kernel", + "clazel-renderer", + "clazel-url", + "clazel-fetch", +]; + /// Workspace members that are not part of the browser, so not drawn. const NOT_DRAWN: &[&str] = &["xtask"]; @@ -143,6 +169,49 @@ pub fn placement_problems(names: &[&str]) -> Vec { out } +/// Engine crates that reach a browser crate through normal dependencies, and +/// `clazel-js*` workspace crates missing from [`ENGINE`]. `deps` is each +/// workspace crate's name with its normal dependencies' names. +pub fn engine_problems(deps: &[(String, Vec)]) -> Vec { + let direct = |name: &str| -> &[String] { + deps.iter() + .find(|(n, _)| n == name) + .map_or(&[][..], |(_, d)| d.as_slice()) + }; + let mut out = Vec::new(); + for (name, _) in deps { + if name.starts_with("clazel-js") && !ENGINE.contains(&name.as_str()) { + out.push(format!( + "{name}: an engine crate (clazel-js*) missing from ENGINE in xtask/src/status.rs" + )); + } + } + for e in ENGINE { + if !deps.iter().any(|(n, _)| n == e) { + out.push(format!( + "xtask/src/status.rs: ENGINE names {e}, which is no workspace crate" + )); + continue; + } + // Breadth-first over the workspace crates reachable from `e`. + let mut seen: Vec<&str> = vec![e]; + let mut next = 0; + while let Some(&cur) = seen.get(next) { + next = next.saturating_add(1); + for d in direct(cur) { + if BROWSER.contains(&d.as_str()) { + out.push(format!( + "{e}: engine crate depends on browser crate {d} (via {cur}); engine crates depend on no browser crate" + )); + } else if deps.iter().any(|(n, _)| n == d) && !seen.contains(&d.as_str()) { + seen.push(d.as_str()); + } + } + } + } + out +} + /// The first sentence of an `axioms.rs`'s module documentation, for the /// detail image's note on axioms. `None` if the crate has no such file or /// it has no `//!` comment. @@ -995,7 +1064,8 @@ pub fn render( #[cfg(test)] mod tests { use super::{ - PLACES, Place, Rows, SCOREBOARD_PER_LINE, numbers, placement_problems, render, short_count, + ENGINE, PLACES, Place, Rows, SCOREBOARD_PER_LINE, engine_problems, numbers, + placement_problems, render, short_count, }; fn row(cells: &[&str]) -> Vec { @@ -1112,6 +1182,45 @@ mod tests { assert!(render(&rows, &|_| None).is_err()); } + #[test] + fn engine_crates_reach_no_browser_crate() { + // The engine crates, with these edges, plus the other crates named. + let graph = |edges: &[(&str, &[&str])], extra: &[&str]| { + let mut deps: Vec<(String, Vec)> = ENGINE + .iter() + .map(|e| { + let to = edges + .iter() + .find(|(n, _)| n == e) + .map_or(&[][..], |(_, d)| *d); + ( + (*e).to_owned(), + to.iter().map(|d| (*d).to_owned()).collect(), + ) + }) + .collect(); + deps.extend(extra.iter().map(|n| ((*n).to_owned(), Vec::new()))); + engine_problems(&deps) + }; + assert!(graph(&[], &[]).is_empty()); + // A direct dependency. + assert_eq!( + graph(&[("clazel-js", &["clazel-dom"])], &["clazel-dom"]).len(), + 1 + ); + // A transitive one, through another engine crate: both are reported. + let found = graph( + &[ + ("clazel-js", &["clazel-js-vm"]), + ("clazel-js-vm", &["clazel-dom"]), + ], + &["clazel-dom"], + ); + assert_eq!(found.len(), 2, "{found:?}"); + // An engine crate left out of ENGINE. + assert_eq!(graph(&[], &["clazel-js-heap"]).len(), 1); + } + #[test] fn short_counts() { assert_eq!(short_count(912), "912"); From 88a03e3d4fb7a3f6b5c684a95bb043605a0f11a9 Mon Sep 17 00:00:00 2001 From: Alex Tiernan-Berry Date: Sat, 21 Nov 2026 17:16:19 +0000 Subject: [PATCH 2/8] clazel-js: the embedding API contract (phase 7.8, contract first) The public types, traits and signatures of the engine's embedding API, with a README stating the rules and doc examples that compile (no_run). Every operation that needs the engine returns Error::NotImplemented; the Terminator, DefaultHost and Limits are real because they are small. Tier 0, no dependencies. Co-Authored-By: Claude Opus 5.5 --- crates/clazel-js/Cargo.toml | 21 + crates/clazel-js/README.md | 325 ++++++++++++++ crates/clazel-js/src/code.rs | 293 ++++++++++++ crates/clazel-js/src/error.rs | 193 ++++++++ crates/clazel-js/src/host.rs | 477 ++++++++++++++++++++ crates/clazel-js/src/lib.rs | 46 ++ crates/clazel-js/src/native.rs | 237 ++++++++++ crates/clazel-js/src/runtime.rs | 330 ++++++++++++++ crates/clazel-js/src/scope.rs | 775 ++++++++++++++++++++++++++++++++ crates/clazel-js/src/value.rs | 346 ++++++++++++++ 10 files changed, 3043 insertions(+) create mode 100644 crates/clazel-js/Cargo.toml create mode 100644 crates/clazel-js/README.md create mode 100644 crates/clazel-js/src/code.rs create mode 100644 crates/clazel-js/src/error.rs create mode 100644 crates/clazel-js/src/host.rs create mode 100644 crates/clazel-js/src/lib.rs create mode 100644 crates/clazel-js/src/native.rs create mode 100644 crates/clazel-js/src/runtime.rs create mode 100644 crates/clazel-js/src/scope.rs create mode 100644 crates/clazel-js/src/value.rs diff --git a/crates/clazel-js/Cargo.toml b/crates/clazel-js/Cargo.toml new file mode 100644 index 000000000..da3af2cf6 --- /dev/null +++ b/crates/clazel-js/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "clazel-js" +version = "0.0.0" +edition.workspace = true +license.workspace = true +publish.workspace = true +description = "The JavaScript engine's embedding API for Clazel (phase-7.md item 7.8): Runtime, realms, scripts and modules, native functions, host objects, rooted handles, the Host trait, limits and the Terminator. This is the contract only; nothing here is implemented yet." + +# No dependencies yet. When the engine's types are needed here they come from +# other engine crates only (`cargo xtask check` enforces that no engine crate +# reaches a browser crate; see ENGINE in xtask/src/status.rs). +[dependencies] + +# Verification tier (docs/VERIFICATION.md). Tier 0: this crate holds the +# contract and its stubs, and nothing is proven about it. +[package.metadata.clazel] +tier = 0 +target-tier = 0 + +[lints] +workspace = true diff --git a/crates/clazel-js/README.md b/crates/clazel-js/README.md new file mode 100644 index 000000000..864d3f60e --- /dev/null +++ b/crates/clazel-js/README.md @@ -0,0 +1,325 @@ +# clazel-js: the engine's embedding API + +`clazel-js` is the one crate a program names to embed Clazel's JavaScript +engine. The browser embeds it, and so can a command-line runtime, a +Node-style server, or another Rust program. This is phase-7.md item 7.8, and +"The engine as a library" in that file is the plan this README works out. + +**Status: the contract, and nothing else.** The types and signatures here are +the proposal, and the doc comments carry examples that compile (`no_run`, +because there is nothing to run). Every operation that needs the engine returns +`Error::NotImplemented`. Tier 0, no proofs. The contract is written first, as +the plan says, so that people can review it before `clazel-webidl` and +`clazel-web` build on it. What to review is below, in "Open questions". + +Read the API in `src/`, one file per topic: `runtime.rs` (Runtime, limits, +Terminator), `value.rs` (the four ways to hold a value), `scope.rs` (all the +operations), `code.rs` (realms, source, scripts, modules), `native.rs` +(native functions, host objects), `host.rs` (the `Host` trait), `error.rs`. +`cargo doc -p clazel-js --no-deps --open` shows the same with the examples. + +## The boundary + +- Engine crates depend on no browser crate. `cargo xtask check` enforces it + with the `ENGINE` list in `xtask/src/status.rs`, which holds this crate. +- `clazel-js` has no dependencies yet. It will re-export the types the API needs + from other engine crates (the heap's value and arena types) and no more. +- The browser uses only this public API. A binding that needs something the API + lacks gets it added here, not a private path. +- The Test262 runner (`clazel-js-shell`, a later item) is a second embedder and + builds `$262` from public calls alone. + +## A `Runtime` + +A `Runtime` is one ECMAScript agent: a heap, a job queue, limits and a `Host`. + +- **No global state.** No `static`, no thread-local. A process can hold many + runtimes. +- **`Send`, not `Sync`.** A runtime can move to another thread between calls, and + only one thread uses it at a time. Compile-checked by doctests. For this to + hold the `Host` is `Send` too. The browser runs one runtime per renderer, on + one thread (7.0(e)). +- **Everything goes through a scope.** `Runtime::scope(|scope| ...)` is the only + way in. Inside native functions and `Host` hooks the engine hands over a + `Scope` for that call. +- **Dropping a runtime** frees the heap and drops native closures and host + object data. It runs no JavaScript. + +Configuration is a `Config` of `Limits` and a `JitMode` (only `Off` until jit.md's +crate exists), and a `Host`: + +```rust,no_run +use clazel_js::{Config, DefaultHost, Limits, RealmOptions, Runtime, Source}; + +fn main() -> Result<(), clazel_js::Error> { + let mut rt = Runtime::new(Config::new(Limits::unlimited()), DefaultHost::new())?; + let realm = rt.scope(|scope| scope.create_realm(RealmOptions::default()))?; + let sum = rt.scope(|scope| { + let value = scope.eval_script(&realm, Source::new("sum.js", "1 + 2"))?; + Ok(scope.as_number(value)) + })?; + assert_eq!(sum, Some(3.0)); + rt.run_jobs()?; + Ok(()) +} +``` + +## Realms + +`Scope::create_realm` makes a realm: a global object and its own built-ins. +`$262.createRealm()` is exactly this, and frames would be later. A `Realm` is a +root (cloneable, `Send`, `Sync`) and every call that runs code names its realm. +`Scope::global` reaches the global object, and installing `console` or `window` +is ordinary property definition on it. `RealmOptions::global` lets the +global object be a host object, which the browser's `Window` needs. +`Scope::set_realm_host_defined` attaches the embedder's data to a realm (HTML's +environment settings object). + +## Scripts and modules + +- **Source** is `Source { name, text, start_line, host_defined }`. The text is a + `&str`, a sequence of code points, as ECMA-262 defines source text. The name + is for stack traces and reports, and `host_defined` is the embedder's data + (base URL, fetch options), kept with the compiled code. +- **Scripts.** `eval_script` does `compile_script` then `run_script`, which are + separate so a host can follow HTML's "prepare the script element". A syntax + error is a thrown `SyntaxError`. +- **Modules** follow ECMA-262's phases, one method each: `parse_module`, + `load_requested_modules`, `link`, `evaluate_module`, plus `module_namespace` and + `module_status`. Loading is asynchronous and the host's: the engine calls + `Host::load_imported_module(referrer, request, payload)`, and the host + answers with `Scope::finish_loading_imported_module(payload, result)`, now or + on a later event-loop turn. Dynamic `import()` uses the same hook. The + `Referrer` carries the importing code's `host_defined` data, so the host knows + what to resolve against. `import.meta` goes through two more hooks. A host + can add its own resolver, or CommonJS (through synthetic modules), without + engine changes. +- **Jobs.** The engine queues jobs and runs them only when asked: + `Runtime::run_jobs` is a microtask checkpoint. The event loop is the host's. + HTML's lives in `clazel-web`, and a Node-style runtime would drive the same + calls from its own. + +## Values, and holding them + +Values live in the collector's heap, which does not move them (7.0(f)). Four +types hold a value, from cheapest to most durable: + +| Type | Roots the value? | Lives | Use | +|---|---|---|---| +| `Local<'s>` | yes, until its scope ends | one `Scope` | everything inside a call. `Copy`; cannot escape the closure (compile-checked) | +| `Handle` | yes, until dropped | any time, any thread | what outlives a call: a callback to run later, a promise's resolvers. `Clone`, `Send`, `Sync`; dropping needs no runtime | +| `Weak` | no | any time | side tables from platform objects to wrappers; `upgrade` gives `None` after collection | +| `Member` | only if its owner reports it | owner's choice | JS values inside a host object's data or the host, reported from `trace` so there is no uncollectable cycle | + +- **Stale is an error, never an alias.** Every reference carries the arena's + generation (7.5, 7.6). Using one that no longer names its object gives + `Error::StaleHandle`. A handle from another runtime gives `Error::WrongRuntime`. +- **When the collector runs:** inside an operation that allocates, or on + `Scope::gc()` (`$262.gc()`), at points the engine chooses. Never between two + of the embedder's own Rust statements, and never while tracing, which is given + no `Scope`. +- **Roots** are the value stack, every live `Local`, every `Handle`, the job + queue, and what the host reports from `Host::trace_roots` (for the browser: + the wrapper of every node in a tree) and each host object's `trace`. +- **Strings** are UTF-16 code unit sequences, as in the language. + `Scope::string` takes Rust text; `string_utf16` takes units, including lone + surrogates, which WebIDL's conversions need. `string_to_utf16` reads exactly, + and `string_to_string_lossy` replaces lone surrogates. + +## Native functions and host objects + +- **`Scope::function(name, length, Callable, f)`** makes a JavaScript function + from a Rust closure `Fn(&mut Scope, &Args) -> Result`. It is `Fn`, not + `FnMut`, because a native function can be re-entered through JavaScript it + calls. State it needs lives in a host object, in the `Host`, or behind a lock. + `Callable::Constructor` makes it usable with `new`, with `Args::new_target` + set, and `get_prototype_from_constructor` gives subclasses their prototype. +- **`HostObject`** is a trait for the Rust data of a JavaScript object. It is + typed (`host_data::` checks, `Error::WrongType` otherwise), is dropped when + the collector frees the object, reports the values it refers to from `trace`, + and may have four exotic hooks (`get_own_property`, `define_own_property`, + `delete_property`, `own_property_keys`) for WebIDL's legacy platform objects. + This is how `clazel-webidl` builds DOM wrappers. + +## `Host` + +One trait for everything ECMA-262 leaves to the host, each with a stated +default, so `DefaultHost` works for a program that needs none. Hooks get +`&mut self` and a `Scope`, may re-enter the engine, and may fail with an +`Error`, which the calling operation passes on. + +| Group | Methods (ECMA-262 name) | Default | +|---|---|---| +| Jobs | `enqueue_promise_job`, `enqueue_generic_job`, `enqueue_timeout_job`, `enqueue_finalization_registry_cleanup_job` | the engine's own queue | +| Job callbacks | `make_job_callback`, `call_job_callback` | a plain callback; call it | +| Modules | `load_imported_module`, `supported_import_attributes`, `get_import_meta_properties`, `finalize_import_meta` | refuse with a `TypeError`; none; none; nothing | +| Promises | `promise_rejection_tracker` | nothing | +| Code from strings | `ensure_can_compile_strings`, `has_source_text_available` | allow; yes | +| Objects | `ensure_can_add_private_element`, `resize_array_buffer` | allow; `Unhandled` | +| The world | `now_ms`, `local_tza`, `random_u64`, `default_locale` | system clock; UTC; (required); `en-US` | +| The collector | `trace_roots` | nothing | + +The browser's answers for the world are its own: 7.0(b)'s fixed offset and +`en-US`, in `clazel-web`. The engine fixes none of them. `random_u64` has no +default because the engine has no entropy source and rule 8 forbids adding a +dependency for one. `DefaultHost` implements it from the standard library. + +**`$262`, built from public calls.** The shell's hooks need nothing private: + +| `$262` | Public call | +|---|---| +| `createRealm()` | `Scope::create_realm`, then `global` | +| `evalScript(src)` | `Scope::eval_script` in the realm | +| `gc()` | `Scope::gc` | +| `detachArrayBuffer(buf)` | `Scope::detach_array_buffer` | +| `agent` | none; see the open questions | + +## Errors and exceptions + +`Result` throughout. One variant is a JavaScript value; the rest are the +engine's and cannot be caught by JavaScript: + +- `Thrown(Exception)`: JavaScript threw. An `Exception` holds the value in a + `Handle`, so it can be reported after the call returned. This includes the + `SyntaxError` for bad source and the `RangeError`s the limits raise. + `Scope::report` turns it into an `ErrorReport` (name, message, stack) without + running user code. +- `Terminated`: a `Terminator` ended the evaluation. +- `OutOfMemory`: the heap limit was hit and not even the `RangeError` could be + allocated. Rare. +- `StaleHandle`, `WrongRuntime`, `WrongType`, `Busy`: misuse of the API, + caught and reported, never undefined behaviour. +- `NotImplemented`: this contract's stubs, until 7.8 builds the bodies. + +A native function returns errors of either kind with `?`. To throw: +`return Err(scope.throw_error(ErrorKind::TypeError, "..."))`, or +`scope.throw(value)` for a value the embedder made (a `DOMException`). + +## Limits and the `Terminator` + +**Limits are the embedder's.** `Limits` has no `Default`, and a struct literal must +name every field, so nothing is fixed in the engine and adding a limit makes +each embedder choose. `Limits::unlimited()` is a named choice for tests. + +| Limit | When passed | +|---|---| +| `heap_bytes` | full collection first, then a `RangeError` | +| `value_stack_bytes` | `RangeError`, "too much recursion" | +| `native_depth` | `RangeError`; counts built-ins that call back into JS | +| `code_bytes` | the JIT stops compiling; not an error | +| `regexp_backtrack_entries` | `RangeError` from the match | +| `nesting_depth` | `SyntaxError` (parser), `RangeError` (`JSON.parse`) | + +Timers and fetches in flight are the host's to bound, not the engine's. + +**`Terminator`** (`Runtime::terminator()`; `Clone`, `Send`, `Sync`) stops a runtime +from another thread. It sets a flag; the interpreter checks it at loop back-edges +and calls, JIT code at the same points, built-ins in their long loops, and native +functions via `Scope::check_terminated`. The evaluation ends with +`Error::Terminated`. JavaScript cannot catch it, and no `finally` runs. The flag +stays set until `Terminator::clear`. The `Terminator` itself is implemented +and tested here, because it is only an atomic flag. The browser keeps 7.0(g)'s +policy (it ends a stuck renderer, on the user's word) and may use this later to +keep the tab. jit.md adds no interaction beyond "JIT code checks the same flag at +the same points". + +**Executable memory** is the embedder's choice (jit.md J.0(b)). `JitMode` gains a +variant that carries a `CodeMapper` when `clazel-jit` exists. Until then it is +interpreter only, which is complete. + +## What the browser's bindings will use + +| Browser need | API | +|---|---| +| Install `window`, `document`, `console` | `create_realm` with a host-object global; `global`; `define_property`, `define_method` | +| Interface objects and prototypes (7.12) | `function` with `Callable::Constructor`; `get_prototype_from_constructor`; `define_property`; `set_prototype_of` | +| Wrappers, one per platform object (7.12, 7.13) | `new_host_object` with typed data; `Weak` for the side table; `Host::trace_roots` for nodes in a tree | +| `NodeList[0]`, `HTMLCollection.name` | `HostObject`'s exotic hooks | +| WebIDL conversions (3.2) | `to_number`, `to_string`, `to_boolean`, `to_object`, `is_callable`, `get_method`, `iterate`, `string_utf16`, `bigint_from_*` | +| `DOMException`, TypeErrors | `throw_error`, `throw` | +| Event listeners calling JS (7.14) | `Handle` or `Member` to the callback; `call`; `report` for uncaught exceptions | +| Promises from `fetch()`, `import()` (7.15, 7.16) | `new_promise`, `resolve_promise`, `reject_promise`, `promise_then`, `promise_state` | +| Script elements (7.15) | `compile_script`, `run_script`, `parse_module`, `load_requested_modules`, `link`, `evaluate_module`, `Host::load_imported_module` | +| Event loop, microtasks, `queueMicrotask` (7.15) | `Runtime::run_jobs`; `Host::enqueue_promise_job`, `make_job_callback`, `call_job_callback`; `clear_kept_objects` after a checkpoint | +| Unhandled rejections | `Host::promise_rejection_tracker` | +| `Date`, `Math.random`, locale | `Host::now_ms`, `local_tza`, `random_u64`, `default_locale` | +| A stuck page (7.0(g)) | `Terminator` | + +## What is deliberately not in the API + +- **A C API** (`clazel-js-capi`): Phase 8, and needs its own decision under rule 1. +- **Stability.** Rust only, unstable, no semver promise until Phase 8 has a second + real user. +- **Node as a drop-in.** A Node-compatible runtime on `clazel-js` is the + realistic path, not V8 API emulation. +- **Threads and shared memory**: `SharedArrayBuffer`, `Atomics`, and so + `$262.agent`; one runtime per thread only (7.0(b), 7.0(e)). +- **`Intl`, Temporal, WebAssembly, a debugger protocol, heap snapshots.** +- **Event loops, timers, `console`, `fetch`, a DOM.** The embedder's. The engine + has none and calls the `Host` instead. +- **Catching panics from native functions.** The lints forbid them here, and an + embedder's panic is its own. +- **Safety against a hostile embedder is not a goal; safety against hostile + JavaScript is.** An embedder that runs untrusted code without the browser's + sandbox relies on the engine's own guarantees: no `unsafe` outside + `clazel-sys`, the arena's generation checks, the validator's theorem for JIT + code, and the limits. + +## Open questions + +Nothing here is a decision the plan marks as the maintainer's. These are what the +plan leaves open and this contract had to settle, or leaves unsettled, so please +look at each. + +1. **After `Terminated`, is the runtime usable?** The proposal: the flag is + sticky, so every call ends `Terminated` until the embedder calls + `Terminator::clear`; after that the heap is consistent and the runtime + usable. It rests on `finally` blocks not running. It makes termination safe + for a runtime that is then dropped, and for the browser, but "usable after" + is a promise to implement and test. +2. **Handle model.** `Local<'s>` scoped to a closure, plus `Handle` (reference + counted, dropped without the runtime) and `Member` (reported from `trace`). + Plan 7.0(f) says "a scoped handle stack, checked on scope exit". The scope + here is a closure with a lifetime the compiler enforces, which is checked + earlier than at exit. The cost is that a value cannot be returned from a + nested scope except as a `Handle`; an `escape` call is possible if that bites. +3. **`Host: Send`.** It keeps `Runtime: Send`. It means the browser's host cannot + hold `Rc`s of DOM state: nodes are arena ids (Phase 4), which should work, + but it is the contract's strictest demand on `clazel-web`. +4. **Exotic hooks.** Four are given; WebIDL §3.9 and §3.10 (legacy platform + objects, named properties) may need `set`/`get` receivers or more. The + set is to be fixed against 7.12's generator, and may grow. +5. **The global's `this` value** (HTML's `WindowProxy`) is not in `RealmOptions`. + ECMA-262 lets a host set it separately from the global object. Needed by + 7.15, and the contract does not yet say how. +6. **Synthetic modules** (`new_synthetic_module`, `set_synthetic_export`) are + reserved in the contract, since "a host can add CommonJS" needs them and + JSON modules do. The plan does not list them as a Phase 7 deliverable. +7. **`$262.agent`.** The plan lists `agent` among the host hooks, and 7.0(b) + leaves out `SharedArrayBuffer` and `Atomics`, which `agent` exists to test. + This API has no agent hook, and the shell skips those tests. If another + host wants agents in Phase 8, a `Runtime` per thread plus shared memory + needs its own design. +8. **Hooks the plan's list lacks.** `HostEnqueueFinalizationRegistryCleanupJob` + (7.6 needs it) and `HostGetSupportedImportAttributes` are in the trait; + the plan's list does not name them. 7.4's check against the pinned edition + decides which stay. +9. **ECMA-262 section numbers** are not cited on the hooks, because 7.1 has not + pinned an edition. They are named by abstract operation instead, which does + not change between editions. Rule 5 asks for sections, so they are added when + 7.1 pins one. Until then the citations are incomplete. +10. **`run_jobs` and a throwing job.** A job that throws stops the run and + returns the exception; later jobs stay queued. A host that wants + "report and continue" overrides the queue hooks and runs jobs itself. + The alternative is one more hook. The plan names none. +11. **`Source` text as `&str`.** Source with a lone surrogate cannot be written. ECMA-262 + source text is code points, and the browser decodes with `clazel-encoding`, + which gives scalar values only, so nothing is lost in practice. Say so if + UTF-16 source is wanted. +12. **Where `CodeMapper` lives.** jit.md names it; this crate cannot depend on a + crate that does not exist. Likely `clazel-jit` defines it and `clazel-js` + re-exports it. +13. **`OutOfMemory` versus `RangeError`.** 7.19 says the heap limit gives a + `RangeError`. This contract keeps `OutOfMemory` for when even that cannot + be allocated. If that case can be avoided by reserving room for one + error object, the variant can go. diff --git a/crates/clazel-js/src/code.rs b/crates/clazel-js/src/code.rs new file mode 100644 index 000000000..1b49058a8 --- /dev/null +++ b/crates/clazel-js/src/code.rs @@ -0,0 +1,293 @@ +//! Realms, source text, scripts and modules. + +use core::any::Any; +use core::marker::PhantomData; + +use crate::native::HostObject; +use crate::value::Handle; + +/// A realm: a global object and its own copy of every built-in +/// (ECMA-262's Realm Record). +/// +/// - **Why more than one.** `$262.createRealm()` in Test262, and later a +/// frame. A realm's `Array` is not another realm's `Array`, and +/// `instanceof` across them is false, as in a browser. +/// - **Lifetime.** A `Realm` is a root: the realm and everything reachable +/// from its global object live until the last clone is dropped. Like +/// [`Handle`] it is `Send`, `Sync` and `Clone`, and needs a +/// [`Scope`](crate::Scope) to do anything. +/// - **No ambient realm.** Every call that runs code names the realm. Inside a +/// native function, [`Scope::current_realm`](crate::Scope::current_realm) +/// is the realm of the function being called. +/// +/// ```no_run +/// use clazel_js::{Runtime, RealmOptions, Source}; +/// +/// fn two_realms(rt: &mut Runtime) -> clazel_js::Result<()> { +/// let (a, b) = rt.scope(|scope| { +/// Ok((scope.create_realm(RealmOptions::default())?, +/// scope.create_realm(RealmOptions::default())?)) +/// })?; +/// rt.scope(|scope| { +/// let same = scope.eval_script(&a, Source::new("t.js", "[] instanceof Array"))?; +/// assert_eq!(scope.as_boolean(same), Some(true)); +/// // A realm's own object is not an instance of the other realm's Array. +/// let global_b = scope.global(&b)?; +/// let _ = global_b; +/// Ok(()) +/// }) +/// } +/// ``` +#[derive(Clone, Debug)] +pub struct Realm { + root: Handle, +} + +impl Realm { + /// The root that keeps the realm alive. + pub fn as_handle(&self) -> &Handle { + &self.root + } +} + +/// How to build a realm. The default is an ordinary global object with the +/// standard built-ins. +/// +/// ```no_run +/// use clazel_js::{Exotic, HostObject, RealmOptions}; +/// +/// /// The browser's `Window`: a host object serving as the global object. +/// struct Window; +/// impl HostObject for Window {} +/// +/// let options = RealmOptions { +/// global: Some(Box::new(Window)), +/// }; +/// # let _ = options; +/// ``` +#[derive(Default)] +pub struct RealmOptions { + /// Make the global object a host object with this data, whose prototype is + /// the realm's `Object.prototype`. `None` makes an ordinary object. Its + /// exotic hooks answer for the global's own properties. The global's `this` + /// value (HTML's `WindowProxy`) is an open question in the README. + pub global: Option>, +} + +/// Source text to compile, with where it came from. +/// +/// - **Text** is a `&str`: a sequence of Unicode code points, as ECMA-262 +/// defines source text. The browser decodes bytes to text with +/// `clazel-encoding` before calling. +/// - **Name** is what stack traces and error reports show: a URL for a +/// script from the network, `"inline"` or similar for the rest. +/// - **`start_line`** is the 1-based line number of the text's first line, so +/// an inline script in a page reports page line numbers. +/// - **`host_defined`** is the embedder's data about this code (a base URL, +/// fetch options). It is kept with the compiled [`Script`] or [`Module`] and +/// given back by [`Scope::host_defined`](crate::Scope::host_defined) +/// and to the [`Host`](crate::Host) hooks as part of a [`Referrer`]. +/// +/// ```no_run +/// use clazel_js::Source; +/// +/// struct BaseUrl(String); +/// +/// let source = Source::new("https://example.test/app.js", "export default 1;") +/// .with_start_line(1) +/// .with_host_defined(Box::new(BaseUrl("https://example.test/".to_owned()))); +/// assert_eq!(source.name(), "https://example.test/app.js"); +/// ``` +pub struct Source<'a> { + name: &'a str, + text: &'a str, + start_line: u32, + host_defined: Option>, +} + +impl<'a> Source<'a> { + /// Source text with a name, starting at line 1, with no host data. + pub fn new(name: &'a str, text: &'a str) -> Source<'a> { + Source { + name, + text, + start_line: 1, + host_defined: None, + } + } + + /// Sets the line number of the first line. + #[must_use] + pub fn with_start_line(mut self, start_line: u32) -> Source<'a> { + self.start_line = start_line; + self + } + + /// Attaches the embedder's data. + #[must_use] + pub fn with_host_defined(mut self, data: Box) -> Source<'a> { + self.host_defined = Some(data); + self + } + + /// The name. + pub fn name(&self) -> &str { + self.name + } + + /// The text. + pub fn text(&self) -> &str { + self.text + } + + /// The line number of the first line. + pub fn start_line(&self) -> u32 { + self.start_line + } + + /// The embedder's data, if any. + pub fn host_defined(&self) -> Option<&(dyn Any + Send)> { + self.host_defined.as_deref() + } +} + +/// A parsed classic script (ECMA-262's Script Record), not yet run. +/// +/// Parsing and running are separate so a host can follow HTML's "prepare the +/// script element", which fetches and compiles, then runs when the parser +/// or the event loop says. [`Scope::eval_script`](crate::Scope::eval_script) does both at +/// once. A `Script` is a root, `Clone`, `Send` and `Sync`, and may be run +/// more than once; top-level `var`s and functions are created in the realm +/// each time it runs, as for a script run twice. +/// +/// ```no_run +/// use clazel_js::{Realm, Runtime, Script, Source}; +/// +/// fn compile_then_run(rt: &mut Runtime, realm: &Realm) -> clazel_js::Result<()> { +/// let script: Script = rt.scope(|scope| { +/// scope.compile_script(realm, Source::new("later.js", "globalThis.n = 1")) +/// })?; +/// // ... the parser unblocks ... +/// rt.scope(|scope| { +/// scope.run_script(&script)?; +/// Ok(()) +/// }) +/// } +/// ``` +#[derive(Clone, Debug)] +pub struct Script { + root: Handle, +} + +impl Script { + /// The root that keeps the script alive. + pub fn as_handle(&self) -> &Handle { + &self.root + } +} + +/// A module (ECMA-262's Source Text Module Record or a synthetic one). +/// +/// The life of a module follows ECMA-262 §16.2.1.5, which the methods of +/// [`Scope`](crate::Scope) name: parse, load requested modules (the host +/// supplies each import through [`Host::load_imported_module`](crate::Host::load_imported_module)), +/// link, evaluate. `Module` is a root, `Clone`, `Send` and `Sync`. +/// +/// ```no_run +/// use clazel_js::{ModuleStatus, Realm, Runtime, Source}; +/// +/// /// Loads and runs a module whose imports the host can already resolve. +/// fn run_module(rt: &mut Runtime, realm: &Realm, text: &str) -> clazel_js::Result<()> { +/// let module = rt.scope(|scope| scope.parse_module(realm, Source::new("m.js", text)))?; +/// rt.scope(|scope| { +/// let loaded = scope.load_requested_modules(&module)?; +/// let _ = loaded; // a promise: settled when every import has been finished +/// Ok(()) +/// })?; +/// rt.run_jobs()?; +/// rt.scope(|scope| { +/// if scope.module_status(&module)? == ModuleStatus::Unlinked { +/// scope.link(&module)?; +/// } +/// let _done = scope.evaluate_module(&module)?; // a promise, for top-level await +/// Ok(()) +/// }) +/// } +/// ``` +#[derive(Clone, Debug)] +pub struct Module { + root: Handle, +} + +impl Module { + /// The root that keeps the module alive. + pub fn as_handle(&self) -> &Handle { + &self.root + } +} + +/// A module's state (ECMA-262's Cyclic Module Record `[[Status]]`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ModuleStatus { + /// Just created by `parse_module`. + New, + /// Its requested modules are loaded; not yet linked. + Unlinked, + /// `link` is running. + Linking, + /// Linked, not yet evaluated. + Linked, + /// Evaluation is running. + Evaluating, + /// Evaluation is waiting on top-level `await`. + EvaluatingAsync, + /// Evaluation finished, with a value or an error (kept by the module). + Evaluated, +} + +/// One import attribute: `with { type: "json" }` is `("type", "json")`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ImportAttribute { + /// The attribute's key. + pub key: String, + /// Its value. + pub value: String, +} + +/// What a module asks to import: ECMA-262's ModuleRequest Record. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ModuleRequest { + /// The module specifier, exactly as written in the source. + pub specifier: String, + /// The import attributes, in source order. + pub attributes: Vec, +} + +/// The code that asked for an import: the referrer of +/// [`Host::load_imported_module`](crate::Host::load_imported_module). Its +/// [host data](crate::Scope::host_defined) tells the host where to resolve +/// the specifier against. +#[derive(Clone, Copy, Debug)] +pub enum Referrer<'a> { + /// A classic script (a dynamic `import()` in one). + Script(&'a Script), + /// A module (a static `import` or a dynamic `import()` in one). + Module(&'a Module), + /// Neither: `import()` in `eval` or `Function` code outside any script + /// or module, which has only the realm. + Realm(&'a Realm), +} + +/// The engine's token for one pending import, passed to +/// [`Host::load_imported_module`](crate::Host::load_imported_module) and given +/// back to [`Scope::finish_loading_imported_module`](crate::Scope::finish_loading_imported_module). +/// +/// A host may finish it at once or on a later turn of its event loop, from +/// the same thread as the runtime. It must be finished exactly once; the type +/// is consumed by finishing it. Dropping it without finishing leaves the +/// module graph's load promise pending for ever, which is a bug in the host +/// but not unsafe. +#[derive(Debug)] +pub struct LoadPayload { + _pending: PhantomData<()>, +} diff --git a/crates/clazel-js/src/error.rs b/crates/clazel-js/src/error.rs new file mode 100644 index 000000000..35c25fef5 --- /dev/null +++ b/crates/clazel-js/src/error.rs @@ -0,0 +1,193 @@ +//! Errors and exceptions. + +use core::fmt; + +use crate::value::Handle; + +/// What every fallible call in this crate returns. +pub type Result = core::result::Result; + +/// The kinds of error object the engine can create (ECMA-262's native error +/// types). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ErrorKind { + /// `Error`. + Error, + /// `EvalError`. + EvalError, + /// `RangeError`. + RangeError, + /// `ReferenceError`. + ReferenceError, + /// `SyntaxError`. + SyntaxError, + /// `TypeError`. + TypeError, + /// `URIError`. + UriError, +} + +/// A value JavaScript threw, held by a rooted [`Handle`]. +/// +/// An `Exception` is what `catch` would see. It stays alive for as long as it +/// is held, whichever scope it was thrown in, so an embedder can report it +/// after the call that threw it has returned. +/// +/// ```no_run +/// use clazel_js::{Error, Realm, Scope, Source}; +/// +/// fn report(scope: &mut Scope<'_>, realm: &Realm) -> clazel_js::Result<()> { +/// match scope.eval_script(realm, Source::new("page.js", "null.x")) { +/// Err(Error::Thrown(exception)) => { +/// let report = scope.report(&exception)?; +/// println!("{}: {}", report.name, report.message); +/// Ok(()) +/// } +/// other => other.map(|_| ()), +/// } +/// } +/// ``` +#[derive(Clone, Debug)] +pub struct Exception { + value: Handle, +} + +impl Exception { + /// Wraps a value to be reported as thrown, for example to refuse a module + /// load in [`Scope::finish_loading_imported_module`](crate::Scope::finish_loading_imported_module). + /// The engine builds the ones it returns in [`Error::Thrown`]. + pub fn from_handle(value: Handle) -> Exception { + Exception { value } + } + + /// The thrown value, as a rooted handle. Turn it back into a + /// [`Local`](crate::Local) with [`Scope::local`](crate::Scope::local). + pub fn value(&self) -> &Handle { + &self.value + } +} + +/// A thrown error described in plain Rust types, for logging and for the +/// browser's "report the exception" step (which is HTML's, not the engine's; +/// the engine only supplies these fields). +/// +/// Built by [`Scope::report`](crate::Scope::report). It never runs user code: +/// a getter that throws while the report is built leaves that field empty. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct ErrorReport { + /// `name` of the thrown object, or `"Error"` if it has none. For a thrown + /// non-object, the type of the value, such as `"string"`. + pub name: String, + /// `message` of the thrown object, or the string conversion of a thrown + /// primitive. + pub message: String, + /// The call stack when the error object was created, innermost first. + /// Empty if the thrown value is not an error object. + pub stack: Vec, +} + +/// One frame of a call stack. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct StackFrame { + /// The function's name, or `None` for top-level code and anonymous + /// functions. + pub function: Option, + /// The `name` of the [`Source`](crate::Source) the frame's code came from. + pub source: String, + /// 1-based line, counting from the source's `start_line`. + pub line: u32, + /// 1-based column, in UTF-16 code units. + pub column: u32, +} + +/// Why a call failed. +/// +/// Exactly one variant, [`Thrown`](Error::Thrown), is a JavaScript value. +/// Every other variant is the engine's or the embedder's, and JavaScript +/// cannot observe or catch it. A native function passes both kinds back with +/// `?`. +/// +/// ```no_run +/// use clazel_js::{Error, Realm, Scope, Source}; +/// +/// fn run(scope: &mut Scope<'_>, realm: &Realm) { +/// match scope.eval_script(realm, Source::new("a.js", "while (true) {}")) { +/// Ok(_) => {} +/// Err(Error::Thrown(_)) => { /* the script threw; `catch` could have caught it */ } +/// Err(Error::Terminated) => { /* a Terminator stopped it; nothing in JS ran after */ } +/// Err(other) => eprintln!("engine error: {other}"), +/// } +/// } +/// ``` +#[derive(Clone, Debug)] +#[non_exhaustive] +pub enum Error { + /// JavaScript threw this value. Includes the `SyntaxError` for source + /// that does not parse, and the `RangeError`s the limits report + /// (heap, value stack, nested native calls, nesting depth, RegExp + /// backtracking). All of them can be caught by JavaScript. + Thrown(Exception), + /// A [`Terminator`](crate::Terminator) ended the evaluation. JavaScript + /// cannot catch it, and no `finally` block runs while it propagates. + Terminated, + /// The heap limit was reached and the engine could not even allocate the + /// `RangeError` to report it. This is the rare case; the ordinary report + /// of the heap limit is [`Thrown`](Error::Thrown). + OutOfMemory, + /// The handle names something that no longer exists, so using it would + /// have aliased a different object. The generation check caught it. + StaleHandle, + /// The handle, realm, script or module belongs to another + /// [`Runtime`](crate::Runtime). + WrongRuntime, + /// The value was not of the type the call needs. The text names what was + /// wanted, for example `"host object of this type"`. + WrongType(&'static str), + /// The data being asked for is already borrowed by a call further up the + /// stack (a host object's data while one of its own hooks runs). + Busy, + /// The contract is written but the body is not. The text names the call. + /// This variant exists only until item 7.8 builds the implementation. + NotImplemented(&'static str), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::Thrown(_) => f.write_str("JavaScript threw a value"), + Error::Terminated => f.write_str("terminated"), + Error::OutOfMemory => f.write_str("out of memory"), + Error::StaleHandle => f.write_str("stale handle"), + Error::WrongRuntime => f.write_str("handle from another runtime"), + Error::WrongType(what) => write!(f, "wrong type: wanted {what}"), + Error::Busy => f.write_str("already borrowed further up the stack"), + Error::NotImplemented(what) => write!(f, "not implemented: {what}"), + } + } +} + +impl std::error::Error for Error {} + +/// The body of every call whose implementation is still to come: names the +/// call, uses its arguments so the contract's parameter names stay as written, +/// and returns [`Error::NotImplemented`]. +macro_rules! not_implemented { + ($what:expr $(, $arg:expr)* $(,)?) => {{ + let _ = ($(&$arg,)*); + ::core::result::Result::Err($crate::Error::NotImplemented($what)) + }}; +} +pub(crate) use not_implemented; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn display_names_the_unimplemented_call() { + assert_eq!( + Error::NotImplemented("Runtime::new").to_string(), + "not implemented: Runtime::new" + ); + } +} diff --git a/crates/clazel-js/src/host.rs b/crates/clazel-js/src/host.rs new file mode 100644 index 000000000..6d4335782 --- /dev/null +++ b/crates/clazel-js/src/host.rs @@ -0,0 +1,477 @@ +//! The [`Host`] trait: everything ECMA-262 leaves to the host, and what the +//! engine needs from the world. +//! +//! The ECMA-262 section of each hook is not cited yet. Rule 5 asks for the +//! exact section, and the edition they refer to is pinned in item 7.1, which +//! has not run. Each hook is named by the abstract operation's name, which +//! does not change between editions; section numbers join when 7.1 pins one, +//! and 7.4 checks this list against the pinned edition's list of host hooks. + +use core::any::Any; +use std::hash::{BuildHasher, RandomState}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use crate::code::{LoadPayload, Module, ModuleRequest, Realm, Referrer}; +use crate::error::{ErrorKind, Result, not_implemented}; +use crate::native::Tracer; +use crate::scope::Scope; +use crate::value::{Handle, Local}; + +/// A queued unit of work for the event loop: a promise reaction, a +/// `FinalizationRegistry` cleanup, or a generic job. +/// +/// The engine makes a `Job` and gives it to the host to queue. Running it is +/// [`Scope::run_job`](crate::Scope::run_job), once, on the runtime's thread. A +/// `Job` is a root, so dropping one without running it only loses the work. +/// It is `Send` and `Sync` like a [`Handle`]. +#[derive(Debug)] +pub struct Job { + root: Handle, + realm: Option, +} + +impl Job { + /// The realm the job runs in, if the operation that made it names one. + pub fn realm(&self) -> Option<&Realm> { + self.realm.as_ref() + } + + /// The root that keeps the job's closure alive. + pub fn as_handle(&self) -> &Handle { + &self.root + } +} + +/// A callback and the host's data about it: ECMA-262's JobCallback Record. +/// +/// [`Host::make_job_callback`] makes one when a promise reaction or a +/// `FinalizationRegistry` is created, and [`Host::call_job_callback`] calls it +/// later. HTML uses the data to remember the "incumbent settings object". +#[derive(Debug)] +pub struct JobCallback { + callback: Handle, + host_defined: Option>, +} + +impl JobCallback { + /// A job callback with no host data. + pub fn new(callback: Handle) -> JobCallback { + JobCallback { + callback, + host_defined: None, + } + } + + /// Attaches the host's data. + #[must_use] + pub fn with_host_defined(mut self, data: Box) -> JobCallback { + self.host_defined = Some(data); + self + } + + /// The callback function. + pub fn callback(&self) -> &Handle { + &self.callback + } + + /// The host's data, if any. + pub fn host_defined(&self) -> Option<&(dyn Any + Send)> { + self.host_defined.as_deref() + } +} + +/// What [`Host::promise_rejection_tracker`] is told happened. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum RejectionOperation { + /// A promise with no handler was rejected. + Reject, + /// A handler was added to an already-rejected promise that had none. + Handle, +} + +/// Which dynamic code-from-strings feature is asking +/// [`Host::ensure_can_compile_strings`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DynamicCodeKind { + /// `eval(...)`; `direct` is true for a direct call that sees local scope. + Eval { + /// Whether this was a direct `eval`. + direct: bool, + }, + /// `Function(...)`. + Function, + /// `GeneratorFunction(...)`. + GeneratorFunction, + /// `AsyncFunction(...)`. + AsyncFunction, + /// `AsyncGeneratorFunction(...)`. + AsyncGeneratorFunction, +} + +/// The strings handed to [`Host::ensure_can_compile_strings`]. They are +/// UTF-16 because the program can build them with lone surrogates. +#[derive(Clone, Copy, Debug)] +pub struct CompileStrings<'a> { + /// Which feature is compiling code. + pub kind: DynamicCodeKind, + /// The parameter strings (empty for `eval`). + pub parameters: &'a [Vec], + /// The body, or for `eval` the code. + pub body: &'a [u16], +} + +/// The answer of [`Host::resize_array_buffer`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Resize { + /// The host did the resize. + Handled, + /// The host left it to the engine's default, which allocates. + Unhandled, +} + +/// What the embedder supplies. Every method has a default so a program that +/// needs none of the hooks can use [`DefaultHost`], and an embedder +/// overrides what it needs. +/// +/// - **Reentrancy.** A hook gets `&mut self` and a [`Scope`] and may call +/// back into the engine through that scope, including evaluating code. +/// While a hook runs, the host is lent to it, so [`Scope::host_mut`] from +/// code the hook runs gives [`Error::Busy`](crate::Error::Busy). +/// - **Errors.** A hook that returns `Err` makes the operation that called it +/// fail with that error, as ECMA-262 says for an abrupt completion from a +/// host-defined operation. `Err(Error::Terminated)` is passed on as is. +/// - **Threads.** `Host: Send`, which keeps [`Runtime`](crate::Runtime) +/// `Send`. A host that needs a value that is not `Send` keeps an id or a +/// channel in the host and the value elsewhere. +/// - **The event loop is the host's.** Nothing here runs a job: the hooks +/// queue, and the embedder calls [`Runtime::run_jobs`](crate::Runtime::run_jobs) +/// when its loop says to. +/// +/// The defaults named in each method are the engine's behaviour for a host +/// that says nothing. The browser's answers (HTML's, and 7.0(b)'s fixed +/// time zone offset and `en-US`) are the browser's, in `clazel-web`. +/// +/// ```no_run +/// use clazel_js::{ +/// Host, Job, Local, Module, ModuleRequest, LoadPayload, Referrer, RejectionOperation, +/// Result, Scope, +/// }; +/// +/// /// A host with a task queue of its own, rejection reporting, and a fixed clock. +/// struct PageHost { +/// tasks: Vec, +/// unhandled: Vec, +/// } +/// +/// impl Host for PageHost { +/// fn enqueue_promise_job(&mut self, _scope: &mut Scope<'_>, job: Job) -> Result<()> { +/// self.tasks.push(job); +/// Ok(()) +/// } +/// +/// fn promise_rejection_tracker( +/// &mut self, +/// _scope: &mut Scope<'_>, +/// _promise: Local<'_>, +/// operation: RejectionOperation, +/// ) { +/// self.unhandled.push(format!("{operation:?}")); +/// } +/// +/// fn now_ms(&mut self) -> f64 { +/// 1_700_000_000_000.0 +/// } +/// +/// fn random_u64(&mut self) -> u64 { +/// 4 // chosen by fair dice roll +/// } +/// } +/// ``` +pub trait Host: Any + Send { + // ---- Jobs ----------------------------------------------------------- + + /// `HostEnqueuePromiseJob(job, realm)`: queue a promise reaction. + /// + /// Default: append it to the engine's own queue, which + /// [`Runtime::run_jobs`](crate::Runtime::run_jobs) drains in order. A host + /// that overrides this takes over the order and calls + /// [`Scope::run_job`] itself. + fn enqueue_promise_job(&mut self, scope: &mut Scope<'_>, job: Job) -> Result<()> { + scope.enqueue_job_internal(job) + } + + /// `HostEnqueueGenericJob(job, realm)`. Default: as for promise jobs. + fn enqueue_generic_job(&mut self, scope: &mut Scope<'_>, job: Job) -> Result<()> { + scope.enqueue_job_internal(job) + } + + /// `HostEnqueueTimeoutJob(job, realm, milliseconds)`: run `job` after at + /// least `delay_ms`. Only a feature with timers in the language uses it + /// (`Atomics.waitAsync`, which the browser does not ship), so no + /// embedder is required to override it. Default: the engine's own queue, + /// with the delay ignored. + fn enqueue_timeout_job( + &mut self, + scope: &mut Scope<'_>, + job: Job, + delay_ms: f64, + ) -> Result<()> { + let _ = delay_ms; + scope.enqueue_job_internal(job) + } + + /// `HostEnqueueFinalizationRegistryCleanupJob(finalizationRegistry)`: a + /// registry has cells to clean up. The phase plan's list of hooks does not + /// name this one and 7.6 needs it (finalization callbacks are queued as + /// tasks); it is listed under the README's open questions. Default: the + /// engine's own queue. + fn enqueue_finalization_registry_cleanup_job( + &mut self, + scope: &mut Scope<'_>, + job: Job, + ) -> Result<()> { + scope.enqueue_job_internal(job) + } + + /// `HostMakeJobCallback(callback)`. Default: a [`JobCallback`] holding the + /// function and no host data. + fn make_job_callback( + &mut self, + scope: &mut Scope<'_>, + callback: Local<'_>, + ) -> Result { + Ok(JobCallback::new(scope.persist(callback))) + } + + /// `HostCallJobCallback(jobCallback, V, argumentsList)`. Default: call the + /// function with `this` and the arguments. + fn call_job_callback<'s>( + &mut self, + scope: &mut Scope<'s>, + callback: &JobCallback, + this: Local<'_>, + arguments: &[Local<'_>], + ) -> Result> { + let function = scope.local(callback.callback())?; + scope.call(function, this, arguments) + } + + // ---- Modules -------------------------------------------------------- + + /// `HostLoadImportedModule(referrer, moduleRequest, hostDefined, payload)`: + /// find (and fetch, if need be) the module `request` names, then call + /// [`Scope::finish_loading_imported_module`] with it or with the error. + /// It may do so before returning or on a later turn. + /// + /// ECMA-262 requires the same `(referrer, request)` to give the same module + /// every time or fail every time; keeping that is the host's job. + /// + /// Default: finish with a `TypeError` saying this host loads no modules. + fn load_imported_module( + &mut self, + scope: &mut Scope<'_>, + referrer: Referrer<'_>, + request: &ModuleRequest, + payload: LoadPayload, + ) -> Result<()> { + let _ = (referrer, request); + let error = scope.new_exception(ErrorKind::TypeError, "this host does not load modules")?; + scope.finish_loading_imported_module(payload, Err(error)) + } + + /// `HostGetSupportedImportAttributes()`: the attribute keys this host + /// understands (for example `"type"`). The engine refuses an import with + /// any other key with a `SyntaxError`. Default: none. Whether the pinned + /// edition has this hook is checked in 7.4. + fn supported_import_attributes(&self) -> &[&'static str] { + &[] + } + + /// `HostGetImportMetaProperties(moduleRecord)`: the properties of + /// `import.meta` for `module`, as (key, value) pairs. Default: none. + fn get_import_meta_properties<'s>( + &mut self, + scope: &mut Scope<'s>, + module: &Module, + ) -> Result)>> { + let _ = (scope, module); + Ok(Vec::new()) + } + + /// `HostFinalizeImportMeta(importMeta, moduleRecord)`: last chance to change + /// the `import.meta` object. Default: nothing. + fn finalize_import_meta( + &mut self, + scope: &mut Scope<'_>, + import_meta: Local<'_>, + module: &Module, + ) -> Result<()> { + let _ = (scope, import_meta, module); + Ok(()) + } + + // ---- Promises, code from strings, and the like ------------------------ + + /// `HostPromiseRejectionTracker(promise, operation)`: a promise was + /// rejected with no handler, or got its first handler after that. It + /// cannot fail or throw; the host records what it needs. Default: nothing. + fn promise_rejection_tracker( + &mut self, + scope: &mut Scope<'_>, + promise: Local<'_>, + operation: RejectionOperation, + ) { + let _ = (scope, promise, operation); + } + + /// `HostEnsureCanCompileStrings(calleeRealm, ...)`: may `eval` and the + /// `Function` constructors compile this text in `callee`? `Err` refuses, + /// and the error is what the call throws. Default: yes. + fn ensure_can_compile_strings( + &mut self, + scope: &mut Scope<'_>, + callee: &Realm, + strings: &CompileStrings<'_>, + ) -> Result<()> { + let _ = (scope, callee, strings); + Ok(()) + } + + /// `HostHasSourceTextAvailable(func)`: may `Function.prototype.toString` + /// show the source of `function`? Default: yes. + fn has_source_text_available(&mut self, scope: &mut Scope<'_>, function: Local<'_>) -> bool { + let _ = (scope, function); + true + } + + /// `HostEnsureCanAddPrivateElement(O)`: may a private element be added to + /// `object`? `Err` refuses. Default: yes. + fn ensure_can_add_private_element( + &mut self, + scope: &mut Scope<'_>, + object: Local<'_>, + ) -> Result<()> { + let _ = (scope, object); + Ok(()) + } + + /// `HostResizeArrayBuffer(buffer, newByteLength)`. Default: + /// [`Resize::Unhandled`]. + fn resize_array_buffer( + &mut self, + scope: &mut Scope<'_>, + buffer: Local<'_>, + new_byte_length: u64, + ) -> Result { + let _ = (scope, buffer, new_byte_length); + Ok(Resize::Unhandled) + } + + // ---- What the engine needs from the world ----------------------------- + + /// The current time in milliseconds since the Unix epoch, for + /// `Date.now()` and `new Date()`. Default: the system clock. + fn now_ms(&mut self) -> f64 { + match SystemTime::now().duration_since(UNIX_EPOCH) { + Ok(d) => d.as_secs_f64() * 1000.0, + Err(_) => 0.0, + } + } + + /// The local time zone's offset from UTC in milliseconds at `time_ms` + /// (ECMA-262's `LocalTZA`). `is_utc` says whether `time_ms` is a UTC time + /// or a local one to convert back. Default: 0, that is, UTC. + fn local_tza(&mut self, time_ms: f64, is_utc: bool) -> f64 { + let _ = (time_ms, is_utc); + 0.0 + } + + /// Random bits for `Math.random`. Required, because the engine has no + /// source of its own (rule 8: no randomness dependency). It need not be + /// cryptographic. [`DefaultHost`] draws from the standard library's + /// per-process random hash keys. + fn random_u64(&mut self) -> u64; + + /// The default locale, as a BCP 47 tag, for `toLocaleString` and friends. + /// Default: `"en-US"`. + fn default_locale(&self) -> &str { + "en-US" + } + + // ---- The collector ------------------------------------------------------ + + /// Reports the JavaScript values the host keeps alive: for the browser, + /// the wrapper of every node in a document's tree, the task queues and the + /// timers. Called during every collection. See [`Tracer`]. Default: + /// nothing. + fn trace_roots(&mut self, tracer: &mut Tracer<'_>) { + let _ = tracer; + } +} + +/// A host that says nothing: every hook has its default, and the clock and +/// randomness come from the standard library. +/// +/// Test262's runner, small tools and the examples use it. A real embedder +/// supplies its own. +/// +/// ```no_run +/// use clazel_js::{Config, DefaultHost, Limits, Runtime}; +/// +/// fn main() -> Result<(), clazel_js::Error> { +/// let _rt = Runtime::new(Config::new(Limits::unlimited()), DefaultHost::new())?; +/// Ok(()) +/// } +/// ``` +#[derive(Debug, Default)] +pub struct DefaultHost { + draws: u64, +} + +impl DefaultHost { + /// A default host. + pub fn new() -> DefaultHost { + DefaultHost { draws: 0 } + } +} + +impl Host for DefaultHost { + fn random_u64(&mut self) -> u64 { + // A fresh `RandomState` has per-process random keys; hashing a counter + // gives different bits each call. Good enough for `Math.random`, which + // ECMA-262 does not require to be unpredictable. + self.draws = self.draws.wrapping_add(1); + RandomState::new().hash_one(self.draws) + } +} + +// The engine's own queue is reached through this one call, which the default +// hooks use and an embedder that forwards to it may too. +impl Scope<'_> { + /// Appends `job` to the engine's own job queue, the one + /// [`Runtime::run_jobs`](crate::Runtime::run_jobs) drains. What the default + /// `enqueue_*` hooks do, and what an overriding host may call to forward. + pub fn enqueue_job_internal(&mut self, job: Job) -> Result<()> { + not_implemented!("Scope::enqueue_job_internal", job) + } + + /// Runs a job to completion. A job that throws returns the exception. + pub fn run_job(&mut self, job: Job) -> Result<()> { + not_implemented!("Scope::run_job", job) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn default_host_answers_for_the_world() { + let mut host = DefaultHost::new(); + assert_eq!(host.local_tza(0.0, true), 0.0); + assert_eq!(host.default_locale(), "en-US"); + assert!(host.now_ms() > 1.5e12); + assert_ne!(host.random_u64(), host.random_u64()); + assert!(host.supported_import_attributes().is_empty()); + } +} diff --git a/crates/clazel-js/src/lib.rs b/crates/clazel-js/src/lib.rs new file mode 100644 index 000000000..5a664c8d5 --- /dev/null +++ b/crates/clazel-js/src/lib.rs @@ -0,0 +1,46 @@ +//! The JavaScript engine's embedding API (phase-7.md item 7.8, "The engine as +//! a library"). +//! +//! **This crate is the contract and nothing else.** Every type and signature +//! is the proposed API, and every operation that needs the engine returns +//! [`Error::NotImplemented`]. The README states the rules in prose (threads, +//! rooting, termination, what is left out) and lists the open questions; the +//! doc comments here carry examples that compile (`no_run`, since nothing +//! runs yet). The contract is for review before the bindings build on it. +//! +//! The pieces, in the order a program meets them: +//! +//! - [`Runtime`], [`Config`], [`Limits`] and [`Terminator`]: one agent, its +//! limits, and the handle that stops it from another thread. +//! - [`Scope`]: every operation, inside [`Runtime::scope`]. Its values are +//! [`Local`]s; [`Handle`], [`Weak`] and [`Member`] hold them longer. +//! - [`Realm`], [`Source`], [`Script`] and [`Module`]: code to run. +//! - [`Scope::function`], [`Args`] and [`HostObject`]: Rust inside JavaScript. +//! - [`Host`]: what ECMA-262 leaves to the embedder, and [`DefaultHost`]. +//! - [`Error`], [`Exception`] and [`ErrorReport`]: what goes wrong. +//! +//! An embedder names this crate and no other engine crate. + +mod code; +mod error; +mod host; +mod native; +mod runtime; +mod scope; +mod value; + +pub use code::{ + ImportAttribute, LoadPayload, Module, ModuleRequest, ModuleStatus, Realm, RealmOptions, + Referrer, Script, Source, +}; +pub use error::{Error, ErrorKind, ErrorReport, Exception, Result, StackFrame}; +pub use host::{ + CompileStrings, DefaultHost, DynamicCodeKind, Host, Job, JobCallback, RejectionOperation, + Resize, +}; +pub use native::{Args, Callable, Exotic, HostObject, NativeFn, Tracer}; +pub use runtime::{Config, JitMode, Limits, Runtime, Terminator}; +pub use scope::{Resolvers, Scope}; +pub use value::{ + Handle, Key, Local, Member, PromiseState, PropertyDescriptor, ValueKind, Weak, WellKnownSymbol, +}; diff --git a/crates/clazel-js/src/native.rs b/crates/clazel-js/src/native.rs new file mode 100644 index 000000000..f18f0553b --- /dev/null +++ b/crates/clazel-js/src/native.rs @@ -0,0 +1,237 @@ +//! Native functions and host objects: how Rust code becomes part of a +//! JavaScript program. + +use core::any::Any; +use core::marker::PhantomData; + +use crate::error::Result; +use crate::scope::Scope; +use crate::value::{Key, Local, Member, PropertyDescriptor}; + +/// What a native function is called with. +/// +/// `this` and the arguments are [`Local`]s of the call's own scope, so the +/// function can use them freely and cannot keep them. A missing argument is +/// `undefined`, as for any JavaScript function. +/// +/// ```no_run +/// use clazel_js::{Args, Local, Result, Scope}; +/// +/// /// `add(a, b)` as JavaScript sees it. +/// fn add<'s>(scope: &mut Scope<'s>, args: &Args<'s>) -> Result> { +/// let a = scope.to_number(args.get(0))?; +/// let b = scope.to_number(args.get(1))?; +/// Ok(scope.number(a + b)) +/// } +/// ``` +#[derive(Clone, Copy, Debug)] +pub struct Args<'s> { + _scope: PhantomData<&'s ()>, +} + +impl<'s> Args<'s> { + /// The `this` value. + pub fn this(&self) -> Local<'s> { + // Implementation arrives with the frame layout (item 7.8). + Local::placeholder() + } + + /// How many arguments the caller passed. + pub fn len(&self) -> usize { + 0 + } + + /// Whether the caller passed no arguments. + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// Argument `index`, or `undefined` if the caller passed fewer. + pub fn get(&self, index: usize) -> Local<'s> { + let _ = index; + Local::placeholder() + } + + /// `new.target`: `Some` when the function was called with `new` (or by + /// `Reflect.construct`), and the constructor `new` was applied to, which + /// may be a subclass. `None` for an ordinary call. + pub fn new_target(&self) -> Option> { + None + } +} + +/// Whether a native function can be used with `new`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Callable { + /// An ordinary function: `new` throws a `TypeError`, and + /// [`Args::new_target`] is always `None`. What WebIDL calls an operation. + #[default] + Function, + /// A constructor: `new` calls it with [`Args::new_target`] set. A call + /// without `new` is the function's own business; it can throw. What + /// WebIDL calls an interface object. + Constructor, +} + +/// A request to run a native function body on behalf of the engine. Boxed +/// closures of this shape are what [`Scope::function`] takes. +/// +/// `Fn`, not `FnMut`: a native function can be re-entered through JavaScript +/// it calls, so mutable state it needs goes in a host object, in the +/// [`Host`](crate::Host), or behind a lock, and not in the closure. `Send` +/// because the [`Runtime`](crate::Runtime) is. +pub type NativeFn = dyn for<'s> Fn(&mut Scope<'s>, &Args<'s>) -> Result> + Send; + +/// An answer from an exotic hook: do what an ordinary object does, or here is +/// the answer. +#[derive(Clone, Copy, Debug)] +pub enum Exotic { + /// No special behaviour for this key: the engine continues as for an + /// ordinary object (looking at the object's own properties, then its + /// prototype). + Ordinary, + /// The embedder's answer. + Handled(T), +} + +/// The data of a host object, and the object's special behaviour. +/// +/// A host object is a JavaScript object that carries a Rust value, which the +/// embedder owns. This is how `clazel-webidl` builds a wrapper for a DOM +/// node: the wrapper is a JavaScript object, and its data says which node. +/// +/// - **Typed.** The data's type is the slot's type. [`Scope::host_data`] and +/// [`Scope::host_data_mut`] check it and give +/// [`Error::WrongType`](crate::Error::WrongType) for any other object, so a +/// method called on the wrong `this` is a defined error and never a +/// reinterpreted pointer. +/// - **Lifetime.** The data is dropped, on the runtime's thread, when the +/// collector frees the object or the runtime is dropped. +/// - **Tracing.** If the data refers to other JavaScript values it reports +/// them from [`trace`](HostObject::trace), using [`Member`]. The default +/// reports nothing. +/// - **Exotic behaviour.** The four hooks let a host object be what WebIDL +/// calls a legacy platform object: `NodeList[0]`, `HTMLCollection.byName`, +/// `localStorage.key`. Each defaults to [`Exotic::Ordinary`], and the +/// engine checks the result against ECMA-262's invariants for the internal +/// method (a non-configurable property cannot be reported missing, and so +/// on), throwing `TypeError` if the hook breaks them. While a hook runs the +/// object's data is lent to it and taken out of the object, so another +/// access to the same data gets [`Error::Busy`](crate::Error::Busy). +/// - **Which hooks exist** is an open question in the README: these four are +/// what WebIDL §3.9 and §3.10 appear to need and the list may grow. +/// +/// ```no_run +/// use clazel_js::{Exotic, HostObject, Key, Local, PropertyDescriptor, Result, Runtime, Scope}; +/// +/// /// The data of a `NodeList` wrapper: the ids of the nodes it holds. +/// struct NodeList { +/// nodes: Vec, +/// } +/// +/// impl HostObject for NodeList { +/// fn get_own_property<'s>( +/// &mut self, +/// scope: &mut Scope<'s>, +/// _this: Local<'s>, +/// key: Key<'_, 's>, +/// ) -> Result>>> { +/// let Key::Index(i) = key else { return Ok(Exotic::Ordinary) }; +/// let Some(id) = self.nodes.get(i as usize) else { +/// return Ok(Exotic::Handled(None)); +/// }; +/// let wrapper = scope.number(*id as f64); // a real binding makes the node's wrapper +/// Ok(Exotic::Handled(Some(PropertyDescriptor { +/// value: Some(wrapper), +/// writable: Some(false), +/// enumerable: Some(true), +/// configurable: Some(true), +/// ..PropertyDescriptor::default() +/// }))) +/// } +/// } +/// +/// fn make(rt: &mut Runtime) -> clazel_js::Result<()> { +/// rt.scope(|scope| { +/// let list = scope.new_host_object(None, NodeList { nodes: vec![1, 2] })?; +/// let n = scope.host_data::(list)?.nodes.len(); +/// assert_eq!(n, 2); +/// Ok(()) +/// }) +/// } +/// ``` +pub trait HostObject: Any + Send { + /// Reports every [`Member`] this data holds. See [`Tracer`]. + fn trace(&self, tracer: &mut Tracer<'_>) { + let _ = tracer; + } + + /// `[[GetOwnProperty]]` for `key`. + fn get_own_property<'s>( + &mut self, + scope: &mut Scope<'s>, + this: Local<'s>, + key: Key<'_, 's>, + ) -> Result>>> { + let _ = (scope, this, key); + Ok(Exotic::Ordinary) + } + + /// `[[DefineOwnProperty]]` for `key`. `Handled(true)` means it succeeded + /// and `Handled(false)` that it was refused. + fn define_own_property<'s>( + &mut self, + scope: &mut Scope<'s>, + this: Local<'s>, + key: Key<'_, 's>, + descriptor: PropertyDescriptor<'s>, + ) -> Result> { + let _ = (scope, this, key, descriptor); + Ok(Exotic::Ordinary) + } + + /// `[[Delete]]` for `key`. + fn delete_property<'s>( + &mut self, + scope: &mut Scope<'s>, + this: Local<'s>, + key: Key<'_, 's>, + ) -> Result> { + let _ = (scope, this, key); + Ok(Exotic::Ordinary) + } + + /// The extra own keys `[[OwnPropertyKeys]]` should list, which the + /// engine puts in front of the object's ordinary keys in the order + /// ECMA-262 fixes (indices first). `Handled` keys that are not strings, + /// symbols or indices are a `TypeError`. + fn own_property_keys<'s>( + &mut self, + scope: &mut Scope<'s>, + this: Local<'s>, + ) -> Result>>> { + let _ = (scope, this); + Ok(Exotic::Ordinary) + } +} + +/// The collector's marker, handed to [`HostObject::trace`] and +/// [`Host::trace_roots`](crate::Host::trace_roots). +/// +/// During a collection the engine calls each live host object's `trace`, and +/// the host's `trace_roots` once. Everything reported is treated as reachable +/// from there. Collection runs only at points the engine chooses (phase-7.md +/// item 7.6), and tracing cannot run JavaScript or allocate: the type gives it +/// no [`Scope`]. +#[derive(Debug)] +pub struct Tracer<'a> { + _collector: PhantomData<&'a mut ()>, +} + +impl Tracer<'_> { + /// Reports that the value is reachable. Reporting one twice is fine, and + /// reporting a stale one is ignored (the generation check). + pub fn mark(&mut self, member: Member) { + let _ = member; + } +} diff --git a/crates/clazel-js/src/runtime.rs b/crates/clazel-js/src/runtime.rs new file mode 100644 index 000000000..828048181 --- /dev/null +++ b/crates/clazel-js/src/runtime.rs @@ -0,0 +1,330 @@ +//! [`Runtime`], its [`Config`] and [`Limits`], and the [`Terminator`]. + +use core::cell::Cell; +use core::marker::PhantomData; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; + +use crate::error::{Result, not_implemented}; +use crate::host::Host; +use crate::scope::Scope; + +/// Every limit is the embedder's to set, and the engine has no default for +/// any of them (phase-7.md, "Limits and stopping"). +/// +/// A struct literal must name every field, so adding a limit later makes +/// every embedder choose a value. The numbers the browser picks are not in +/// this crate. Each limit has its own report, listed with the field. +/// +/// ```no_run +/// use clazel_js::Limits; +/// +/// // A test harness with limits generous enough never to matter, and one +/// // that is not: a small heap that is meant to be hit. +/// let relaxed = Limits::unlimited(); +/// let strict = Limits { +/// heap_bytes: 64 << 20, +/// ..relaxed +/// }; +/// # let _ = strict; +/// ``` +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Limits { + /// Heap size in bytes. An allocation that would pass it first runs a full + /// collection, then throws a `RangeError` if it still would. + pub heap_bytes: u64, + /// Size of the value-stack region in bytes. Passing it throws a + /// `RangeError` ("too much recursion"). + pub value_stack_bytes: u64, + /// How many native functions may be on the call stack at once, counting + /// built-ins that call back into JavaScript such as `Array.prototype.map`. + /// Passing it throws a `RangeError`. + pub native_depth: u32, + /// Bytes of generated machine code the JIT may hold. Passing it stops + /// compiling and leaves functions to the interpreter; it is not an error. + /// Ignored when [`JitMode::Off`]. + pub code_bytes: u64, + /// Entries in the RegExp matcher's backtrack stack. Passing it throws a + /// `RangeError` from the match, rather than hanging on `(a+)+b`. + pub regexp_backtrack_entries: u64, + /// Nesting depth of the parser (source text) and of `JSON.parse`. Passing + /// it throws a `SyntaxError` for source and a `RangeError` for JSON. + pub nesting_depth: u32, +} + +impl Limits { + /// Limits that no ordinary program reaches, for tests and for a runner + /// that wants the engine's behaviour without its limits getting in the + /// way. This is a named choice, not a default: nothing in the engine + /// calls it. + pub const fn unlimited() -> Limits { + Limits { + heap_bytes: u64::MAX, + value_stack_bytes: u64::MAX, + native_depth: u32::MAX, + code_bytes: u64::MAX, + regexp_backtrack_entries: u64::MAX, + nesting_depth: u32::MAX, + } + } +} + +/// Whether the JIT is on. Only [`Off`](JitMode::Off) exists until jit.md's +/// `clazel-jit` does; then a variant carrying a `CodeMapper` is added +/// (jit.md J.0(b)): the embedder's choice of how validated code becomes +/// executable. The interpreter is complete without it. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub enum JitMode { + /// Interpret only. + #[default] + Off, +} + +/// What a [`Runtime`] is built from. +/// +/// ```no_run +/// use clazel_js::{Config, JitMode, Limits}; +/// +/// let config = Config::new(Limits::unlimited()); +/// assert_eq!(config.jit, JitMode::Off); +/// ``` +#[derive(Clone, Copy, Debug)] +pub struct Config { + /// The limits. See [`Limits`]. + pub limits: Limits, + /// Whether to use the JIT. + pub jit: JitMode, +} + +impl Config { + /// A configuration with the given limits and the JIT off. + pub const fn new(limits: Limits) -> Config { + Config { + limits, + jit: JitMode::Off, + } + } +} + +/// A handle that stops a [`Runtime`] from another thread. +/// +/// - **How it works.** `terminate` sets a flag. The interpreter checks it at +/// loop back-edges and at calls, and JIT code checks it at the same points. +/// An evaluation that sees it ends with +/// [`Error::Terminated`](crate::Error::Terminated). +/// - **JavaScript cannot catch it.** `catch` does not run, and neither does +/// `finally`: running either would run JavaScript after being told to stop. +/// Native frames see `Err(Error::Terminated)` and must pass it on. One that +/// does not still stops at the next check, which raises it again. +/// - **It is sticky.** The flag stays set, so every later call into the same +/// `Runtime` also ends in `Terminated`, until [`Terminator::clear`] (an open +/// question in the README is whether a terminated runtime stays usable). +/// - **Cost.** The check is one relaxed atomic load. It is not a way to +/// interrupt a native function that is itself in a long loop; built-ins +/// check it too, and an embedder's native function should +/// [`Scope::check_terminated`] in a long loop. +/// - **It is the embedder's policy.** The browser still ends a stuck renderer +/// from outside, on the user's word (phase-7.md 7.0(g)), and may use this +/// later to keep the tab. +/// +/// A `Terminator` is `Clone`, `Send` and `Sync`. +/// +/// ```no_run +/// use std::thread; +/// use std::time::Duration; +/// use clazel_js::{Config, DefaultHost, Limits, Realm, Runtime}; +/// +/// fn run_for_a_second(rt: &mut Runtime, realm: &Realm) { +/// let terminator = rt.terminator(); +/// let watchdog = thread::spawn(move || { +/// thread::sleep(Duration::from_secs(1)); +/// terminator.terminate(); +/// }); +/// let _ = rt.scope(|scope| { +/// scope.eval_script(realm, clazel_js::Source::new("loop.js", "for (;;) {}"))?; +/// Ok::<(), clazel_js::Error>(()) +/// }); +/// let _ = watchdog.join(); +/// rt.terminator().clear(); +/// } +/// ``` +#[derive(Clone, Debug, Default)] +pub struct Terminator { + flag: Arc, +} + +impl Terminator { + /// Asks the runtime to stop. Safe to call from any thread, any number of + /// times. + pub fn terminate(&self) { + self.flag.store(true, Ordering::Relaxed); + } + + /// Whether `terminate` has been called and not cleared. + pub fn is_terminated(&self) -> bool { + self.flag.load(Ordering::Relaxed) + } + + /// Lets the runtime run again. Call it after an evaluation has returned + /// `Terminated`, never while one is running. + pub fn clear(&self) { + self.flag.store(false, Ordering::Relaxed); + } +} + +/// One ECMAScript agent: a heap, a job queue, limits and a [`Host`]. +/// +/// - **No global state.** Everything the engine knows lives in the `Runtime`, +/// with no `static` and no thread-local, so a process can hold many. +/// - **Threads.** A `Runtime` is `Send` and not `Sync`. It can move to another +/// thread between calls, and only one thread can use it at a time. The +/// browser runs one per renderer, on one thread, as phase-7.md 7.0(e) +/// decided. [`Terminator`] is the one piece usable from other threads. +/// `Host: Send` is what keeps this true, because the host lives inside. +/// - **Calls go through a scope.** [`Runtime::scope`] runs a closure with a +/// [`Scope`], and everything else is a method of that. +/// - **Dropping** frees the whole heap, runs each native closure's and host +/// object's destructor, and does not run any JavaScript (no finalizer). +/// +/// ```compile_fail +/// use clazel_js::Runtime; +/// +/// fn needs_sync() {} +/// +/// // Does not compile: a Runtime is not Sync. +/// fn check() { needs_sync::(); } +/// ``` +/// +/// ```no_run +/// use clazel_js::{Config, DefaultHost, Limits, RealmOptions, Runtime, Source}; +/// +/// fn main() -> Result<(), clazel_js::Error> { +/// let mut rt = Runtime::new(Config::new(Limits::unlimited()), DefaultHost::new())?; +/// let realm = rt.scope(|scope| scope.create_realm(RealmOptions::default()))?; +/// let sum = rt.scope(|scope| { +/// let value = scope.eval_script(&realm, Source::new("sum.js", "1 + 2"))?; +/// Ok(scope.as_number(value)) +/// })?; +/// assert_eq!(sum, Some(3.0)); +/// rt.run_jobs()?; +/// Ok(()) +/// } +/// ``` +/// +/// A `Runtime` moves to another thread as a whole: +/// +/// ```no_run +/// use clazel_js::Runtime; +/// +/// fn assert_send() {} +/// fn check() { assert_send::(); } +/// ``` +pub struct Runtime { + limits: Limits, + terminator: Terminator, + host: Box, + // `Cell` is `Send` and not `Sync`, which is the rule. + _not_sync: PhantomData>, +} + +impl Runtime { + /// Builds a runtime with no realms. The `host` is taken for the life of + /// the runtime; reach it again with [`Runtime::host_mut`] or, from inside + /// a native function, [`Scope::host_mut`]. + pub fn new(config: Config, host: impl Host) -> Result { + not_implemented!("Runtime::new", config, host) + } + + /// Runs `f` with a [`Scope`]. Every [`Local`](crate::Local) made inside is + /// rooted until `f` returns, and cannot leave it; what `f` returns must + /// not borrow from the scope. This is the only way in. + /// + /// `f` cannot call `scope` again, because it has no access to the + /// `Runtime`. Code that wants an inner scope uses [`Scope::nested`]. + pub fn scope(&mut self, f: impl for<'s> FnOnce(&mut Scope<'s>) -> R) -> R { + let mut scope = Scope::new(); + f(&mut scope) + } + + /// Runs queued jobs (promise reactions, generic jobs, finalization + /// callbacks) until the queue is empty, and returns how many ran. This is + /// a microtask checkpoint; the engine never decides when to run one. + /// + /// The queue is the engine's own unless the [`Host`] diverted it: + /// [`Host::enqueue_promise_job`] and its siblings default to appending to + /// it. A job that throws stops the run: the exception comes back as + /// `Err`, the jobs after it stay queued, and calling `run_jobs` again + /// continues with them. A [`Terminator`] stops it as it stops anything. + /// + /// ```no_run + /// use clazel_js::Runtime; + /// + /// fn checkpoint(rt: &mut Runtime) -> clazel_js::Result<()> { + /// // After a script returns, with the host's own tasks still to run: + /// let ran = rt.run_jobs()?; + /// println!("{ran} jobs"); + /// Ok(()) + /// } + /// ``` + pub fn run_jobs(&mut self) -> Result { + not_implemented!("Runtime::run_jobs") + } + + /// A handle that stops this runtime from another thread. Every call gives + /// a handle to the same flag. + pub fn terminator(&self) -> Terminator { + self.terminator.clone() + } + + /// The limits this runtime was built with. + pub fn limits(&self) -> Limits { + self.limits + } + + /// The host, between calls. Not available while a hook is running; there + /// the hook's own `&mut self` is the host. + pub fn host_mut(&mut self) -> &mut dyn Host { + &mut *self.host + } + + /// Bytes the heap holds now, live and not yet swept, for the embedder's + /// own accounting and for tests of [`Limits::heap_bytes`]. + pub fn heap_used(&self) -> Result { + not_implemented!("Runtime::heap_used") + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn is_send() {} + fn is_send_sync() {} + + #[test] + fn terminator_is_a_shared_sticky_flag() { + is_send_sync::(); + let a = Terminator::default(); + let b = a.clone(); + assert!(!a.is_terminated()); + b.terminate(); + assert!(a.is_terminated()); + b.terminate(); + assert!(a.is_terminated()); + a.clear(); + assert!(!b.is_terminated()); + } + + #[test] + fn runtime_is_send() { + is_send::(); + } + + #[test] + fn unlimited_is_the_largest_of_each() { + let l = Limits::unlimited(); + assert_eq!(l.heap_bytes, u64::MAX); + assert_eq!(l.native_depth, u32::MAX); + } +} diff --git a/crates/clazel-js/src/scope.rs b/crates/clazel-js/src/scope.rs new file mode 100644 index 000000000..e34c8dca0 --- /dev/null +++ b/crates/clazel-js/src/scope.rs @@ -0,0 +1,775 @@ +//! [`Scope`]: every operation on values, realms, code and objects. + +use core::any::Any; +use core::marker::PhantomData; + +use crate::code::{ + LoadPayload, Module, ModuleStatus, Realm, RealmOptions, Referrer, Script, Source, +}; +use crate::error::{Error, ErrorKind, ErrorReport, Exception, Result, not_implemented}; +use crate::host::Host; +use crate::native::{Args, Callable, HostObject}; +use crate::value::{ + Handle, Key, Local, Member, PromiseState, PropertyDescriptor, ValueKind, Weak, WellKnownSymbol, +}; + +/// The resolving functions of a promise made by [`Scope::new_promise`]. +/// +/// Held by the embedder until the work the promise stands for is done: a +/// fetch finishes, a timer fires. It is two [`Handle`]s, `Send` and `Sync`, +/// and settling uses [`Scope::resolve_promise`] and [`Scope::reject_promise`] +/// on the runtime's thread. Settling twice is a no-op, as for JavaScript's own +/// resolving functions. +#[derive(Clone, Debug)] +pub struct Resolvers { + resolve: Handle, + reject: Handle, +} + +impl Resolvers { + /// The `resolve` function. + pub fn resolve_function(&self) -> &Handle { + &self.resolve + } + + /// The `reject` function. + pub fn reject_function(&self) -> &Handle { + &self.reject + } +} + +/// Where all work on a [`Runtime`](crate::Runtime) happens, and the owner of +/// the lifetime `'s` that every [`Local`] it makes carries. +/// +/// A `Scope` exists inside [`Runtime::scope`](crate::Runtime::scope), inside +/// each native function and hook (which get one for their call), and inside +/// [`Scope::nested`]. All the engine's operations are methods of it, grouped +/// below. +/// +/// - **Rooting.** Each `Local` is rooted until its scope ends. A loop that +/// makes many temporary values uses `nested` per iteration so they are not +/// all held until the end. +/// - **Collection.** The collector runs only inside an operation that +/// allocates or that the embedder asks for ([`Scope::gc`]), never between +/// two lines of the embedder's own code, so no `Local` is ever seen half +/// moved. The heap does not move objects (phase-7.md 7.0(f)). +/// - **Errors.** Operations that can run JavaScript, and so throw, return +/// `Result`. Operations that cannot (making a number, reading a kind) do not. +/// +/// ```no_run +/// use clazel_js::{Key, Runtime}; +/// +/// fn sum_squares(rt: &mut Runtime, n: u32) -> clazel_js::Result { +/// rt.scope(|scope| { +/// let list = scope.new_array(0)?; +/// for i in 0..n { +/// // Temporaries die at the end of each pass, not at the end of the call. +/// scope.nested(|inner| { +/// let x = inner.number(f64::from(i) * f64::from(i)); +/// inner.set(list, Key::Index(i), x) +/// })?; +/// } +/// let length = scope.get(list, Key::from("length"))?; +/// Ok(scope.as_number(length).unwrap_or(0.0)) +/// }) +/// } +/// ``` +#[derive(Debug)] +pub struct Scope<'s> { + // Invariant in `'s`, so a `Local<'s>` cannot be coerced to another scope's. + _scope: PhantomData &'s ()>, +} + +impl<'s> Scope<'s> { + pub(crate) fn new() -> Scope<'s> { + Scope { + _scope: PhantomData, + } + } + + /// Runs `f` with an inner scope. The `Local`s `f` makes are released when + /// it returns, and cannot escape it. What `f` returns must be owned + /// (a [`Handle`], a number, an [`Exception`]); to keep a value, call + /// [`Scope::persist`] inside `f`. + pub fn nested(&mut self, f: impl for<'i> FnOnce(&mut Scope<'i>) -> R) -> R { + let mut inner = Scope::new(); + f(&mut inner) + } + + // ---- Holding values ---------------------------------------------------- + + /// Roots `value` beyond this scope. See [`Handle`]. + pub fn persist(&mut self, value: Local<'_>) -> Handle { + let _ = value; + Handle::placeholder() + } + + /// The value a handle names, as a `Local` of this scope. + /// [`Error::WrongRuntime`] if the handle is another runtime's, + /// [`Error::StaleHandle`] if its generation does not match. + pub fn local(&mut self, handle: &Handle) -> Result> { + not_implemented!("Scope::local", handle) + } + + /// A weak reference to `value`. See [`Weak`]. + pub fn downgrade(&mut self, value: Local<'_>) -> Weak { + let _ = value; + Weak::placeholder() + } + + /// The value, if it is still alive. `Ok(None)` once it has been collected. + pub fn upgrade(&mut self, weak: &Weak) -> Result>> { + not_implemented!("Scope::upgrade", weak) + } + + /// A [`Member`] for `value`, to store in a host object's data and report + /// from its `trace`. + pub fn member(&mut self, value: Local<'_>) -> Member { + let _ = value; + Member::placeholder() + } + + /// The value a member names. [`Error::StaleHandle`] if the owner did not + /// report it and it has been collected. + pub fn local_from_member(&mut self, member: Member) -> Result> { + not_implemented!("Scope::local_from_member", member) + } + + // ---- Making and reading primitive values ----------------------------- + + /// `undefined`. + pub fn undefined(&mut self) -> Local<'s> { + Local::placeholder() + } + + /// `null`. + pub fn null(&mut self) -> Local<'s> { + Local::placeholder() + } + + /// A Boolean. + pub fn boolean(&mut self, value: bool) -> Local<'s> { + let _ = value; + Local::placeholder() + } + + /// A Number. NaN is canonicalized, as the value encoding requires. + pub fn number(&mut self, value: f64) -> Local<'s> { + let _ = value; + Local::placeholder() + } + + /// A String from Rust text. + pub fn string(&mut self, value: &str) -> Local<'s> { + let _ = value; + Local::placeholder() + } + + /// A String from UTF-16 code units, which may hold lone surrogates that a + /// Rust `&str` cannot. This is the exact form JavaScript strings take, + /// and what WebIDL's `DOMString` and `USVString` conversions start from. + pub fn string_utf16(&mut self, units: &[u16]) -> Local<'s> { + let _ = units; + Local::placeholder() + } + + /// A BigInt from an `i64`. + pub fn bigint_from_i64(&mut self, value: i64) -> Local<'s> { + let _ = value; + Local::placeholder() + } + + /// A BigInt from a `u64`. + pub fn bigint_from_u64(&mut self, value: u64) -> Local<'s> { + let _ = value; + Local::placeholder() + } + + /// A new unique Symbol with an optional description. + pub fn new_symbol(&mut self, description: Option<&str>) -> Local<'s> { + let _ = description; + Local::placeholder() + } + + /// A well-known symbol. The same symbol in every call and every realm of + /// this runtime, as ECMA-262 says. + pub fn well_known_symbol(&mut self, symbol: WellKnownSymbol) -> Local<'s> { + let _ = symbol; + Local::placeholder() + } + + /// What kind of value this is. Never throws and never runs JavaScript. + pub fn kind(&self, value: Local<'_>) -> ValueKind { + let _ = value; + ValueKind::Undefined + } + + /// The Boolean, or `None` if the value is not one. + pub fn as_boolean(&self, value: Local<'_>) -> Option { + let _ = value; + None + } + + /// The Number, or `None` if the value is not one. + pub fn as_number(&self, value: Local<'_>) -> Option { + let _ = value; + None + } + + /// A String's UTF-16 code units, exactly. `Err(WrongType)` for a + /// non-string. + pub fn string_to_utf16(&self, value: Local<'_>) -> Result> { + not_implemented!("Scope::string_to_utf16", value) + } + + /// A String as Rust text, with each lone surrogate replaced by U+FFFD. + /// `Err(WrongType)` for a non-string. + pub fn string_to_string_lossy(&self, value: Local<'_>) -> Result { + not_implemented!("Scope::string_to_string_lossy", value) + } + + // ---- Conversions and tests (what WebIDL's conversions are built from) -- + + /// `ToBoolean`. Cannot throw. + pub fn to_boolean(&mut self, value: Local<'_>) -> bool { + let _ = value; + false + } + + /// `ToNumber`. Can throw: a Symbol, a BigInt, or an object whose + /// `valueOf` throws. + pub fn to_number(&mut self, value: Local<'_>) -> Result { + not_implemented!("Scope::to_number", value) + } + + /// `ToString`, as a String value. Can throw. + pub fn to_string(&mut self, value: Local<'_>) -> Result> { + not_implemented!("Scope::to_string", value) + } + + /// `ToObject`. Throws a `TypeError` for `undefined` and `null`. + pub fn to_object(&mut self, value: Local<'_>) -> Result> { + not_implemented!("Scope::to_object", value) + } + + /// `IsCallable`. + pub fn is_callable(&self, value: Local<'_>) -> bool { + let _ = value; + false + } + + /// `IsConstructor`. + pub fn is_constructor(&self, value: Local<'_>) -> bool { + let _ = value; + false + } + + /// `IsArray`. Throws for a revoked proxy. + pub fn is_array(&mut self, value: Local<'_>) -> Result { + not_implemented!("Scope::is_array", value) + } + + /// `IsStrictlyEqual` (`===`). + pub fn strict_equals(&self, a: Local<'_>, b: Local<'_>) -> bool { + let _ = (a, b); + false + } + + /// `SameValue` (`Object.is`). + pub fn same_value(&self, a: Local<'_>, b: Local<'_>) -> bool { + let _ = (a, b); + false + } + + /// `InstanceofOperator` (`value instanceof constructor`). Can throw. + pub fn instance_of(&mut self, value: Local<'_>, constructor: Local<'_>) -> Result { + not_implemented!("Scope::instance_of", value, constructor) + } + + // ---- Objects ------------------------------------------------------------ + + /// A new ordinary object, as `{}` in the current realm. + pub fn new_object(&mut self) -> Result> { + not_implemented!("Scope::new_object") + } + + /// A new Array of the given length, as `new Array(length)`. + pub fn new_array(&mut self, length: u32) -> Result> { + not_implemented!("Scope::new_array", length) + } + + /// A new Array holding these values. + pub fn new_array_from(&mut self, elements: &[Local<'_>]) -> Result> { + not_implemented!("Scope::new_array_from", elements) + } + + /// `Get(object, key)`. Runs getters and proxy traps, so can throw. + pub fn get(&mut self, object: Local<'_>, key: Key<'_, '_>) -> Result> { + not_implemented!("Scope::get", object, key) + } + + /// `Set(object, key, value, true)`: throws in the cases strict-mode + /// assignment throws (a read-only property, a frozen object). + pub fn set(&mut self, object: Local<'_>, key: Key<'_, '_>, value: Local<'_>) -> Result<()> { + not_implemented!("Scope::set", object, key, value) + } + + /// `HasProperty` (`key in object`). + pub fn has_property(&mut self, object: Local<'_>, key: Key<'_, '_>) -> Result { + not_implemented!("Scope::has_property", object, key) + } + + /// `DeletePropertyOrThrow`, but returning `false` for a refusal instead of + /// throwing, as sloppy-mode `delete` does. + pub fn delete_property(&mut self, object: Local<'_>, key: Key<'_, '_>) -> Result { + not_implemented!("Scope::delete_property", object, key) + } + + /// `DefinePropertyOrThrow`: `Object.defineProperty`. + pub fn define_property( + &mut self, + object: Local<'_>, + key: Key<'_, '_>, + descriptor: PropertyDescriptor<'_>, + ) -> Result<()> { + not_implemented!("Scope::define_property", object, key, descriptor) + } + + /// `GetPrototypeOf`. `null` is returned as the `null` value. + pub fn get_prototype_of(&mut self, object: Local<'_>) -> Result> { + not_implemented!("Scope::get_prototype_of", object) + } + + /// `SetPrototypeOf`: throws if the object refuses (not extensible, or a + /// cycle). + pub fn set_prototype_of(&mut self, object: Local<'_>, prototype: Local<'_>) -> Result<()> { + not_implemented!("Scope::set_prototype_of", object, prototype) + } + + /// `GetMethod(value, key)`: `Ok(None)` if the property is `undefined` or + /// `null`, a `TypeError` if it is anything else but callable. + pub fn get_method(&mut self, value: Local<'_>, key: Key<'_, '_>) -> Result>> { + not_implemented!("Scope::get_method", value, key) + } + + /// `Call(function, this, arguments)`. + pub fn call( + &mut self, + function: Local<'_>, + this: Local<'_>, + arguments: &[Local<'_>], + ) -> Result> { + not_implemented!("Scope::call", function, this, arguments) + } + + /// `Construct(constructor, arguments, newTarget)`; `new_target` of `None` + /// is the constructor itself. + pub fn construct( + &mut self, + constructor: Local<'_>, + arguments: &[Local<'_>], + new_target: Option>, + ) -> Result> { + not_implemented!("Scope::construct", constructor, arguments, new_target) + } + + /// Runs the iterator protocol over `iterable`, calling `f` with each value + /// until it returns `Ok(false)` or the iterator ends. If `f` returns `Err`, + /// or `Ok(false)`, the iterator is closed (`IteratorClose`) first. This is + /// the operation WebIDL's `sequence` and `iterable` conversions need. + /// + /// ```no_run + /// use clazel_js::Runtime; + /// + /// fn count(rt: &mut Runtime, iterable: &clazel_js::Handle) -> clazel_js::Result { + /// rt.scope(|scope| { + /// let iterable = scope.local(iterable)?; + /// let mut n = 0; + /// scope.iterate(iterable, |_scope, _item| { + /// n += 1; + /// Ok(true) + /// })?; + /// Ok(n) + /// }) + /// } + /// ``` + pub fn iterate( + &mut self, + iterable: Local<'_>, + f: impl for<'i> FnMut(&mut Scope<'i>, Local<'i>) -> Result, + ) -> Result<()> { + not_implemented!("Scope::iterate", iterable, f) + } + + // ---- Native functions and host objects ------------------------------------ + + /// A JavaScript function that runs `f`. + /// + /// `name` and `length` are the function's `name` and `length`. `callable` + /// says whether `new` works on it. `f` gets a fresh scope for the call, + /// the arguments, and returns the result or an [`Error`]. Panics in `f` + /// are not caught: the lints forbid them in this repository, and an + /// embedder that panics gets its own panic. + /// + /// ```no_run + /// use clazel_js::{Args, Callable, Key, Local, Result, Runtime, Scope}; + /// + /// fn install(rt: &mut Runtime, realm: &clazel_js::Realm) -> Result<()> { + /// rt.scope(|scope| { + /// let global = scope.global(realm)?; + /// let greet = scope.function("greet", 1, Callable::Function, |scope, args| { + /// let who = scope.to_string(args.get(0))?; + /// let who = scope.string_to_string_lossy(who)?; + /// Ok(scope.string(&format!("hello, {who}"))) + /// })?; + /// scope.set(global, Key::from("greet"), greet) + /// }) + /// } + /// ``` + pub fn function( + &mut self, + name: &str, + length: u32, + callable: Callable, + f: impl for<'a> Fn(&mut Scope<'a>, &Args<'a>) -> Result> + Send + 'static, + ) -> Result> { + not_implemented!("Scope::function", name, length, callable, f) + } + + /// Makes a function with [`Scope::function`] and defines it as a method + /// of `object`: writable, non-enumerable, configurable, as WebIDL + /// operations and built-in methods are. + pub fn define_method( + &mut self, + object: Local<'_>, + name: &str, + length: u32, + f: impl for<'a> Fn(&mut Scope<'a>, &Args<'a>) -> Result> + Send + 'static, + ) -> Result<()> { + not_implemented!("Scope::define_method", object, name, length, f) + } + + /// A new host object carrying `data`, with this prototype (`None` is + /// `null`). See [`HostObject`]. + pub fn new_host_object( + &mut self, + prototype: Option>, + data: impl HostObject, + ) -> Result> { + not_implemented!("Scope::new_host_object", prototype, data) + } + + /// The data of a host object of type `T`. [`Error::WrongType`] if the + /// value is anything else (another type of host object included), and + /// [`Error::Busy`] if one of its own hooks is running. + pub fn host_data(&self, object: Local<'_>) -> Result<&T> { + not_implemented!("Scope::host_data", object) + } + + /// As [`Scope::host_data`], mutably. + pub fn host_data_mut(&mut self, object: Local<'_>) -> Result<&mut T> { + not_implemented!("Scope::host_data_mut", object) + } + + /// `GetPrototypeFromConstructor(newTarget, ...)`: the `prototype` of + /// `new_target` if it is an object, else `fallback`. A constructor that + /// makes a host object calls this with its [`Args::new_target`] so that a + /// subclass (`class X extends Node`) gets its own prototype. + pub fn get_prototype_from_constructor( + &mut self, + new_target: Local<'_>, + fallback: Local<'_>, + ) -> Result> { + not_implemented!( + "Scope::get_prototype_from_constructor", + new_target, + fallback + ) + } + + /// The embedder's [`Host`] as its own type. [`Error::WrongType`] if the + /// host is another type, and [`Error::Busy`] while a hook of the host is + /// running (the hook already has the host as `&mut self`). + pub fn host_mut(&mut self) -> Result<&mut H> { + not_implemented!("Scope::host_mut") + } + + /// For a native function: ends the call with [`Error::Terminated`] if a + /// [`Terminator`](crate::Terminator) has been used. Call it in any native + /// loop that can run long. + pub fn check_terminated(&self) -> Result<()> { + not_implemented!("Scope::check_terminated") + } + + // ---- Errors --------------------------------------------------------------- + + /// A new error object of `kind` with `message`, as an [`Exception`] ready to + /// throw or to refuse a module load with. + pub fn new_exception(&mut self, kind: ErrorKind, message: &str) -> Result { + not_implemented!("Scope::new_exception", kind, message) + } + + /// The `Err` for throwing a new error: `return Err(scope.throw_error(...))`. + /// If creating the error object itself fails, that failure is returned. + pub fn throw_error(&mut self, kind: ErrorKind, message: &str) -> Error { + match self.new_exception(kind, message) { + Ok(exception) => Error::Thrown(exception), + Err(other) => other, + } + } + + /// The `Err` for throwing any value, for example a `DOMException` the + /// embedder made. + pub fn throw(&mut self, value: Local<'_>) -> Error { + Error::Thrown(Exception::from_handle(self.persist(value))) + } + + /// The value inside an exception, as a `Local` of this scope. + pub fn exception_value(&mut self, exception: &Exception) -> Result> { + self.local(exception.value()) + } + + /// Describes a thrown value. See [`ErrorReport`]. Reads `name`, `message` + /// and `stack` as data properties and does not call getters, so it cannot + /// run JavaScript or throw. + pub fn report(&mut self, exception: &Exception) -> Result { + not_implemented!("Scope::report", exception) + } + + // ---- Promises --------------------------------------------------------------- + + /// A new pending promise and its resolving functions. For an API that + /// returns a promise and settles it later (`fetch`). + /// + /// ```no_run + /// use clazel_js::{Handle, Resolvers, Runtime}; + /// + /// // `fetch()` returns the promise now and keeps the resolvers for later. + /// fn start_fetch(rt: &mut Runtime) -> clazel_js::Result<(Handle, Resolvers)> { + /// rt.scope(|scope| { + /// let (promise, resolvers) = scope.new_promise()?; + /// Ok((scope.persist(promise), resolvers)) + /// }) + /// } + /// + /// // The kernel answered; settle it, then let the reactions run. + /// fn finish_fetch(rt: &mut Runtime, resolvers: &Resolvers) -> clazel_js::Result<()> { + /// rt.scope(|scope| { + /// let response = scope.new_object()?; + /// scope.resolve_promise(resolvers, response) + /// })?; + /// rt.run_jobs()?; + /// Ok(()) + /// } + /// ``` + pub fn new_promise(&mut self) -> Result<(Local<'s>, Resolvers)> { + not_implemented!("Scope::new_promise") + } + + /// Calls the promise's `resolve` with `value`. If the value is a thenable + /// the promise follows it, as for any resolve. + pub fn resolve_promise(&mut self, resolvers: &Resolvers, value: Local<'_>) -> Result<()> { + not_implemented!("Scope::resolve_promise", resolvers, value) + } + + /// Calls the promise's `reject` with `reason`. + pub fn reject_promise(&mut self, resolvers: &Resolvers, reason: Local<'_>) -> Result<()> { + not_implemented!("Scope::reject_promise", resolvers, reason) + } + + /// `Promise.resolve(value)` in the current realm. + pub fn promise_resolve(&mut self, value: Local<'_>) -> Result> { + not_implemented!("Scope::promise_resolve", value) + } + + /// `PerformPromiseThen` on `promise` with these reactions (each a function + /// or `None`), returning the derived promise. This is how the embedder + /// continues after a promise it did not make, such as the one + /// [`Scope::evaluate_module`] returns. + pub fn promise_then( + &mut self, + promise: Local<'_>, + on_fulfilled: Option>, + on_rejected: Option>, + ) -> Result> { + not_implemented!("Scope::promise_then", promise, on_fulfilled, on_rejected) + } + + /// A promise's state now. Reading it never marks a rejection handled. + pub fn promise_state(&self, promise: Local<'_>) -> Result> { + not_implemented!("Scope::promise_state", promise) + } + + // ---- ArrayBuffers ------------------------------------------------------------ + + /// A new `ArrayBuffer` that owns `bytes`. + pub fn new_array_buffer(&mut self, bytes: Vec) -> Result> { + not_implemented!("Scope::new_array_buffer", bytes) + } + + /// An `ArrayBuffer`'s bytes. Empty for a detached one. The borrow ends + /// before any call that can run JavaScript, which could detach or resize it. + pub fn array_buffer_bytes(&self, buffer: Local<'_>) -> Result<&[u8]> { + not_implemented!("Scope::array_buffer_bytes", buffer) + } + + /// `DetachArrayBuffer(buffer, key)`: after it the buffer has length 0. + /// `key` must be the `ArrayBuffer`'s detach key if it has one, else a + /// `TypeError`. This is Test262's `$262.detachArrayBuffer`, and what + /// `postMessage` transfers and `structuredClone` use later. + pub fn detach_array_buffer(&mut self, buffer: Local<'_>, key: Option>) -> Result<()> { + not_implemented!("Scope::detach_array_buffer", buffer, key) + } + + // ---- Realms --------------------------------------------------------------------- + + /// `CreateRealm` plus `SetDefaultGlobalBindings`: a new realm with its own + /// built-ins. This is `$262.createRealm`. + pub fn create_realm(&mut self, options: RealmOptions) -> Result { + not_implemented!("Scope::create_realm", options) + } + + /// The realm of the function being run. Inside a native function, the + /// function's own realm; inside a hook, the realm of the code that + /// triggered it, if there is one. + pub fn current_realm(&mut self) -> Result { + not_implemented!("Scope::current_realm") + } + + /// The realm's global object. Add properties to it with [`Scope::set`] and + /// [`Scope::define_property`]; that is how an embedder installs `console` + /// or `window`. + pub fn global(&mut self, realm: &Realm) -> Result> { + not_implemented!("Scope::global", realm) + } + + /// Attaches the embedder's data to a realm (HTML's environment settings + /// object), replacing what was there. + pub fn set_realm_host_defined( + &mut self, + realm: &Realm, + data: Box, + ) -> Result<()> { + not_implemented!("Scope::set_realm_host_defined", realm, data) + } + + /// The data attached with [`Scope::set_realm_host_defined`]. + pub fn realm_host_defined(&self, realm: &Realm) -> Result> { + not_implemented!("Scope::realm_host_defined", realm) + } + + // ---- Scripts and modules ------------------------------------------------------------ + + /// `ParseScript`: compiles `source`. A syntax error is + /// [`Error::Thrown`] holding a `SyntaxError` of `realm`. + pub fn compile_script(&mut self, realm: &Realm, source: Source<'_>) -> Result