🤖 hazel-jit, for `dev`: a compiler from Hazel to JavaScript, with the tests that hold it to the interpreter's answers. This is the one PR that tracks the jit. The npm package's branch, #2857 (`hazeljs`), merges it rather than keeping a copy of its own.

## Executive summary

- **What it is.** hazel-jit compiles a complete Hazel program to JavaScript and runs that in place of the interpreter. Where it can't (a hole, a test, an error the interpreter would show), the interpreter runs the program as it does today, so an answer never changes.
- **Why.** Speed, toward 60 frames a second for small edits. Compiled ahead of time, the games of hazeljs-examples run 2,392 times as fast as on the interpreter (the geometric mean over 45 operations in 17 games). Gnome dig's step takes 82 ms on the interpreter and 0.28 ms through the jit.
- **What it changes in `dev`.** It adds new files, and 13 lines to two of `dev`'s, `Builtins.re` and `Transition.re`, for mixed mode. Nothing in the app turns hazel-jit on yet: the editor, the evaluator and the stepper run as before.
- **How it is checked.** Every evaluator test also runs compiled, where it compiles, and must give the interpreter's answer. Of the 289 checks, 234 compile; 211 of those give the interpreter's answer and none differs. The other 23 end where the interpreter's result is not a value, which the sweep doesn't compare. hazel-jit also has 13 tests of its own.
- **Who uses it.** The hazeljs npm package (#2857): its `Hazel.jit` and `Hazel.compile` are hazel-jit. And the games of hazeljs-examples, which keep their rules compiled ahead of time.
- **What to review.** The two hooks into the interpreter; the shapes compiled code gives values, which pages that keep compiled code depend on; and the list of what is left to the interpreter.

## Engineering summary

- **In and out.** The input is the elaborated term the interpreter would run, with the types the statics gave it. The output is JavaScript source: the body of a function of one argument, `$R`, the runtime (about 23 KB of source: equality, lists, numbers, the builtins). The caller makes it a function with `new Function` and calls it.
- **How the code is written.** Expressions all the way down. A `let`'s bindings are assigned, in a comma expression, to variables declared at the top of the enclosing function, so a `let` makes no closure. Every binding gets a JS name of its own (`x$12`), so shadowing can't clash. A builtin written in OCaml is the runtime's JS version of it; one written in Hazel (`List.map`) is compiled once, before the program.
- **Values.** Close to what a person would write in JavaScript: numbers, strings and booleans as themselves, a record as a plain object, a list as cells `{$h, $t}` (so `::` is O(1)), a constructor as `{$c, $v}` (the table below). An Int is exact, as the interpreter's is: a JS number while it is a safe integer, a BigInt past that. An SInt is 32 bits, each result checked. A field read `e.x` is the property itself, behind a check.
- **Calls and loops.** A function bound to a name whose parameter is a tuple pattern takes the parts as JS arguments, so a call with the tuple written out makes no array: `fire_at.$d(n, i)`. A recursive function's calls of itself in tail position are a `for (;;)` loop, so a long list doesn't overflow the stack. Every other caller still passes the tuple, to the function's one-argument form. A module's member is read as its own variable (`Common.pick` is `pick`), a constructor without an argument is one constant made once, and `==` against a number, string or boolean written out is `===`.
- **What is left to the interpreter.** By rule, not by gap: holes outside mixed mode (below), the stepper's filters, an operation the interpreter stops at with an error, undefined, and a run past its budget. For a form, the compiler raises `Unsupported(reason)`; at run time, the compiled run stops. Either way the interpreter's run is the answer.
- **Back to Hazel.** `HazelJitValue` turns a compiled value back into a Hazel value by the types the term records, or into a diff against the last answer.
- **Mixed mode.** The interpreter runs a program around its holes and calls its fully typed functions (whole types declared) compiled, as builtins made at run time. A call that can't finish compiled falls back to the interpreter, for that call alone.
- **Holes in mixed mode.** A hole in an argument crosses into compiled code as an opaque value and comes back as the very term; a function with a hole in its code compiles, the hole an opaque value too. Code that would look inside one (match it, add to it, branch on it) runs in a checked version that stops there, and that call falls back. An answer holding a hole carries the interpreter's casts, made by the interpreter's own code (`Ascriptions`). A list of 2,000 built with a hole, then its length, runs about 17 times as fast as on the interpreter, where before the hole sent the call back.
- **Speed on the tests.** Over the 208 evaluator programs that compile and agree, the median program runs 395 times as fast compiled, run after run. On a first run, with its JS parsed, it runs 6.9 times as fast; compiling all 208 took 65 ms, against the interpreter's 143 ms for their first runs.

## What it holds

| Part | Files | What it does |
|---|---|---|
| The compiler | `src/language/dynamics/HazelJit.re` | An elaborated term as the body of a JavaScript function of its runtime (`$R`), and the runtime's source. A form it does not compile raises `Unsupported` with the reason, and the caller runs the interpreter. |
| The values across | `src/language/dynamics/HazelJitValue.re` | A Hazel value into compiled code's shapes and back, by the types the compiled term records; a compiled program instantiated; an answer carried back as a diff against the last one. |
| Mixed mode | `src/language/dynamics/HazelJitMixed.re`, 5 lines in `Builtins.re`, 8 in `Transition.re` | The interpreter calls a program's fully typed functions compiled, as builtins made at run time, holes and all. Nothing in the app turns it on yet. |
| Tests | `test/Test_HazelJit.re`, `test/Test_HazelJit_Agree.re`, a hook in `test/evaluator/Test_Evaluator_Prelude.re` | Every evaluator test also run compiled (and mixed) where it compiles, compared with the interpreter's answer shape by shape; agreement on the language's forms, big Ints, invalid operations, strings, partial and mutual functions, the step limit, undefined, labels, Unicode, field reads, records whose labels look like the runtime's own keys, loops and JS arguments; values carried back; diffs; what is not compiled and why; mixed mode, holes in it carried and fallen back. |

## How compiled values look

| Hazel | Compiled JavaScript |
|---|---|
| A tuple whose every entry is labeled, `(x = 1, y = 2)` | A plain object, `{x: 1, y: 2}`, its keys in the type's order |
| Any other tuple, `(1, 2)` or `(1, y = 2)` | An array, carrying its labels under `Symbol.for("hazel-jit.labels")` |
| A list | `null`, or a cell `{$h, $t}` |
| A constructor, `Some(3)`; `None` | `{$c: "Some", $v: 3}`; `{$c: "None"}`, one constant made once for each constructor without an argument |
| A function | A JS function of one argument; a function of a tuple takes an array. A named function of a tuple pattern also has a direct form, `f.$d(a, b)`, its parts as JS arguments |

- A field read `e.x` compiles to the property itself, `e["x"]`, behind a check that `e` is an object holding `x` and not a list's cell. Anything else (a list of rows, the empty list, a value the interpreter would be stuck on) goes to the runtime's `$R.dot`, so the answer is the same.
- A label named `length` or `__proto__`, or starting with `$`, is kept as `$` and the label. So no record has the keys `$h`, `$t`, `$c` or `$v`, and a record is never taken for a cell or a constructor.
- `==` is `$R.eq`, which is small enough for the engine to inline: its first line compares two numbers, strings or booleans with `===`, and objects go on to `$R.eqo`. Floats compare with `===` directly.

These shapes are Matthew's decisions of 2026-11-24. Measured on the games as their pages play them, records as objects take 0.63 of the time that records as arrays took (the geometric mean over 14 games), with every answer the same.

## Beside other compilers to JavaScript

| Value | hazel-jit | ReScript 12 | Melange 5 | js_of_ocaml 5.9 |
|---|---|---|---|---|
| A list cell; the empty list | `{$h, $t}`; `null` | `{hd, tl}`; `0` | `{hd, tl}`; `0` | `[0, hd, tl]`; `0` |
| A record | an object by label | an object by field | an object by field | `[0, f1, f2]` |
| `Take(a, b, k)` | `{$c: "Take", $v: [a, b, k]}` | `{TAG: "Take", _0, _1, _2}` | `{TAG: 0, _0, _1, _2}` | `[0, a, b, k]` |
| `Some(t)`; `None` | `{$c: "Some", $v: t}`; `{$c: "None"}` | `t`; `undefined` | `t`; `undefined` | `[0, t]`; `0` |
| A function of two | a named one: `f.$d(a, b)`; else one argument, an array | `f(a, b)` | `f(a, b)` | `f(a, b)` |
| `i == 0` on Ints | `i === 0` against a literal; else `$R.eq(a, b)` | `i === 0` | `i === 0` | `0 === i` |
| A tail call | of itself: a loop; else a call | a loop | a loop | a loop |

hazel-jit's names: `$h` and `$t` are a list cell's head and tail, `$c` and `$v` a constructor's name and value, `$d` a named function's direct form, and `$R` the runtime compiled code is given. They begin with `$` because a record's label that does is kept under `$` and the label, so no record has these keys, and one key tells a cell or a constructor from a record. ReScript and Melange name a cell's parts `hd` and `tl`, and a constructor's `TAG`, `_0`, `_1`; js_of_ocaml uses arrays, the tag first.

hazel-jit's records, its calls of named functions and its loops now look like ReScript's and Melange's; its constructors and options do not yet. On one small rule (a Petri net's step), ReScript's and Melange's code runs about 4 times as fast as hazel-jit's (measured 2026-11-25), where hazel-jit's Ints are exact and every function counts a step for the run's budget.

