Commit graph

39 commits

Author SHA1 Message Date
Sebastian Herrlinger
6d7e96a399 refactor(codemode): make the Rust crate the language layer only
The crate becomes the Rust implementation of the reference's language layer (`src/language/`): its public API is
the Rust form of `Language` (`Runtime::make` with `globals(run)`, modules, limits and translation; `HostFunction`
for `Host.fn` with sync, async and sync-thenable types, idempotent, constructible and takes-functions;
`DurableFunction`; `Namespace`; `Failure` for `Host.fail` and `Host.missing`; `Run` with its metadata; programs,
suspend and resume; snapshots). Code Mode (tools, schemas, the catalog, `search`, OpenAPI, hooks, max tool calls,
extensions) is removed, and the language files move from `src/language/` to `src/`.

Host calls follow the reference's language runtime: arguments cross under the runtime's translation (functions and
promises fail the call unless dropped or awaited), a function from a result crosses back only to a function that
takes functions, async and durable calls start at the next handover, sync work can block (`Returned::Block`) or
stay pending (`Returned::Pending`), and a suspend is refused while a call that can't be detached runs. Namespace
paths carry their root label, and their `keys` may fail. Snapshots save the run's metadata and its calls by global
path, and restart them by resolving that path again.

The replays define the generators' host globals (`conformance/reference.rs` shares `tools` with
`conformance/reference.ts`): the cases, `host.json`, `boundary.json` and `streaming.json`. `tests/host.rs` mirrors
the reference's `test/language.test.ts`; the API tests are ported, and the Code Mode tests are removed.
2026-11-19 01:54:11 +01:00
kommander
54f0d1e41a feat(codemode): hold huge sparse arrays
The reference keeps an array's elements in a host JavaScript array, which
JavaScriptCore stores sparsely, so a[4294967294] = x works and makes the
length 4294967295. Here a write that far failed with 'Invalid array length'.

An array now turns sparse when a write lands past the longest dense array
(MAX_ARRAY_LEN): its items keep the dense prefix, the SPARSE object flag is
set, and its other elements and its length are its own properties, so
snapshots and reachability carry them unchanged. Element reads and writes,
in, hasOwnProperty, delete, keys, for-in, length (which makes it dense again
once short enough), push, pop, at, slice, includes, indexOf and lastIndexOf
work on it as in the reference, and the callback methods, reduce, flat and
flatMap visit only the elements it holds. Code that walks every element
makes the array dense first and fails with the reference's errors when it
is too long ('Invalid array length', 'Out of memory' for sort), where the
reference either fails or runs on for minutes. Logs show its first
elements. Arrays at most MAX_ARRAY_LEN long, every one the benchmarks make
among them, stay dense and take the same paths as before.

Setting length out of range and spreading too many values now say
'Invalid array length' without a period, as the reference does. Touches
object.rs (SPARSE), ops.rs (element and length paths, define, iteration),
convert.rs, host.rs, web.rs (structured clone), object.rs, buffer.rs.

The last nine test262 files leave rust-skipped.txt, which is now empty.
2026-11-18 18:56:11 +01:00
kommander
e10ecb8811 fix(codemode): read 2^32 - 1 and above on an array as plain keys
An array's numeric read took any integer as an element index, so a[2 ** 32 -
1], which is stored as a plain property, read through to the prototypes
and came back undefined. Only indexes below 2^32 - 1 are elements, as the
writes already knew. Touches ops.rs (get_elem).

Two test262 files leave rust-skipped.txt.
2026-11-18 18:56:11 +01:00
kommander
d0ea5e8e79 feat(codemode): keep lone surrogates in strings
Strings are UTF-8, which cannot hold a lone surrogate, so every one became
U+FFFD: '\ud800' === '\udc00' was true and s[0] + s.slice(1) lost the pair.
A string that is not well-formed UTF-16 now keeps its code units behind a
flag (Strings::wtf), and its text is a canonical carrier: UTF-8 in which
each lone surrogate is U+10FFFF followed by a private-use character that
encodes it, and a real U+10FFFF is doubled. Text equality stays string
equality, so comparisons, Map and Set keys and property keys need nothing
new, and every allocation decodes the carrier, so a high and a low
surrogate brought together by concatenation, repeat, padding or
replacement become their character.