## Where it comes from

The compiler and its tests come from the livelits line's `trial/794-games-aot` (the jit of #2817), ported to Jane Street Core, with the arms for livelit-only forms (`Quote`, `Unquote`, `Bind`, `Splice`, a module's `ModVal`) taken out. The livelit views compiled (`HazelJitRun`, `HazelJitDOM`) and their tests stay on the livelits line.

Since it opened:

- **Records as objects** (9ec865976d), above.
- **A recursive function's own capture**, undefined when the function was made, is bound again by its `FixF` on the way back (5ec4ff4307).
- **A pattern by position that meets a labeled entry** leaves the run to the interpreter (e0a5925f3b).
- **A recursive function's calls of itself in tail position are a loop** (50b70d5a40), its variables declared in each pass, so a closure keeps its pass's values.
- **A named function of a tuple pattern takes the parts as JS arguments** (43828037c9).
- **A constructor without an argument is one constant** (ae29353ff0), **a module's member is read as its own variable** (9dd8fce210), and **`==` against a literal is `===`** (0ce95a2e8f): together 0.95 of the jit's time on the games. With both, the games take 0.70 of the jit's time as their pages play them (the geometric mean over 14 games), every answer the same; nearly all of it is the arguments.

## Mixed mode, at its boundary

Mixed mode keeps the interpreter in charge, so holes, probes and the stepper work as they do, and calls a program's complete, fully typed functions compiled.