Code that counts or cuts code units reads them through StrRef (length,
charCodeAt, slice, comparison, search, split); iteration, String.raw,
fromCharCode, JSON.parse escapes, literals and regex matches produce lone
surrogates; JSON.stringify and RegExp.escape write them as \u escapes;
isWellFormed, toWellFormed, encodeURI (URIError, with the reference's
message) and localeCompare see them. localeCompare weighs them as the
reference's ICU does, where ICU4X would weigh them as U+FFFD. URL,
URLSearchParams, TextEncoder and Buffer's UTF-8 take USVStrings, so a lone
surrogate becomes U+FFFD there, as in the reference; Buffer's latin1 and
utf16le take the code units.

At the host boundary the reference hands its strings over as they are; a
Rust host value is UTF-8, so results, tool arguments, logs and diagnostics
carry U+FFFD for a lone surrogate, the bytes the reference's own
TextEncoder writes for them. Text from the host has a real U+10FFFF
doubled on the way in. Snapshots save the carrier and restore it exactly.

Instructions (5 iterations) stay within 0.1% on all nine programs; JSON
round-trip 1922M -> 1923M, Map/Set 1021M -> 1017M, string building
717M -> 713M. Touches strings.rs, compiler.rs (literals), convert.rs
(JSON, host values), host.rs (host values), ops.rs (string iteration),
run.rs (diagnostics) and vm.rs (char_str).

Eight test262 files leave rust-skipped.txt.
2026-11-18 18:56:11 +01:00
kommander
2c721e5b69 feat(codemode): collate localeCompare like the reference's host
localeCompare used a case-folding heuristic that disagreed with the
reference on 634 of 4,841 sampled pairs (accents, punctuation, canonical
equivalence, scripts). It now uses ICU4X's root collation, which the
reference's host uses for its en-US default, and agrees on all of them.

Dependency: icu_collator 2.4 with compiled data (pure Rust, Unicode's
ICU4X). It adds 1,247,048 bytes to the stripped embed example
(4,785,968 -> 6,033,016; bench/RESULTS.md (d) updated); nearly all of that is the root collation table,
so generating data for the root locale alone saves under 1 KB.
2026-11-18 18:56:11 +01:00
kommander
493240ee71 fix(codemode): match the reference's Array methods on frozen arrays, callbacks and iteration
Mutating Array methods run the reference's check of what their first write
would hit: adding to a non-extensible array, deleting from a sealed one, or
writing a frozen one each fail with the reference's message, sealed arrays
no longer pop or shift, and reverse leaves a frozen array of fewer than two
items alone. sort checks its comparator first and leaves the array as it
was when the comparator throws; it used to empty it.

Callback methods of Array, Map, Set and Uint8Array.sort name themselves in
the reference's 'Array.map expects a function callback.' forEach, map,
filter, some, every, flatMap and reduceRight skip indexes a callback cut
off by shrinking the array, and includes and indexOf on an empty array
return before converting fromIndex.

Array.from checks its mapper first, maps an iterable as it reads it and
closes the iterator when the mapper throws (an endless iterator ran out of
memory), and rejects primitives and promises. Object.fromEntries reads its
entries one at a time, closes the iterator on a bad entry, and accepts only
entries without opaque references, like the reference. Array.prototype is
an array, and an arguments object is never frozen merely by being
non-extensible.

On top of the array holes: mutating methods check mutability once (push
returns at once for an array with no such flags), and an index read past an
array's end or at a hole finds Array.prototype's own items, which store an
index without interning it. Touches ops.rs (inherited_elem).
2026-11-18 18:56:11 +01:00
kommander
29915a5310 fix(codemode): assigning undefined fails like assigning a constant
As in the reference, `undefined = 12` and its compound, logical and destructuring forms throw "Cannot assign to constant 'undefined'." instead of a ReferenceError.

language/global-code/import.js fails in the reference as it does here (a relative import throws when it runs instead of a parse error), so it moves from rust-skipped.txt to the reference's skipped.txt.
2026-11-18 18:56:10 +01:00
kommander
03066b4ba3 fix(codemode): delete, arguments, await names and iterator errors match the reference
- delete: optional and parenthesized targets delete; an identifier fails when it runs; built-in constants and prototypes refuse; a function's name and length can be deleted; strings and nullish bases get the reference's errors; tool references refuse.
- arguments: delete leaves a hole, length is a hidden writable property, the binding can be reassigned, and iterating it reads its enumerable own values.
- await is a plain name at the top level unless an expression starts with it, and an escaped await is a label.
- A named function expression's own name is bound before its parameters, so their defaults see it read-only.
- Iterators that break the protocol get the reference's errors everywhere they are opened, stepped or closed, including async yield* over a non-iterable.
- Promise.all, allSettled, any and race reject when their input is not iterable or iterating it fails.
- An accessor in an object literal fails when the literal runs, and export is a parse error, as in the reference.

Drops 77 files from rust-skipped.txt.
2026-11-18 18:56:10 +01:00
kommander
1b65246dfe fix(codemode): let a function's name and length be deleted, and name bound functions
A function's own name and length are configurable in the reference:
deleting one leaves the inherited Function.prototype value ("" and 0), and
assigning still fails as read-only. Two object flags record the deletion,
and reads, 'in' and hasOwnProperty honour them; a frozen or sealed
function still refuses. bind now gives the bound function its own
'bound <name>' and the target's length less the bound arguments.

delete's errors read 'Cannot delete property 'k'.' everywhere, as in the
reference, for arrays and Uint8Array too. Touches object.rs (flags) and
ops.rs (get, has, has_own, delete).