- **What is compiled.** A `let` at the top of the program that binds a function whose whole type is declared (`let f : A -> B = fun ...`), with no unknown in it. Each is compiled with the accepted functions before it, so it may call them. A function that names anything else is not compiled, and the reason is kept. A module's members run on the interpreter for now (below).
- **How it hooks in.** The program is rewritten before it runs: the interpreter still evaluates each such definition to its own closure, then hands it to a builtin made at run time, which gives back a second builtin, the compiled function. The interpreter's one change is to look builtins up in a table filled at run time, after its fixed one.
- **A call.** The argument is converted into compiled code's shapes. The compiled function runs under a budget (50 million calls or 1 s). The answer is read back by the declared result type, which is why the type must be declared: a JavaScript number does not say whether it was an Int or a Float. An answer that may hold a hole is cast to that type by the interpreter's own `Ascriptions`, so mixed mode's answer is the interpreter's, casts included.
- **Falling back, one call at a time.** If the argument will not convert, an operation is invalid (a division by zero), the budget runs out, or the answer will not convert back, the interpreter applies its own closure to the same argument. Evaluation has no effects, so running a call again is safe.
- **What the boundary costs.** Compiled functions call one another directly, so the crossing is paid only where interpreted code calls compiled code, in proportion to what crosses. On build 49: `fib(16)`, all compiled, 72.6 ms interpreted against 0.1 ms mixed; the Petri net rule 120.8 against 16.8 ms; but a one-line function called 500 times from an interpreted loop 22.4 against 27.9 ms, each crossing costing more than its work.
- **Compiled code never calls interpreted code.** A function that calls one the interpreter keeps is itself left to the interpreter, so the boundary is crossed one way only. One function that cannot compile keeps every function that calls it interpreted.
- **Holes cross unopened.** A hole in an argument crosses as an opaque value, its term kept aside. Compiled code may move it (return it, store it in a pair or a record, count a list holding it), and it converts back as the very term that went in, with its cast. Code that would look inside it (match a constructor, branch on it, `x + ?`) stops the call, which falls back, so the interpreter gives the indeterminate answer.
- **Functions as arguments.** A compiled function that passes compiled functions, or lambdas of its own, calls them directly in JavaScript. An interpreter's closure passed in from interpreted code crosses as an opaque value, as a hole does: carried, but calling it stops the call, which falls back. A function in an answer comes back as a Hazel closure when compiled code made it; a recursive one, or one it did not make, makes that call fall back. No test has a function-typed parameter yet.
- **Polymorphic functions.** Compiled code erases types: `typfun a -> e` compiles as `e`, a type application `f@<T>` as `f`, and one compiled function serves every type it is used at, as compiled code never looks at a type at run time. Mixed mode does not compile one, since a candidate's declared type must be an arrow at the top, and a `forall` is not. Reading an answer back at a type variable has no type to go by: across a page's boundary, a whole JavaScript number comes back an Int and any other a Float, so a polymorphic function used at Float could give back `2.0` as the Int `2`. No test covers a polymorphic function across that boundary.