25 test262 files leave rust-skipped.txt.
2026-11-18 18:56:10 +01:00
kommander
f304df0a4f fix(codemode): reject Promise combinators whose input cannot be iterated
Promise.all, allSettled, any and race threw synchronously when their
argument was not iterable or iterating it failed; like the reference they
now return a promise rejected with that error, and word the non-iterable
case as the reference does ('Promise.all expects a synchronous iterable,
received a number.').

GetIterator now uses the reference's messages for a Symbol.iterator that is
not a function or returns a non-object, in every place that iterates.
Touches ops.rs (get_iterator, get_async_iterator).

70 test262 files leave rust-skipped.txt.
2026-11-18 18:56:10 +01:00
kommander
ff6da3f34b fix(codemode): resolve \k to whichever duplicate named group matched
regress binds \k<name> to the first group of that name only. When a name is
duplicated, at most one of its groups participates and a back-reference to
a group that did not participate matches empty, so compile now rewrites
\k<name> to the back-references of every group of that name in sequence,
(?:\1\2). With named groups present, \k inside a class is a syntax error
in the reference, which regress accepted; it now throws too.

Three test262 files leave rust-skipped.txt.
2026-11-18 18:56:10 +01:00
kommander
e4c73711f3 feat(codemode): real array holes
Arrays hold holes from elisions, Array(n), delete, length and far writes. A hole is not an own property: reads and `in` fall through to the prototypes, keys and for-in skip it, and logs print it empty. Methods follow the reference: the callback methods skip indexes not in the array, the find methods read them live, sort puts holes last, flat drops them, and spreads and copies such as toReversed read them as undefined. Holes cross the extension boundary as holes.

Drops 40 files from rust-skipped.txt, and 15 stale entries from the reference's test262 skipped.txt that its runner passes.
2026-11-18 18:56:10 +01:00
kommander
b4c5085f80 test(codemode): drop test262 files that RegExp and tagged templates now pass together 2026-11-18 18:56:10 +01:00
kommander
01ba82d8a7 fix(codemode): one arguments object per call, keys converted once
A function makes its arguments object once, at entry, and arrows read
their enclosing function's; an index past the arguments is an ordinary
property. A computed key converts once in compound assignment, ++/--
and before an object literal's value is evaluated, and strings compare
by UTF-16 code units in every relational operator.
2026-11-18 18:56:10 +01:00
kommander
0f359cfd30 fix(codemode): bind programs as scripts and fix loop and parameter scoping
A program still parses as a module, for top-level await, but binds as a
script like the reference, so a top-level function and var may share a
name. A for...of/in head sees the loop's own bindings in their TDZ, a for
loop's first iteration gets its own copy of the loop bindings, and with
parameter expressions each parameter is in its TDZ until bound. A named
function expression's own name is read-only. Breaking out of for await
over an iterator without return() no longer restarts the program.
2026-11-18 18:56:09 +01:00
kommander
3fa2858c50 feat(codemode): add tagged templates
A tag is read like a callee, so a member tag keeps its receiver, and is
called with the site's strings array and the substitutions. The array
holds the cooked text, undefined for an invalid escape, and a read-only
raw array of the source text; each site makes it once per run. A
read-only assignment now reports the reference's message.
2026-11-18 18:56:09 +01:00
kommander
eddd08ca02 fix(codemode): reject circular values and Promise.race([]) like the reference
A member assignment, Array push, unshift, splice and fill, and
Object.assign throw a TypeError (an invalid data value) when the stored
value reaches its container through data objects, as the reference does
on purpose. Promise.race over an empty iterable rejects with the
reference's hint instead of never settling.
2026-11-18 18:56:09 +01:00
kommander
7a3d2e1fe0 feat(codemode): add async generators and for await
Async generator functions, for await...of and Symbol.asyncIterator, as
the reference has them: requests queue with their promises and run the
body when it waits for one, yield and return await their value, and a
sync iterable adapts to async with each value awaited and a rejection
closing it.

A generator's return() now runs the compiled return path after its
yield, so finally blocks and enclosing iterators close as for a return
statement. yield* forwards next, throw and return to its iterator.
Generator functions get their own prototype, so g() instanceof g holds.

run() hands its exit value back packed in one word: returning a two-word
Value stalled on store forwarding in short callbacks.
2026-11-18 18:56:09 +01:00
kommander
654615c894 fix(codemode): stop ToNumber panicking on a non-ASCII string
A string of three or more bytes whose first character is not ASCII sliced
inside that character while looking for a 0x/0o/0b prefix.
2026-11-18 18:56:09 +01:00
kommander
f4d4236f43 perf(codemode): resume generators on the dispatch loop
A generator now owns its value stack. Resuming it swaps that stack in and
pushes its boxed frame; yielding swaps back. Nothing is copied and run()
is not re-entered when for-of, array destructuring, spread, rest elements,
yield* or a direct next() call drives it. Spread and rest collect yields
without leaving the generator.

Closure cells now live in local slots and exception handlers on one VM
stack, so a frame carries no per-call vectors. Comparisons fuse with the
following conditional jump, a discarded yield skips its pop, and a TDZ
marker that is overwritten at once is dropped.

Array destructuring closes its iterator when a binding or default throws,
and a failed step no longer closes it.

generator iteration: 4.4 ms -> 2.7 ms median (reference 5.3 ms).
2026-11-18 18:56:09 +01:00
kommander
b43925d720 fix(codemode): match JavaScriptCore's Math.hypot
Every argument converts before infinities and NaN decide the result, so a
later argument's throw is not skipped, and the sum follows
JavaScriptCore's algorithm (libm for two values, a scaled sum for three,
a scaled fused running sum beyond), giving the reference's last bits.
2026-11-18 18:56:09 +01:00
kommander
ebb15aeb19 feat(codemode): add URI functions, toExponential, Math.sumPrecise, f16round and copyWithin
- encodeURI/encodeURIComponent/decodeURI/decodeURIComponent with the
  reference's URIError messages.
- Number formatting follows JavaScriptCore: toString(radix) ports its exact
  integer digits and shortest-fraction algorithm, toExponential and
  toPrecision round half up on the exact value, toFixed keeps the sign of
  a negative that rounds to zero, and number-to-string picks the even
  digit when two shortest forms tie. Range errors use the host messages.
- Math.sumPrecise sums exactly and rounds once; Math.f16round rounds
  straight from the double; Array.prototype.copyWithin.

Number-to-string and its tie rule live in value.rs, so integers from 2^53
up print their shortest digits instead of every digit.

copyWithin converts its arguments through ToPrimitive like the other Array methods. Number-to-string decides ties in 128-bit integer arithmetic. test262: the reference's skipped.txt drops three copyWithin files the reference passes.
2026-11-18 18:56:09 +01:00
kommander
00964d83de fix(codemode): reject non-object receivers in Object.prototype methods
hasOwnProperty, isPrototypeOf and propertyIsEnumerable now throw the
reference's TypeError for undefined, null, primitives and tool references
instead of answering false, valueOf and toLocaleString throw on null and
undefined, and a tool reference's toString tag is [object Object], all as
in the reference.

reference-gaps.txt drops the four Promise files that passed here only through the accepted undefined receiver.
2026-11-18 18:56:09 +01:00
kommander
5cdf1ddc7c feat(codemode): add Iterator helpers, WeakMap, WeakSet, groupBy and Set methods
Iterator with Iterator.from and the lazy helpers (map, filter, take, drop,
flatMap) and consumers (reduce, toArray, forEach, some, every, find),
closing their source on early exit; Map getOrInsert(Computed), Map.groupBy,
Object.groupBy, the Set composition methods over Set-like operands, and
WeakMap/WeakSet. Map and Set methods now reject each other's receivers,
Iterator.prototype.next rejects foreign receivers, and exhausted built-in
iterators stay done, as in the reference.

RegExp: the flag accessors are listed on RegExp.prototype, and patterns
without u or v are matched as code units, so astral literals match.
No new dependencies.

test262: the reference's skipped.txt drops twelve Iterator and Set files the reference itself passes, which pass here too. Built-in iterators report their JS tags ([object Array Iterator], [object Set Iterator]), as the reference now does.
2026-11-18 18:56:09 +01:00
kommander
98bcf108e3 feat(codemode): add Uint8Array, Buffer, TextEncoder, TextDecoder, atob and btoa
Uint8Array with JS byte semantics (wrapping writes, shared subarray views,
live iterators, the callback methods, base64 and hex), Node's Buffer over
it with its encodings, numeric reads and writes and Node error codes,
UTF-8 TextEncoder and streaming TextDecoder, and forgiving-base64 atob and
btoa. Also fixes Object.prototype.toLocaleString to call toString and adds
Array.prototype.toLocaleString. No new dependencies; the stripped embed
example grows from 3262504 to 3379344 bytes.

Uint8Array numeric arguments and byte values convert without consulting program methods, as the reference's coerceToNumber does.
2026-11-18 18:56:09 +01:00
kommander
2a7c0b5296 feat(codemode): add Date
The Date constructor in every form, Date.now/parse/UTC, the local and UTC
getters and setters with the reference's coercion order and invalid-date
rules, and the string forms: deterministic ISO toString, en-US UTC locale
strings, host-local toDateString/toTimeString, toUTCString. Date.parse
follows JavaScriptCore: the ISO format first, then the legacy formats.
Dates take the string hint for default ToPrimitive and serialize through
toJSON.

Local time follows the host zone (TZ, else /etc/localtime) through the
tz-rs crate (pure Rust TZif reader, no dependencies); with this commit's
Date code the stripped embed example grows from 3178872 to 3262504 bytes.
2026-11-18 18:56:09 +01:00
kommander
7dd5025216 feat(codemode): add String normalize, raw, isWellFormed and toWellFormed
normalize uses the unicode-normalization crate (pure Rust, the standard
NFC/NFD/NFKC/NFKD tables); the stripped embed example grows from 3047304
to 3178872 bytes. Program strings are UTF-8, so isWellFormed is always
true and toWellFormed returns its receiver. repeat and padStart report the
reference's limit errors.
2026-11-18 18:56:09 +01:00
kommander
fccbad7d9e feat(codemode): add RegExp and regex-aware String methods
Regular expression literals, the RegExp constructor with flags, lastIndex,
exec/test, RegExp.escape, and match, matchAll, search, replace, replaceAll
and split with regex patterns, replacement templates and function
replacers.