## Types: errors, type holes and unknowns

Hazel is gradually typed: the interpreter runs code with type errors and unknown types, inserting casts and stopping at one that fails. Compiled code erases casts, so what it leaves to the interpreter is decided by where a cast could fail.

- **Static type errors.** The interpreter runs ill-typed code and stops at the failed cast. The editor compiles no program with a static error (the evaluator sweep's 30 ill-typed programs). The package's `Hazel.jit` and `Hazel.jitProgram` compile one anyway and return it with `ok: false` and the errors, leaving the choice to the page: Gnome world's page uses no rules with errors.
- **A type hole written, `?`, is a hole.** A program with one is not compiled ("a type hole"): a cast through it can fail at run time with no static error, as `f(([1.5, 2.5] : ?))` for `f` taking `[Int]` does, and compiled code, its types erased, cannot tell an Int from a Float.
- **An unknown type nobody wrote is compiled, and there compiled code can part from the interpreter.** `let f = fun x -> x + 1 in f(true)` has no static error, as `x`'s type is unknown. The interpreter stops at the failed cast (`true` is not an Int); compiled code answers `2`. The same happens inside a fully typed function, `let f : Bool -> Int = fun b -> let g = fun x -> x + 1 in g(b)`, so mixed mode's candidates can meet it too. The evaluator sweep has no such program. A fix to decide: compile a check where a value is cast out of an unknown type into a ground type (a Bool, a String, a list, a constructor: a `typeof` or a key test), stopping the run so that the interpreter answers. An Int and a Float through an unknown type stay alike, as both are JavaScript numbers, unless Floats are tagged.

## Where it differs from the interpreter on `dev`

- **SInt overflow.** hazel-jit stops a 32-bit SInt that overflows at `IntegerOverflow`; `dev`'s interpreter wraps it (2147483647 + 1 is -2147483648). SInt is to have 64 bits everywhere, with overflow an error (#2828). The jit's 64-bit SInt is on `trial/758-sint64-jit` and comes here with #2828. The evaluator tests have no such program, so the sweep does not meet it.
- **A cast out of an unknown type nobody wrote** is erased, so where the interpreter stops at the failed cast, compiled code runs on (`let f = fun x -> x + 1 in f(true)`: the interpreter's failed cast, compiled code's `2`). See *Types: errors, type holes and unknowns*.
- **A tuple with a label given twice** is not compiled, since keying it by its labels would lose one entry. The interpreter runs it, keeping both entries as `dev` has since #2472.

## Next, on this branch

- Mixed mode's types from the statics, not from annotations: `dev` lowers a module to lets whose patterns lose their annotations, so a module's members run on the interpreter in mixed mode for now.
- Holes beyond mixed mode: a whole program, a livelit's view and the package's `Hazel.jit` still refuse them. Multiholes and error holes, with their environment, stay the interpreter's.
- Values across without converting: in mixed mode, the interpreter keeps a compiled call's answer as compiled code holds it, converting only what it looks inside, so a value passed from one compiled function to another through interpreted code is never converted.
- The games' rules as test programs (hazeljs-examples, compiled whole).
- A check at each cast out of an unknown type into a ground type, so compiled code stops where the interpreter's cast fails.
- Polymorphic functions in mixed mode: the type at each use, from the type application or the statics, to read the answer back by; and a test of one across a page's boundary.
- Tests of a function-typed parameter in mixed mode, from compiled callers and from interpreted ones.
- 64-bit SInt, with #2828.

Tried and not kept: lists as cells plus array segments (`hazel-jit-lists`). On hazeljs-examples' seventeen games it cost about 8% ahead of time and 4% through the jit, all answers the same, so cells stay.

The design and the measurements are in Hazel reports: [report 54](https://matthewhammer.org/hazel/reports/054/#records-decide) (records, lists and holes), [report 55](https://matthewhammer.org/hazel/reports/055/) (holes in mixed mode), [report 63](https://matthewhammer.org/hazel/reports/063/) (every game, four ways) and [report 46](https://matthewhammer.org/hazel/reports/046/) (beside ReScript, Melange and js_of_ocaml).

🤖 Generated with [Claude Code](https://claude.com/claude-code)