Adds the regress crate (pure Rust, ECMAScript regex semantics, UTF-16
matching); the stripped embed example grows from 2139576 to 3047304 bytes.

The RegExp pattern, exec/test input and lastIndex convert without consulting program methods, as the reference's coerceToString/coerceToNumber do. test262: the files this fixes leave rust-skipped.txt, and the reference's skipped.txt drops Array lastIndexOf 15.4.4.15-5-21, which the reference passes since its Array arguments go through ToPrimitive.
2026-11-18 18:56:09 +01:00
kommander
230d462289 fix(codemode): parse Unicode 17 identifiers with acorn 8.16 2026-11-18 18:56:08 +01:00
kommander
3dbee2a738 fix(codemode): convert Array arguments, lengths and sort elements through ToPrimitive
The integer arguments of the Array methods, length = object, and the elements a default sort compares call the program's own valueOf/toString, as do String.fromCharCode/fromCodePoint, JSON.parse, and the string iterator's receiver. repeat(NaN) is "", as ToIntegerOrInfinity makes NaN 0.
2026-11-18 18:56:08 +01:00
kommander
0c5a6a6c2b fix(codemode): let in find an array hole's inherited index
The fast path for an integer in an array answered false for a hole; it now answers only for a present element and leaves the rest to the prototype walk, so forEach, some, and reduce visit an index inherited from Array.prototype.
2026-11-18 18:56:01 +01:00
kommander
58579fc70e fix(codemode): match JS in built-in object details
Resolving functions are anonymous, Set.prototype.keys is values, built-in iterators report their kind (Array Iterator, Map Iterator, ...), AggregateError has no own message unless given one, and generator and async functions inherit from their own non-callable function prototypes.
2026-11-18 18:56:01 +01:00
kommander
d4bb17439f fix(codemode): delete on a primitive base is true unless the wrapper owns the key
delete "abc"[5] and delete (1).x are true, as they delete from the wrapper; a string's own index or length still throws in strict mode.
2026-11-18 18:56:01 +01:00
kommander
e70845f198 fix(codemode): evaluate the right side of o.x = v before checking o
PutValue checks the base, so null.x = f() calls f before it throws, and (1).x = f() surfaces f's throw.
2026-11-18 18:55:49 +01:00
kommander
3afec0de63 fix(codemode): evaluate new arguments before checking the constructor
EvaluateNew evaluates the callee and its arguments before IsConstructor, so an argument's side effects and throws come first. Bumps the compiler version, since NEW no longer emits a separate check.
2026-11-18 18:55:49 +01:00
kommander
2a932f1331 fix(codemode): convert functions, generators and iterators through ToPrimitive
Operators and built-in arguments now call their valueOf/toString like any other object, as JS does: fn + 1 is "[object Function]1" and -fn is NaN. Promises and tool references still reject, so a missing await cannot hide.
2026-11-18 18:55:16 +01:00
kommander
8bc1023f3d Merge the test262 runner into the host API work 2026-11-18 18:54:15 +01:00
kommander
e9164a18ce test(codemode): check test262 parity in both directions
The runner now checks the files in the reference's skipped.txt too: those
that pass here are gaps on the TypeScript side, listed with a category in
test262/reference-gaps.txt. The check fails when an unlisted one passes, a
listed one fails here or leaves the reference's skipped.txt, or the
reference's own runner, through test262/reference.ts, passes a listed one.
Each category says whether Rust really has the behaviour or passes through
a looser check where the reference is strict on purpose.
2026-11-18 18:54:08 +01:00
Sebastian
ee90bf2aa2 test(codemode): add a test262 parity runner for the Rust port
Runs the reference's pinned test262 file set, synced by the reference's own
script, with the reference harness semantics. test262/rust-skipped.txt lists
the files that fail here but pass in the reference; the runner fails on an
unlisted failure and on a listed file that passes.
2026-11-18 18:53:57 +01:00