Skip to content

DEMO: print TypeScript for TScert verification under experimental -bs-emit-ts - #9211

Open
cristianoc wants to merge 6 commits into
masterfrom
exp/emit-ts-2
Open

cristianoc wants to merge 6 commits into
masterfrom
exp/emit-ts-2

Conversation

@cristianoc

@cristianoc cristianoc commented Nov 4, 2026 •

Copy link
Copy Markdown
Collaborator

TScert: a sound core for TypeScript

Under the experimental -bs-emit-ts flag, the compiler writes a module as TypeScript (.res.ts, .mts for .mjs, .cts for .cjs) in place of JavaScript. The goal is ReScript programs whose generated code is verified by TScert, a checker for TypeScript that accepts a function only with a proof that it is type-safe.

Results

tests/build_tests/emit_ts compiles 15 ReScript modules with -bs-emit-ts — including a runnable 3-module Todo web app (TodoModel + TodoView + TodoApp, zero runtime-dts/ contracts) and a 2-module recursive AST/evaluator (Expr + Eval):

  • tsc --strict: 0 diagnostics (tsc.txt is empty)
  • TScert (single-pass 0406f7e50, 2026-11-24): 15/15 modules, 95/95 units verified (36/36 units in the Todo app)
  • Run the Todo app directly on Node 26 (type-stripped ESM, no bundler):
    node tests/build_tests/emit_ts/todo-server.mts
Module What it exercises Units verified
TodoModel.res → TodoModel.res.ts Todo domain types (priority, filter, todo, appState), immutable CRUD, search, counts (0 runtime-dts/) 16/16
TodoView.res → TodoView.res.ts Styled HTML/CSS page rendering, HTML escaping, filter tabs, priority pills, search bar (0 runtime-dts/) 7/7
TodoApp.res → TodoApp.res.ts Variant-driven HTTP router, query decoding, option<int> ID parser, JSON serialization, (state, req) => (state, res) (0 runtime-dts/) 13/13
Expr.res → Expr.res.ts Recursive AST, tail recursion, nested-match constant folding, export const 5/5
Eval.res → Eval.res.ts Cross-module .res value/type imports, result, @unboxed & poly variants, ref + while/for loops, array writes, mutable records 8/8
Memo.res → Memo.res.ts dict<option<int>> + Option.getOr over nested option markers 2/2
NestMatch.res → NestMatch.res.ts Nested option pattern matching (Some(None), Some(Some(x))) & polymorphic overloads 5/5
Nest.res → Nest.res.ts Nested options, option<unit>, polymorphic option overloads, marker-keyed record 9/9
Arith, Arr, Gen, Opt, OptArg, Rec, Shape Arithmetic, arrays, generics, options, optional labelled args, records, tagged variants 30/30

Examples

1. Runnable 3-module Todo web app (TodoModel.res + TodoView.res + TodoApp.res)

ReScript + TScert verified Todo web app

The entire application core — domain model, priority cycling, filtering, search, HTML escaping, styled page rendering, query decoding, and variant-driven routing — is verified pure ReScript behind a 33-line Node HTTP adapter (todo-server.mts).

Source excerpts:

// TodoModel.res
type priority = Low | Medium | High
type filter = All | Active | Completed
type todo = {id: int, title: string, done: bool, priority: priority}
type appState = {nextId: int, todos: array<todo>}

let nextPriority = (p: priority): priority =>
  switch p {
  | Low => Medium
  | Medium => High
  | High => Low
  }

// TodoApp.res
let handleRequest = (state: TodoModel.appState, req: request): (TodoModel.appState, response) =>
  switch parseRoute(req.method, req.path) {
  | Home(filter, query) => (
      state,
      {status: 200, contentType: "text/html; charset=utf-8", body: TodoView.renderPage(state, filter, query)},
    )
  | GetTodo(id) =>
    switch TodoModel.findTodo(state.todos, id) {
    | Some(todo) => (state, jsonResponse(200, todoJson(todo)))
    | None => (state, textResponse(404, "not found"))
    }
  | Toggle(id) =>
    let next = TodoModel.toggleTodo(state, id)
    (next, jsonResponse(200, todosJson(next.todos)))
  ...
  }

Generated TypeScript excerpts (TodoModel.res.ts + TodoApp.res.ts):

// TodoModel.res.ts
export type priority = "Low" | "Medium" | "High";
export type filter = "All" | "Active" | "Completed";
export type todo = {
  readonly id: number;
  readonly title: string;
  readonly done: boolean;
  readonly priority: priority
};
export type appState = { readonly nextId: number; readonly todos: todo[] };

export function nextPriority(p: priority): priority {
  switch (p) {
    case "Low" : return "Medium";
    case "Medium" : return "High";
    case "High" : return "Low";
  }
}

// TodoApp.res.ts
import * as TodoView from "./TodoView.res.ts";
import * as TodoModel from "./TodoModel.res.ts";
import type {appState as TodoModel_appState} from './TodoModel.res.ts';

export function handleRequest(state: TodoModel_appState, req: request): [TodoModel_appState, response] {
  ...
  switch (id.TAG) {
    case "Home" :
      return [
        state,
        {
          status: 200,
          contentType: "text/html; charset=utf-8",
          body: TodoView.renderPage(state, id._0, id._1)
        }
      ];
    case "GetTodo" :
      let todo = TodoModel.findTodo(state.todos, id._0);
      if (todo !== undefined) {
        return [state, { status: 200, contentType: "application/json; charset=utf-8", body: todoJson(todo) }];
      } else {
        return [state, { status: 404, contentType: "text/plain; charset=utf-8", body: "not found" }];
      }
    ...
  }
}

2. Multi-module AST and evaluator (Expr.res + Eval.res)

Source excerpts:

// Expr.res
type rec expr = Lit(int) | Var(string) | Neg(expr) | Bin(op, expr, expr)

let zero = Lit(0)

let rec unwrapNeg = (e: expr): expr =>
  switch e {
  | Neg(Neg(inner)) => unwrapNeg(inner)
  | _ => e
  }

// Eval.res
let lookup = (env: array<binding>, target: string): option<int> => {
  let found = ref(None)
  let i = ref(0)
  while i.contents < Array.length(env) && found.contents == None {
    switch env[i.contents] {
    | Some(b) if b.name == target => found := Some(b.value)
    | _ => ()
    }
    i := i.contents + 1
  }
  found.contents
}

Generated TypeScript (Expr.res.ts + Eval.res.ts):

// Expr.res.ts
export function unwrapNeg(_e: expr): expr {
  while (true) {
    let e = _e;
    if (e.TAG !== "Neg") {
      return e;
    }
    let inner = e._0;
    if (inner.TAG !== "Neg") {
      return e;
    }
    _e = inner._0;
    continue;
  };
}

export const zero: expr = { TAG: "Lit", _0: 0 };

// Eval.res.ts
import * as Expr from "./Expr.res.ts";
import type {expr as Expr_expr} from './Expr.res.ts';

export function lookup(env: binding[], target: string): (undefined | number) {
  let found: (undefined | number) = undefined;
  let i: number = 0;
  while (i < env.length && found === undefined) {
    let b = env[i];
    if (b !== undefined && b.name === target) {
      found = b.value;
    }
    i = i + 1 | 0;
  };
  return found;
}

3. Nested options and polymorphic overloads (NestMatch.res → NestMatch.res.ts)

Some(None) isn't undefined: the nested-option encoding and the type -bs-emit-ts prints
// NestMatch.res
let getOr = (o: option<'a>, d: 'a) =>
  switch o {
  | Some(v) => v
  | None => d
  }

let inner = (o: option<option<int>>) =>
  switch o {
  | Some(Some(n)) => n
  | Some(None) => -1
  | None => 0
  }
// NestMatch.res.ts
import * as Primitive_option from "@rescript/runtime/lib/es6/Primitive_option.mjs";

export function getOr<a extends string | number | boolean | bigint>(o: (undefined | a), d: a): a;
export function getOr<a extends string | number | boolean | bigint>(o: (undefined | (
    (undefined | a)
  | { readonly BS_PRIVATE_NESTED_SOME_NONE: 0 })), d: (undefined | a)): (undefined | a);
export function getOr<a extends string | number | boolean | bigint>(o: (undefined | (
    (undefined | a)
  | { readonly BS_PRIVATE_NESTED_SOME_NONE: 0 })), d: (undefined | a)): (undefined | a) {
  if (o !== undefined) {
    return Primitive_option.valFromOption(o);
  } else {
    return d;
  }
}

export function inner(o: (undefined | (
    (undefined | number)
  | { readonly BS_PRIVATE_NESTED_SOME_NONE: 0 }))): number {
  if (o === undefined) {
    return 0;
  }
  let n = Primitive_option.valFromOption(o);
  if (n !== undefined) {
    return n;
  } else {
    return -1;
  }
}

Implementation details

What is printed

  • Each top-level function and its parameters (including tail-call lowered _param parameters) are annotated from the typed tree (Js_ts_collect in compiler/driver, read by the JS printer through Js_ts_annot in compiler/backend): export function f(a: T): R. Types come from genType's translation: records become object types (with readonly on immutable fields), tagged variants become tagged unions, and @unboxed and polymorphic variants become unions.
  • Immutable top-level non-function bindings print as export const x: T = …, preserving annotations across coercion renames.
  • Same-package .res imports use the emitted TypeScript suffix (.res.ts, .mts, .cts), and types referenced from other modules emit import type {t as Mod_t} from './Mod.res.ts'.
  • Local bindings stay unannotated except mutable (property = Variable), uninitialized, or undefined-initialized locals (including SROA-unboxed ref(...)), which retain = undefined where applicable and carry their monomorphic type so string/variant literals do not widen.
  • A polymorphic function declares its type parameters, with one name per type variable across its parameters and result: second<a, b>(_x: a, y: b): b.
  • An optional labelled argument after the last mandatory one prints as byOpt?: number. An earlier one prints fromOpt: undefined | number, because TypeScript requires every parameter after an optional one to be optional.
  • A top-level binding exported under its printed name (excluding default, including converted reserved names such as $$eval) prints inline as export function or export const.
  • A function whose body is only return; keeps the statement, which TypeScript requires when the result type is other than undefined, void or any.

The option type

undefined | T describes option<T> exactly only when T is never undefined. The runtime represents Some(None) as a marker object {BS_PRIVATE_NESTED_SOME_NONE: 0}, one level deeper per nesting. The backend prints:

ReScript TypeScript
option<int>, option<string>, option<record> undefined | T
option<option<int>>, option<unit> undefined | T | { readonly BS_PRIVATE_NESTED_SOME_NONE: 0 }
option<option<option<int>>> undefined | number | { …: 0 } | { …: 1 }
option<'a> in a type declaration, abstract payload, or payload that may own BS_PRIVATE_NESTED_SOME_NONE undefined | T | { readonly BS_PRIVATE_NESTED_SOME_NONE: number }
Polymorphic function over option<'a> One overload per nesting depth ('a := option^k<a>, k = 0, 1), with a extends string | number | boolean | bigint; implementation carries the deepest instance

On a primitive, Primitive_option.some and valFromOption return their argument, so each overload holds without assuming who owns BS_PRIVATE_NESTED_SOME_NONE. A payload that may own that key (a record or inline record with a field of that runtime name, an object type, or a variant containing one) prints marker depth number. Polymorphic option code at a record payload, or nested deeper than the printed overloads, is refused by tsc and never falsely accepted.

TScert

Verified with TScert on single-pass at 0406f7e50 (2026-11-24): all 15 modules (95/95 units) verify end to end. To reproduce after building TScert (make setup && make build):

node pipeline/verify-source.mts <rescript>/tests/build_tests/emit_ts/src/TodoApp.res.ts \
  --project <rescript>/tests/build_tests/emit_ts

What a verification means: for inputs of the declared types, the function does not get stuck and does not return a value outside its result type. TScert takes imports at their declared types, so modules importing runtime helpers assume the hand-written declarations in runtime-dts/ (Primitive_int, Primitive_option, Stdlib_Option, Stdlib_Array); the three Todo web app modules rely on none of them.

Open

  • Polymorphic option code at record payloads or nesting beyond depth 1 needs either an assumption that only the runtime's markers own BS_PRIVATE_NESTED_SOME_NONE, or conditional types.
  • Only ES module output emits the type header and inline exports (commonjs_program does not).
  • Functions the optimizer synthesizes print unannotated.
  • The runtime declarations in runtime-dts/ are hand-written; a typed declaration for each runtime module would replace them.
  • Directional TScert extensions for client-side rescript-react apps are tracked in Roadmap: extensions needed to verify a simple rescript-react app cristianoc/TScert#378.

Checklist

  • Added a changelog fragment (see changes/README.md), or no release notes are needed and a maintainer should apply changelog:skip.
  • Added tests for the fix or feature.
  • Gave every commit a description below its subject, saying why it is made (see "Commit messages" in CONTRIBUTING.md).
  • Signed off every commit for the DCO (git commit -s).

@github-actions

github-actions Bot commented Nov 4, 2026

Copy link
Copy Markdown

Changelog

No changelog entry.

Semantic Diff

8 commits · Full page

Print TypeScript for a module under the experimental -bs-emit-ts flag

571a0cc · cristianoc + Claude · Nov 04, 2026, 01:34 UTC

Why

A feasibility study for checking ReScript output with TScert, which reads TypeScript whose top-level functions annotate their parameters and result. The flag writes .res.ts (.mts for .mjs) in place of the JavaScript output, annotates each top-level function from the typed tree, and puts the module's type declarations at the top through genType's translation. The annotations are keyed by Ident.t (name and stamp), so one reaches the output only when the J IR prints the identifier the typed tree bound; RESCRIPT_EMIT_TS_DEBUG=1 reports, per printed top-level function, whether its stamp and its parameters' stamps are the typed tree's.

JS modified (top-level functions under -bs-emit-ts)

type point = {x: int, y: int, label: string}
let moveX = (p: point, dx: int) => {...p, x: p.x + dx}

js · After: Rec.res.ts

-function moveX(p, dx) {
+export type point = {
+  readonly x: number;
+  readonly y: number;
+  readonly label: string
+};
+
+function moveX(p: point, dx: number): point {
   return {
     x: p.x + dx | 0,
     y: p.y,
     label: p.label
   };
 }

Review

  • Do the stamps survive to the printer? For every binding let f = (…) => … at the top level or in a nested module, uncurried, inlined into its callers, private or exported, the printed function and each of its parameters carry the typed tree's stamp. A function the optimizer synthesizes, such as let partial = curried(1), has fresh parameters and is printed unannotated.
Print an exported top-level function as export function under -bs-emit-ts

8ec2de4 · cristianoc + Claude · Nov 04, 2026, 01:36 UTC

Why

TScert's source fragment admits export function f(…) and refuses the trailing export list export { f, … }. Under -bs-emit-ts a top-level function exported under its own name is printed with export in front and leaves the list; other exports, such as a module record or an alias, stay in it. The printer is assumed to print a top-level function under its source name.

JS modified (exports under -bs-emit-ts)

let add = (a: int, b: int) => a + b

js

-function add(a: number, b: number): number {
+export function add(a: number, b: number): number {
   return a + b | 0;
 }
-
-export {
-  add,
-}
Print type parameters and optional parameters under -bs-emit-ts

2a07f4e · cristianoc + Claude · Nov 04, 2026, 02:50 UTC

Why

A polymorphic function printed its type variables without declaring them, which tsc rejects, and each parameter's variables were named on their own, so distinct variables shared the name T1. Optional labelled arguments printed as mandatory undefined | T parameters.

JS modified (-bs-emit-ts type parameters)

let id = x => x
let second = (_x: 'a, y: 'b): 'b => y

js

-export function id(x: T1): T1 {
+export function id<T1>(x: T1): T1 {
   return x;
 }
-export function second(_x: T1, y: T1): T1 {
+export function second<a, b>(_x: a, y: b): b {
   return y;
 }

JS modified (-bs-emit-ts optional labelled arguments)

let scale = (x: int, ~by=2) => x * by
let offset = (~from=0, x: int) => x - from

js

-export function scale(x: number, byOpt: (undefined | number)): number {
+export function scale(x: number, byOpt?: number): number {
 …
 export function offset(fromOpt: (undefined | number), x: number): number {

Review

  • Why does fromOpt keep undefined | number? TypeScript requires every parameter after an optional one to be optional, so ? goes only on the optional arguments after the last mandatory one; a ReScript call passes undefined for an omitted argument in either position.
Check in the -bs-emit-ts examples and their TypeScript output

ed4458a · cristianoc + Claude · Nov 04, 2026, 02:54 UTC

The build test tests/build_tests/emit_ts compiles seven examples with -bs-emit-ts and type-checks the checked-in .res.ts output with tsc --strict against declarations for the runtime functions the output imports.

Print option types true of the nested-option encoding under -bs-emit-ts

beb6284 · cristianoc + Claude · Nov 04, 2026, 04:32 UTC

Why

option<t> printed undefined | t, but Some(v) is a marker object {BS_PRIVATE_NESTED_SOME_NONE: depth} when v is undefined or a marker, so the type was false for option<option<int>> and option<unit>. At a type parameter it was false at a nested instantiation, and the runtime declarations valFromOption<A>(x: A): A, getOr and map were false there: at A the marker type, valFromOption(some(undefined)) returns undefined. A verifier taking those declarations accepted programs returning wrong values.

Representation modified (option under -bs-emit-ts)

representation

 option<int>                      ↦ undefined | number
-option<option<int>>              ↦ undefined | (undefined | number)
-option<'a>                       ↦ undefined | a
+option<option<int>>              ↦ undefined | (undefined | number) | { readonly BS_PRIVATE_NESTED_SOME_NONE: number }
+option<'a>                       ↦ undefined | a, with a extends string | number | boolean | bigint
+option<'a> in a type declaration ↦ undefined | a | { readonly BS_PRIVATE_NESTED_SOME_NONE: number }
+rule: the marker arm is printed where Typeopt.type_cannot_contain_undefined fails for the payload, the test that selects Psome over Psome_not_nest

JS modified (-bs-emit-ts type parameters)

let getOr = (o, d) =>
  switch o {
  | Some(v) => v
  | None => d
  }

js

-export function getOr<T1>(o: (undefined | T1), d: T1): T1 {
+export function getOr<T1 extends string | number | boolean | bigint>(o: (undefined | T1), d: T1): T1 {

JS modified (-bs-emit-ts nested options)

type box<'a> = {v: option<'a>}
let keep = (o: option<option<int>>) => o

js

-export type box<a> = { readonly v: (undefined | a) };
-export function keep(o: (undefined | (undefined | number))): (undefined | (undefined | number)) {
+export type box<a> = { readonly v: (undefined | (
+    a
+  | { readonly BS_PRIVATE_NESTED_SOME_NONE: number })) };
+export function keep(o: (undefined | (
+    (undefined | number)
+  | { readonly BS_PRIVATE_NESTED_SOME_NONE: number }))): …

The runtime declarations in runtime-dts state the same bound, each line audited against Primitive_option.res and Stdlib_Option.res, and Stdlib_Array.reduce's callback receives the index and the array that Array.prototype.reduce passes. The Nest example shows the marker arm and the bound.

Review

  • Why bound a type parameter by the primitives, and not by every type without the marker key? some(x) and valFromOption(x) return x exactly when x is not undefined and its key BS_PRIVATE_NESTED_SOME_NONE reads undefined. A primitive owns no keys and its untampered prototypes hold none. A TypeScript record type admits values owning further keys, and a weak type { BS_PRIVATE_NESTED_SOME_NONE?: undefined } rejects every record that does not state that field, so no wider bound is both true and usable.
  • What does the bound refuse? A call of such a function at a non-primitive instantiation, getOr of an option<point> say, fails tsc. A nested match such as Some(Some(n)) fails tsc too: the marker arm erases the depth, so no true declaration of valFromOption returns the payload type there.
Print the marker arm of option in aliases and optional arguments of arrows

ccb1f14 · cristianoc + Claude · Nov 04, 2026, 04:39 UTC

Why

The marker arm reached only options genType translated from a type expression as option<t>. A type declaration's manifest, translated from its core type, and an optional argument of a function type, whose option genType rebuilds, still printed undefined | t for a payload that can hold a marker. An optional argument of a function type in a type declaration also lost its option: the core type of ~x: int=? is its payload int, which genType read as the whole argument.

JS modified (-bs-emit-ts type declarations)

type opt<'a> = option<'a>
type callback = (~x: option<int>=?) => int
type cb2 = (~x: int=?) => int

js

-export type opt<a> = (undefined | a);
-export type callback = (x:(undefined | number)) => number;
-export type cb2 = (x:number) => number;
+export type opt<a> = (undefined | (
+    a
+  | { readonly BS_PRIVATE_NESTED_SOME_NONE: number }));
+export type callback = (x:(undefined | (
+    (undefined | number)
+  | { readonly BS_PRIVATE_NESTED_SOME_NONE: number }))) => number;
+export type cb2 = (x:(undefined | number)) => number;

Review

  • Does this change genType's own output? Only where a type declaration has an optional argument in a function type, which genType printed without its undefined; the marker arm is off outside -bs-emit-ts, and the gentype tests' outputs are unchanged.
Print a function body that is only return; under -bs-emit-ts

b0a9c17 · cristianoc + Claude · Nov 04, 2026, 05:12 UTC

Why

The printer drops a lone return;, so such a function prints an empty body. TypeScript requires a return in a function whose declared result type is other than undefined, void or any, and rejects the empty body with TS2355.

JS modified (-bs-emit-ts body that is only return;)

let none = (): option<int> => None

js

 export function none(): (undefined | number) {
+  return;
 }

Review

  • Does JavaScript output change? No: the statement is kept only under -bs-emit-ts.
Record tsc's diagnostics for the emit_ts examples, with nested-option unwrapping

8a1bb7e · cristianoc + Claude · Nov 04, 2026, 05:12 UTC

The emit_ts test writes what tsc --strict reports for the generated TypeScript to a checked-in tsc.txt, so an example the printed types refuse is checked in with its diagnostics. NestMatch unwraps nested options: a nested match and the generic getOr at 'a = option<int>, which the primitive bound on Primitive_option refuses.

@codecov

codecov Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 85.29412% with 70 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.25%. Comparing base (45dba2c) to head (b722717).

Files with missing lines Patch % Lines
compiler/driver/js_ts_collect.ml 82.60% 44 Missing ⚠️
compiler/backend/js_ts_annot.ml 77.90% 19 Missing ⚠️
compiler/backend/js_dump.ml 92.94% 6 Missing ⚠️
compiler/gentype/translate_type_expr_from_types.ml 92.30% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #9211      +/-   ##
==========================================
+ Coverage   82.22%   82.25%   +0.03%     
==========================================
  Files         461      463       +2     
  Lines       65573    66018     +445     
==========================================
+ Hits        53916    54305     +389     
- Misses      11657    11713      +56     
Files with missing lines Coverage Δ
compiler/backend/js_dump_import_export.ml 99.03% <100.00%> (+0.01%) ⬆️
compiler/backend/js_dump_lit.ml 100.00% <ø> (ø)
compiler/backend/js_dump_program.ml 98.61% <100.00%> (+0.14%) ⬆️
compiler/backend/js_stmt_make.ml 72.97% <100.00%> (ø)
compiler/backend/lam_coercion.ml 100.00% <100.00%> (ø)
compiler/backend/lam_compile.ml 90.58% <100.00%> (+0.01%) ⬆️
compiler/backend/lam_compile_main.ml 94.67% <100.00%> (+0.04%) ⬆️
compiler/backend/lam_pass_sroa.ml 86.58% <100.00%> (ø)
compiler/driver/js_implementation.ml 85.59% <100.00%> (+0.37%) ⬆️
compiler/driver/rescript_compiler_driver.ml 80.78% <100.00%> (+0.06%) ⬆️
... and 7 more

... and 4 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@pkg-pr-new

pkg-pr-new Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

rescript

npm i https://pkg.pr.new/rescript@9211

@rescript/belt

npm i https://pkg.pr.new/@rescript/belt@9211

@rescript/darwin-arm64

npm i https://pkg.pr.new/@rescript/darwin-arm64@9211

@rescript/linux-arm64

npm i https://pkg.pr.new/@rescript/linux-arm64@9211

@rescript/linux-x64

npm i https://pkg.pr.new/@rescript/linux-x64@9211

@rescript/runtime

npm i https://pkg.pr.new/@rescript/runtime@9211

@rescript/win32-x64

npm i https://pkg.pr.new/@rescript/win32-x64@9211

commit: b722717

@github-actions

github-actions Bot commented Nov 4, 2026

Copy link
Copy Markdown

Why:
    A feasibility study for checking ReScript output with TScert, which reads
    TypeScript whose top-level functions annotate their parameters and
    result. The flag writes `.res.ts` (`.mts` for `.mjs`, `.cts` for `.cjs`)
    in place of the JavaScript output, annotates each top-level function from
    the typed tree, puts the module's type declarations at the top through
    genType's translation, and prints nested options by depth and polymorphic
    option functions as overloads so both `tsc --strict` and TScert accept
    them.

    `Js_ts_annot` in `compiler/backend` holds the per-request annotation
    table keyed by `Ident.t` (name and stamp) that the JS printer reads;
    `Js_ts_collect` in `compiler/driver` populates it from the typed tree
    using `gentype`, keeping `backend` free of a `gentype` dependency.
    `RESCRIPT_EMIT_TS_DEBUG=1` reports, per printed top-level function,
    whether its stamp and its parameters' stamps are the typed tree's.

JS modified (top-level functions and exports under -bs-emit-ts):
Example:
    type point = {x: int, y: int, label: string}
    let moveX = (p: point, dx: int) => {...p, x: p.x + dx}
Before (js):
    function moveX(p, dx) {
      return {
        x: p.x + dx | 0,
        y: p.y,
        label: p.label
      };
    }

    export {
      moveX,
    }
After (js): Rec.res.ts
    export type point = {
      readonly x: number;
      readonly y: number;
      readonly label: string
    };

    export function moveX(p: point, dx: number): point {
      return {
        x: p.x + dx | 0,
        y: p.y,
        label: p.label
      };
    }

JS modified (-bs-emit-ts type parameters, optional arguments and lone return;):
Example:
    let second = (_x: 'a, y: 'b): 'b => y
    let scale = (x: int, ~by=2) => x * by
    let offset = (~from=0, x: int) => x - from
    let none = (): option<int> => None
Before (js):
    function second(_x, y) {
      return y;
    }
    function scale(x, byOpt) {
      …
    }
    function offset(fromOpt, x) {
      …
    }
    function none() {
    }
After (js):
    export function second<a, b>(_x: a, y: b): b {
      return y;
    }
    export function scale(x: number, byOpt?: number): number {
      …
    }
    export function offset(fromOpt: (undefined | number), x: number): number {
      …
    }
    export function none(): (undefined | number) {
      return;
    }

Representation modified (option under -bs-emit-ts):
After (representation):
    option<int>                                                 ↦ undefined | number
    option<option<int>>                                         ↦ undefined | number | { readonly BS_PRIVATE_NESTED_SOME_NONE: 0 }
    option<option<option<int>>>                                 ↦ undefined | number | { …: 0 } | { …: 1 }
    option<unit>                                                ↦ undefined | void | { readonly BS_PRIVATE_NESTED_SOME_NONE: 0 }
    option<'a> in a type declaration, or at an abstract payload ↦ undefined | a | { …: number }
    option<option<keyed>> (payload may own marker key)          ↦ undefined | keyed | { …: number }
    rule: Some(v) is the marker of depth 0 when v is undefined, of depth d + 1 when v is the marker of depth d, and v otherwise (Primitive_option.some); a payload is no marker only where it cannot hold undefined and may own no key BS_PRIVATE_NESTED_SOME_NONE

JS modified (-bs-emit-ts polymorphic option code):
Example:
    let getOr = (o: option<'a>, d: 'a) =>
      switch o {
      | Some(v) => v
      | None => d
      }
After (js):
    export function getOr<a extends string | number | boolean | bigint>(o: (undefined | a), d: a): a;
    export function getOr<a extends string | number | boolean | bigint>(o: (undefined | (
        (undefined | a)
      | { readonly BS_PRIVATE_NESTED_SOME_NONE: 0 })), d: (undefined | a)): (undefined | a);
    export function getOr<a extends string | number | boolean | bigint>(o: (undefined | (
        (undefined | a)
      | { readonly BS_PRIVATE_NESTED_SOME_NONE: 0 })), d: (undefined | a)): (undefined | a) {
      …
    }

Review: Does JavaScript or genType output change outside -bs-emit-ts? No:
all printer hooks and the lone `return;` guard are gated on `emit_ts`, and
genType's `option_payload_markers` hook defaults to `No_markers`; the
genType test suites produce unchanged outputs.

Review: Why split `Js_ts_annot` (`backend`) and `Js_ts_collect` (`driver`)?
`compiler/backend` does not depend on `gentype`, whereas `compiler/driver`
already links both `backend` and `gentype`. Keeping the per-request table in
`backend` and the typed-tree/genType collector in `driver` preserves that
boundary.

Review: Why overloads instead of a conditional type for `Some<A>`?
`Some<A>` at an unbounded `A` is true only if no value but the runtime's
markers owns the key `BS_PRIVATE_NESTED_SOME_NONE`; a TypeScript object type
admits further keys. Each overload is the function's signature at
`'a := option^k<a>` (`k = 0, 1`) with `a` bounded to primitives, holding
with no extra assumption.

Signed-off-by: Cristiano Calcagno <ccrisccris@gmail.com>
Add `tests/build_tests/emit_ts`, compiling ten example modules (`Arith`,
`Arr`, `Gen`, `Memo`, `Nest`, `NestMatch`, `Opt`, `OptArg`, `Rec`, `Shape`)
with `-bs-emit-ts` and recording `tsc --strict` diagnostics in `tsc.txt`
against audited runtime declarations in `runtime-dts/` (`Primitive_option`,
`Stdlib_Option`, `Stdlib_Array`). `tsc.txt` is empty, and all ten generated
modules (46 units) verify end-to-end under TScert's `single-pass` branch.

Signed-off-by: Cristiano Calcagno <ccrisccris@gmail.com>
@github-actions

github-actions Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Changelog

No changelog entry.

Semantic Diff

6 commits · Full page

Print TypeScript for a module under the experimental -bs-emit-ts flag

ad393f3 · cristianoc · Nov 24, 2026, 03:22 UTC

Why

A feasibility study for checking ReScript output with TScert, which reads TypeScript whose top-level functions annotate their parameters and result. The flag writes .res.ts (.mts for .mjs, .cts for .cjs) in place of the JavaScript output, annotates each top-level function from the typed tree, puts the module's type declarations at the top through genType's translation, and prints nested options by depth and polymorphic option functions as overloads so both tsc --strict and TScert accept them.

Js_ts_annot in compiler/backend holds the per-request annotation table keyed by Ident.t (name and stamp) that the JS printer reads; Js_ts_collect in compiler/driver populates it from the typed tree using gentype, keeping backend free of a gentype dependency. RESCRIPT_EMIT_TS_DEBUG=1 reports, per printed top-level function, whether its stamp and its parameters' stamps are the typed tree's.

JS modified (top-level functions and exports under -bs-emit-ts)

type point = {x: int, y: int, label: string}
let moveX = (p: point, dx: int) => {...p, x: p.x + dx}

js · After: Rec.res.ts

-function moveX(p, dx) {
+export type point = {
+  readonly x: number;
+  readonly y: number;
+  readonly label: string
+};
+
+export function moveX(p: point, dx: number): point {
   return {
     x: p.x + dx | 0,
     y: p.y,
     label: p.label
   };
 }
-
-export {
-  moveX,
-}

JS modified (-bs-emit-ts type parameters, optional arguments and lone return;)

let second = (_x: 'a, y: 'b): 'b => y
let scale = (x: int, ~by=2) => x * by
let offset = (~from=0, x: int) => x - from
let none = (): option<int> => None

js

-function second(_x, y) {
+export function second<a, b>(_x: a, y: b): b {
   return y;
 }
-function scale(x, byOpt) {
+export function scale(x: number, byOpt?: number): number {
   …
 }
-function offset(fromOpt, x) {
+export function offset(fromOpt: (undefined | number), x: number): number {
   …
 }
-function none() {
+export function none(): (undefined | number) {
+  return;
 }

Representation modified (option under -bs-emit-ts)

representation · After

option<int>                                                 ↦ undefined | number
option<option<int>>                                         ↦ undefined | number | { readonly BS_PRIVATE_NESTED_SOME_NONE: 0 }
option<option<option<int>>>                                 ↦ undefined | number | { …: 0 } | { …: 1 }
option<unit>                                                ↦ undefined | void | { readonly BS_PRIVATE_NESTED_SOME_NONE: 0 }
option<'a> in a type declaration, or at an abstract payload ↦ undefined | a | { …: number }
option<option<keyed>> (payload may own marker key)          ↦ undefined | keyed | { …: number }
rule: Some(v) is the marker of depth 0 when v is undefined, of depth d + 1 when v is the marker of depth d, and v otherwise (Primitive_option.some); a payload is no marker only where it cannot hold undefined and may own no key BS_PRIVATE_NESTED_SOME_NONE

JS modified (-bs-emit-ts polymorphic option code)

let getOr = (o: option<'a>, d: 'a) =>
  switch o {
  | Some(v) => v
  | None => d
  }

js · After

export function getOr<a extends string | number | boolean | bigint>(o: (undefined | a), d: a): a;
export function getOr<a extends string | number | boolean | bigint>(o: (undefined | (
    (undefined | a)
  | { readonly BS_PRIVATE_NESTED_SOME_NONE: 0 })), d: (undefined | a)): (undefined | a);
export function getOr<a extends string | number | boolean | bigint>(o: (undefined | (
    (undefined | a)
  | { readonly BS_PRIVATE_NESTED_SOME_NONE: 0 })), d: (undefined | a)): (undefined | a) {
  …
}

Review

  • Does JavaScript or genType output change outside -bs-emit-ts? No: all printer hooks and the lone return; guard are gated on emit_ts, and genType's option_payload_markers hook defaults to No_markers; the genType test suites produce unchanged outputs.
  • Why split Js_ts_annot (backend) and Js_ts_collect (driver)? compiler/backend does not depend on gentype, whereas compiler/driver already links both backend and gentype. Keeping the per-request table in backend and the typed-tree/genType collector in driver preserves that boundary.
  • Why overloads instead of a conditional type for Some<A>? Some<A> at an unbounded A is true only if no value but the runtime's markers owns the key BS_PRIVATE_NESTED_SOME_NONE; a TypeScript object type admits further keys. Each overload is the function's signature at 'a := option^k<a> (k = 0, 1) with a bounded to primitives, holding with no extra assumption.
Add -bs-emit-ts build test with checked-in TypeScript and tsc output

dcba023 · cristianoc · Nov 24, 2026, 03:23 UTC

Add tests/build_tests/emit_ts, compiling ten example modules (Arith, Arr, Gen, Memo, Nest, NestMatch, Opt, OptArg, Rec, Shape) with -bs-emit-ts and recording tsc --strict diagnostics in tsc.txt against audited runtime declarations in runtime-dts/ (Primitive_option, Stdlib_Option, Stdlib_Array). tsc.txt is empty, and all ten generated modules (46 units) verify end-to-end under TScert's single-pass branch.

Emit cross-module imports, const exports, tail-call params and local types under -bs-emit-ts

caf6288 · cristianoc · Nov 24, 2026, 04:16 UTC

Why

Multi-module programs, non-function exports, tail-recursive functions and local refs or deferred initializations need five extensions under -bs-emit-ts so both tsc --strict and TScert accept the emitted TypeScript: - Same-package ML module imports use the emitted TypeScript suffix (.res.ts, .mts, .cts), and Js_ts_collect resolves cross-module type dependencies with Bundler resolution and that suffix so function signatures, value bindings and type declarations import types from ./Mod.res.ts. - Top-level non-function bindings collect their monomorphic types from the typed tree, propagate annotations across Lam_coercion's Ident.rename, and print immutable bindings as export const x: T = … rather than live export let bindings. - Inline export checks compare the printed name from Ext_pp_scope against Ext_ident.convert id.name (excluding default), so reserved names such as eval print export function $$eval while scope-collision renames stay in export { … }. - Tail-call lowering (Lam_compile) propagates parameter annotations and overload origins when introducing _param. - Js_stmt_make.define_variable retains = undefined under -bs-emit-ts, Js_ts_collect records monomorphic local binding types and record/tuple field types, Lam_pass_sroa propagates field types to scalar-replaced locals (such as ref(None)), and Js_dump annotates uninitialized or undefined-initialized locals.

JS modified (-bs-emit-ts cross-module imports and const/reserved exports)

// Expr.res: type expr = Lit(int) | ...
let zero = Lit(0)
// Eval.res:
let eval = (e: Expr.expr) => Expr.simplify(e)

js

 // Expr.res.ts
-let zero = { TAG: "Lit", _0: 0 };
-export { zero, }
+export const zero: expr = { TAG: "Lit", _0: 0 };
 
 // Eval.res.ts
-import * as Expr from "./Expr.res.js";
-function $$eval(e: Expr_expr): Expr_expr {
+import * as Expr from "./Expr.res.ts";
+import type {expr as Expr_expr} from './Expr.res.ts';
+export function $$eval(e: Expr_expr): Expr_expr {
   return Expr.simplify(e);
 }
-export { $$eval, }

JS modified (-bs-emit-ts tail-call parameter and uninitialized local types)

let rec unwrapNeg = (e: expr): expr =>
  switch e {
  | Neg(Neg(inner)) => unwrapNeg(inner)
  | _ => e
  }
let find = (xs: array<int>) => {
  let found = ref(None)
  …
  found.contents
}

js

-export function unwrapNeg(_e): expr {
+export function unwrapNeg(_e: expr): expr {
   while (true) { … }
 }
 export function find(xs: number[]): (undefined | number) {
-  let found;
+  let found: (undefined | number) = undefined;
   …
   return found;
 }

Review

  • Does JavaScript or genType output change outside -bs-emit-ts? No: all emission and annotation hooks are gated on Js_ts_annot.enabled ().
Add multi-module Expr and Eval examples to -bs-emit-ts build test

b722717 · cristianoc · Nov 24, 2026, 04:17 UTC

Add a two-module AST and evaluator (Expr and Eval) to tests/build_tests/emit_ts along with an audited Primitive_int.d.mts contract for Primitive_int.div, exercising cross-module .res imports of types and values, recursive variants, tail recursion, non-function const exports, result, @unboxed and polymorphic variants, ref with while/for loops, array writes, and mutable record fields. tsc.txt remains empty (0 diagnostics), and all 12 generated modules (59/59 units) verify under TScert single-pass (0406f7e50).

✨ Annotate mutable local bindings under -bs-emit-ts

a9fd8b6 · cristianoc · Nov 24, 2026, 05:00 UTC · new

Why

A mutable local binding (property = Variable, such as an SROA-unboxed ref(All) holding a string-union variant) widens in TypeScript when printed without a type annotation (let filter = "All" infers string, which fails when returned at filter). Annotating mutable locals with their collected monomorphic type keeps the narrowed union type intact.

JS modified (-bs-emit-ts mutable local bindings)

let parseFilter = (flag: bool): TodoModel.filter => {
  let filter = ref(TodoModel.All)
  if flag { filter := TodoModel.Active }
  filter.contents
}

js

 export function parseFilter(flag: boolean): TodoModel_filter {
-  let filter = "All";
+  let filter: TodoModel_filter = "All";
   if (flag) {
     filter = "Active";
   }
   return filter;
 }

Review

  • Does JavaScript output change outside -bs-emit-ts? No: the annotation branch is gated on Js_ts_annot.enabled ().
✨ Add TScert-verified multi-module Todo web app to -bs-emit-ts build test

d5158ff · cristianoc · Nov 24, 2026, 05:01 UTC · new

Add a usable, styled Todo web app split across three ReScript modules (TodoModel, TodoView, TodoApp) plus a thin Node 26 HTTP adapter (todo-server.mts) to tests/build_tests/emit_ts. The verified ReScript core covers priorities, filters, search, inline editing, toggle-all, clear-completed, HTML escaping, URL/query parsing, variant-driven routing, and JSON responses, with zero runtime-dts/ contracts. tsc.txt stays empty (0 diagnostics), all 15 modules (95/95 units; 36/36 for the Todo app) verify under TScert single-pass (0406f7e50), and all HTTP routes pass live against todo-server.mts on Node 26.

@github-actions

github-actions Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

⚠️ Compiler benchmarks

Allocated words

In total: 637,410,895 → 638,383,191 (+0.15%).

Generated projects: 629,040,207 → 630,360,151 (+0.21%).

⚠️ Regression: 19 benchmarks allocate more than 1% more.

Benchmark Base Head Change
build/Namespace/clean 84,166,681 85,195,516 +1.22%
packages/@rescript/runtime/Primitive_list.resi 91,887 92,959 +1.17%
packages/@rescript/runtime/Primitive_float_extern.res 93,687 94,759 +1.14%
packages/@rescript/runtime/Stdlib_Blob.res 93,905 94,977 +1.14%
packages/@rescript/runtime/Stdlib_File.res 95,714 96,786 +1.12%
packages/@rescript/runtime/Primitive_promise.res 97,062 98,134 +1.10%
packages/@rescript/runtime/Primitive_int_extern.res 97,915 98,987 +1.09%
packages/@rescript/runtime/Stdlib_Iterable.resi 98,169 99,241 +1.09%
packages/@rescript/runtime/Primitive_string_extern.res 98,223 99,295 +1.09%
packages/@rescript/runtime/Stdlib_AsyncIterable.resi 98,318 99,390 +1.09%
217 more changes
Benchmark Base Head Change
packages/@rescript/runtime/Stdlib_Iterable.res 98,944 100,016 +1.08%
packages/@rescript/runtime/Stdlib_AsyncIterable.res 99,015 100,087 +1.08%
packages/@rescript/runtime/Obj.res 99,164 100,236 +1.08%
packages/@rescript/runtime/Primitive_exceptions.resi 100,319 101,391 +1.07%
packages/@rescript/runtime/Primitive_dict.res 102,715 103,787 +1.04%
packages/@rescript/runtime/Primitive_hash.resi 102,744 103,816 +1.04%
packages/@rescript/runtime/Primitive_module.resi 103,182 104,254 +1.04%
packages/@rescript/runtime/RescriptTools.res 104,517 105,595 +1.03%
packages/@rescript/runtime/Stdlib_TaggedTemplate.resi 106,124 107,196 +1.01%
packages/@rescript/runtime/Stdlib_ArrayBuffer.res 107,537 108,609 +1.00%
packages/@rescript/runtime/Stdlib_ArrayBuffer.resi 110,989 112,061 +0.97%
packages/@rescript/runtime/RescriptTools_ExtractCodeBlocks.res 112,140 113,212 +0.96%
packages/@rescript/runtime/Stdlib_Lazy.resi 112,434 113,506 +0.95%
packages/@rescript/runtime/Primitive_array_extern.res 114,220 115,292 +0.94%
packages/@rescript/runtime/Primitive_object_extern.res 114,729 115,801 +0.93%
packages/@rescript/runtime/Stdlib_TaggedTemplate.res 115,368 116,443 +0.93%
packages/@rescript/runtime/Stdlib_Intl_Segments.res 116,601 117,673 +0.92%
packages/@rescript/runtime/Stdlib_Bool.resi 116,818 117,890 +0.92%
packages/@rescript/runtime/Primitive_object.resi 117,125 118,197 +0.92%
packages/@rescript/runtime/Dom_storage2.res 120,182 121,254 +0.89%
packages/@rescript/runtime/Jsx.res 121,738 122,810 +0.88%
packages/@rescript/runtime/Primitive_option.resi 122,265 123,337 +0.88%
packages/@rescript/runtime/Stdlib_JsExn.resi 122,775 123,847 +0.87%
packages/@rescript/runtime/Stdlib_WeakSet.res 123,172 124,244 +0.87%
packages/@rescript/runtime/Stdlib_WeakMap.res 135,503 136,575 +0.79%
packages/@rescript/runtime/Stdlib_Type.resi 135,946 137,018 +0.79%
packages/@rescript/runtime/Stdlib_Bool.res 146,012 147,141 +0.77%
packages/@rescript/runtime/Primitive_float.res 146,893 148,022 +0.77%
packages/@rescript/runtime/Primitive_bool.res 147,218 148,347 +0.77%
packages/@rescript/runtime/Stdlib_Ordering.res 152,340 153,507 +0.77%
packages/@rescript/runtime/Stdlib_Global.res 141,743 142,821 +0.76%
packages/@rescript/runtime/Stdlib_Temporal_Now.res 143,495 144,567 +0.75%
packages/@rescript/runtime/Stdlib_Symbol.res 146,511 147,583 +0.73%
packages/@rescript/runtime/Primitive_string.res 159,592 160,740 +0.72%
packages/@rescript/runtime/Stdlib_IterableIterator.resi 149,406 150,478 +0.72%
packages/@rescript/belt/src/Belt_Int.resi 149,771 150,843 +0.72%
packages/@rescript/belt/src/Belt_Float.resi 151,251 152,323 +0.71%
packages/@rescript/runtime/Stdlib_Intl_Common.res 154,360 155,432 +0.69%
packages/@rescript/runtime/Stdlib_Intl_Segmenter.res 154,540 155,612 +0.69%
packages/@rescript/runtime/Stdlib_Global.resi 155,548 156,620 +0.69%
packages/@rescript/runtime/Dom_storage.res 167,042 168,190 +0.69%
packages/@rescript/runtime/Stdlib_Intl_NumberFormat_Grouping.res 159,421 160,512 +0.68%
packages/@rescript/runtime/Primitive_int.res 171,842 173,009 +0.68%
packages/@rescript/runtime/Stdlib_Iterator.resi 159,246 160,318 +0.67%
packages/@rescript/runtime/Stdlib_Pair.res 165,262 166,372 +0.67%
packages/@rescript/runtime/Stdlib_AsyncIterableIterator.resi 159,925 160,997 +0.67%
packages/@rescript/runtime/Stdlib_Symbol.resi 160,141 161,213 +0.67%
packages/@rescript/runtime/Stdlib_Generator.resi 160,547 161,619 +0.67%
packages/@rescript/belt/src/Belt_Float.res 165,048 166,139 +0.66%
packages/@rescript/runtime/Primitive_bigint.res 177,314 178,481 +0.66%
packages/@rescript/belt/src/Belt_Int.res 165,790 166,881 +0.66%
packages/@rescript/runtime/Stdlib_RegExp.res 163,713 164,788 +0.66%
packages/@rescript/belt/src/Belt_internalBucketsType.resi 164,724 165,796 +0.65%
packages/@rescript/runtime/Stdlib_AsyncGenerator.resi 165,925 166,997 +0.65%
packages/@rescript/runtime/Stdlib_JsExn.res 173,080 174,186 +0.64%
packages/@rescript/runtime/Stdlib_Intl.res 173,862 174,964 +0.63%
packages/@rescript/belt/src/Belt_MutableStack.resi 169,281 170,353 +0.63%
packages/@rescript/belt/src/Belt_SortArrayString.resi 169,577 170,649 +0.63%
packages/@rescript/belt/src/Belt_SortArrayInt.resi 169,695 170,767 +0.63%
packages/@rescript/runtime/Stdlib_Intl_ListFormat.res 169,825 170,897 +0.63%
packages/@rescript/belt/src/Belt_HashSetString.resi 175,553 176,625 +0.61%
packages/@rescript/belt/src/Belt_HashSetInt.resi 175,666 176,738 +0.61%
packages/@rescript/belt/src/Belt_Range.resi 176,657 177,729 +0.61%
packages/@rescript/runtime/Stdlib_IterableIterator.res 178,852 179,933 +0.60%
packages/@rescript/runtime/Stdlib_AsyncIterator.resi 177,818 178,890 +0.60%
packages/@rescript/runtime/Stdlib_Intl_Collator.res 178,667 179,739 +0.60%
packages/@rescript/belt/src/Belt.res 187,948 189,071 +0.60%
packages/@rescript/runtime/Stdlib_Intl_RelativeTimeFormat.res 180,464 181,536 +0.59%
packages/@rescript/runtime/Primitive_array.res 191,984 193,113 +0.59%
packages/@rescript/runtime/Stdlib_JsError.resi 184,968 186,040 +0.58%
packages/@rescript/runtime/Stdlib_BigInt.resi 186,569 187,641 +0.57%
packages/@rescript/runtime/Stdlib_RegExp.resi 187,800 188,872 +0.57%
packages/@rescript/runtime/Primitive_exceptions.res 201,232 202,361 +0.56%
packages/@rescript/runtime/Stdlib_Generator.res 200,286 201,402 +0.56%
packages/@rescript/belt/src/Belt_internalSetBuckets.resi 194,250 195,322 +0.55%
packages/@rescript/runtime/Stdlib_Float.resi 194,292 195,364 +0.55%
packages/@rescript/runtime/Primitive_list.res 203,745 204,868 +0.55%
packages/@rescript/runtime/Stdlib_BigInt.res 207,074 208,203 +0.55%
packages/@rescript/runtime/Stdlib_Type.res 201,438 202,529 +0.54%
packages/@rescript/runtime/Stdlib_Intl_Locale.res 198,068 199,140 +0.54%
packages/@rescript/runtime/Stdlib_Nullable.resi 199,672 200,744 +0.54%
packages/@rescript/runtime/Stdlib_JsError.res 229,751 230,975 +0.53%
packages/@rescript/runtime/Stdlib_Intl_PluralRules.res 201,889 202,961 +0.53%
packages/@rescript/runtime/Stdlib_Map.res 205,648 206,739 +0.53%
packages/@rescript/runtime/Stdlib_AsyncGenerator.res 211,156 212,272 +0.53%
packages/@rescript/runtime/Stdlib_Null.resi 204,431 205,503 +0.52%
packages/@rescript/runtime/Stdlib_Int.resi 206,103 207,175 +0.52%
packages/@rescript/runtime/Stdlib_Lazy.res 221,184 222,334 +0.52%
packages/@rescript/runtime/Stdlib_Set.res 210,990 212,081 +0.52%
packages/@rescript/belt/src/Belt_MutableQueue.resi 207,326 208,398 +0.52%
packages/@rescript/belt/src/Belt_HashMapString.resi 213,714 214,786 +0.50%
packages/@rescript/belt/src/Belt_HashMapInt.resi 213,828 214,900 +0.50%
packages/@rescript/runtime/Stdlib_Float.res 218,863 219,960 +0.50%
packages/@rescript/runtime/Stdlib_Iterator.res 234,922 236,085 +0.50%
packages/@rescript/runtime/Stdlib_Map.resi 217,108 218,180 +0.49%
packages/@rescript/runtime/Stdlib_Temporal.res 223,963 225,065 +0.49%
packages/@rescript/runtime/Stdlib_AsyncIterableIterator.res 228,325 229,425 +0.48%
packages/@rescript/belt/src/Belt_HashSet.resi 222,778 223,850 +0.48%
packages/@rescript/belt/src/Belt_internalBuckets.resi 223,042 224,114 +0.48%
packages/@rescript/runtime/Stdlib_Set.resi 228,953 230,025 +0.47%
packages/@rescript/runtime/Stdlib_DataView.res 230,306 231,378 +0.47%
packages/@rescript/runtime/Stdlib_IteratorObject.resi 234,376 235,448 +0.46%
packages/@rescript/runtime/Stdlib_Option.resi 236,507 237,579 +0.45%
packages/@rescript/runtime/Stdlib_JSON.resi 237,027 238,099 +0.45%
packages/@rescript/runtime/Primitive_js_extern.res 239,834 240,909 +0.45%
packages/@rescript/runtime/Pervasives.res 239,805 240,877 +0.45%
packages/@rescript/belt/src/Belt_Result.resi 240,168 241,240 +0.45%
packages/@rescript/runtime/Stdlib_Dict.resi 240,779 241,851 +0.45%
packages/@rescript/belt/src/Belt_Option.resi 243,374 244,446 +0.44%
packages/@rescript/runtime/Stdlib_Object.res 247,331 248,403 +0.43%
packages/@rescript/runtime/Stdlib_IteratorObject.res 250,722 251,800 +0.43%
packages/@rescript/belt/src/Belt_SortArray.resi 253,942 255,014 +0.42%
packages/@rescript/belt/src/Belt_SetString.resi 259,922 260,994 +0.41%
packages/@rescript/belt/src/Belt_SetInt.resi 260,049 261,121 +0.41%
packages/@rescript/belt/src/Belt_Id.resi 260,286 261,358 +0.41%
packages/@rescript/belt/src/Belt_Range.res 288,346 289,528 +0.41%
packages/@rescript/runtime/Stdlib_Temporal_PlainMonthDay.res 268,246 269,337 +0.41%
packages/@rescript/belt/src/Belt_MutableSetString.resi 264,996 266,068 +0.40%
packages/@rescript/belt/src/Belt_MutableSetInt.resi 265,113 266,185 +0.40%
packages/@rescript/runtime/Primitive_option.res 297,411 298,613 +0.40%
packages/@rescript/runtime/Stdlib_AsyncIterator.res 294,756 295,938 +0.40%
packages/@rescript/belt/src/Belt_Id.res 289,887 291,047 +0.40%
packages/@rescript/runtime/Stdlib_DataView.resi 268,044 269,116 +0.40%
packages/@rescript/runtime/Stdlib_JSON.res 296,903 298,081 +0.40%
packages/@rescript/belt/src/Belt_internalBucketsType.res 291,615 292,763 +0.39%
packages/@rescript/runtime/RescriptTools_Docgen.resi 273,524 274,596 +0.39%
packages/@rescript/runtime/RescriptTools_Docgen.res 283,791 284,882 +0.38%
packages/@rescript/runtime/Stdlib_Nullable.res 329,857 331,100 +0.38%
packages/@rescript/runtime/Stdlib_Null.res 332,359 333,602 +0.37%
packages/@rescript/runtime/Stdlib_Result.resi 296,377 297,449 +0.36%
packages/@rescript/belt/src/Belt_HashMap.resi 296,908 297,980 +0.36%
packages/@rescript/runtime/Stdlib_Temporal_Instant.res 307,599 308,690 +0.35%
packages/@rescript/runtime/Stdlib_Dict.res 320,111 321,223 +0.35%
packages/@rescript/runtime/Stdlib_Math.res 327,556 328,682 +0.34%
packages/@rescript/runtime/Stdlib_Temporal_PlainTime.res 320,257 321,348 +0.34%
packages/@rescript/belt/src/Belt_MutableMapString.resi 314,993 316,065 +0.34%
packages/@rescript/belt/src/Belt_Option.res 389,121 390,445 +0.34%
packages/@rescript/belt/src/Belt_MutableMapInt.resi 315,111 316,183 +0.34%
packages/@rescript/belt/src/Belt_MutableStack.res 387,514 388,801 +0.33%
packages/@rescript/runtime/Primitive_module.res 337,540 338,656 +0.33%
packages/@rescript/runtime/Stdlib_Math.resi 328,324 329,396 +0.33%
packages/@rescript/runtime/Stdlib_Int8Array.res 343,494 344,569 +0.31%
packages/@rescript/runtime/Stdlib_Uint8Array.res 343,507 344,582 +0.31%
packages/@rescript/runtime/Stdlib_Float32Array.res 343,614 344,689 +0.31%
packages/@rescript/runtime/Stdlib_Float64Array.res 343,614 344,689 +0.31%
packages/@rescript/runtime/Stdlib_Int16Array.res 343,639 344,714 +0.31%
packages/@rescript/runtime/Stdlib_Int32Array.res 343,641 344,716 +0.31%
packages/@rescript/runtime/Stdlib_Uint16Array.res 343,646 344,721 +0.31%
packages/@rescript/runtime/Stdlib_Uint32Array.res 343,646 344,721 +0.31%
packages/@rescript/runtime/Stdlib_BigInt64Array.res 343,671 344,746 +0.31%
packages/@rescript/runtime/Stdlib_BigUint64Array.res 343,748 344,823 +0.31%
packages/@rescript/runtime/Stdlib_Uint8ClampedArray.res 344,022 345,097 +0.31%
packages/@rescript/runtime/Stdlib_Promise.res 352,778 353,875 +0.31%
packages/@rescript/belt/src/Belt_Result.res 409,437 410,698 +0.31%
packages/@rescript/belt/src/Belt_internalAVLset.resi 354,869 355,941 +0.30%
packages/@rescript/runtime/Stdlib_Promise.resi 356,017 357,089 +0.30%
packages/@rescript/runtime/Stdlib_Temporal_Common.res 366,668 367,740 +0.29%
packages/@rescript/runtime/Stdlib_Temporal_Duration.res 373,600 374,691 +0.29%
packages/@rescript/runtime/Stdlib_Console.res 370,179 371,251 +0.29%
packages/@rescript/runtime/Stdlib_Temporal_PlainYearMonth.res 382,285 383,376 +0.29%
packages/@rescript/runtime/Stdlib_Intl_DateTimeFormat.res 389,599 390,671 +0.28%
packages/@rescript/belt/src/Belt_MapString.resi 391,308 392,380 +0.27%
packages/@rescript/belt/src/Belt_MapInt.resi 391,351 392,423 +0.27%
packages/@rescript/belt/src/Belt_MutableMap.resi 395,444 396,516 +0.27%
packages/@rescript/runtime/Stdlib_Temporal_PlainDate.res 403,907 404,998 +0.27%
packages/@rescript/belt/src/Belt_MutableSet.resi 397,546 398,618 +0.27%
packages/@rescript/belt/src/Belt_SetDict.resi 402,680 403,752 +0.27%
packages/@rescript/runtime/Stdlib_Intl_NumberFormat.res 404,810 405,885 +0.27%
packages/@rescript/runtime/Stdlib_List.resi 409,863 410,935 +0.26%
packages/@rescript/runtime/Stdlib_Console.resi 411,610 412,682 +0.26%
packages/@rescript/runtime/Stdlib_Int.res 455,336 456,486 +0.25%
packages/@rescript/runtime/Stdlib_Temporal_PlainDateTime.res 438,194 439,285 +0.25%
build/clean 237,109,587 237,699,889 +0.25%
packages/@rescript/belt/src/Belt_Set.resi 437,438 438,510 +0.25%
packages/@rescript/belt/src/Belt_internalAVLtree.resi 452,423 453,495 +0.24%
packages/@rescript/runtime/Stdlib_String.res 503,934 505,120 +0.24%
packages/@rescript/runtime/Stdlib_String.resi 497,477 498,549 +0.22%
packages/@rescript/belt/src/Belt_Set.res 857,946 859,763 +0.21%
packages/@rescript/belt/src/Belt_MapDict.resi 513,298 514,370 +0.21%
packages/@rescript/runtime/Stdlib_Date.res 551,778 552,891 +0.20%
packages/@rescript/runtime/Stdlib_Temporal_ZonedDateTime.res 574,181 575,272 +0.19%
packages/@rescript/belt/src/Belt_internalSetBuckets.res 699,079 700,396 +0.19%
packages/@rescript/belt/src/Belt_Map.res 981,236 983,081 +0.19%
packages/@rescript/belt/src/Belt_Map.resi 579,471 580,559 +0.19%
packages/@rescript/runtime/Stdlib_Option.res 753,633 755,047 +0.19%
packages/@rescript/belt/src/Belt_MutableQueue.res 791,334 792,741 +0.18%
packages/@rescript/runtime/Stdlib_Date.resi 614,248 615,320 +0.17%
packages/@rescript/belt/src/Belt_internalSetInt.res 730,723 731,975 +0.17%
packages/@rescript/belt/src/Belt_internalSetString.res 731,914 733,166 +0.17%
packages/@rescript/belt/src/Belt_Array.resi 650,336 651,408 +0.16%
parse/RedBlackTreeNoComments.res 355,139 355,675 +0.15%
packages/@rescript/belt/src/Belt_MutableMapString.res 1,155,019 1,156,743 +0.15%
packages/@rescript/belt/src/Belt_MutableMapInt.res 1,154,742 1,156,462 +0.15%
packages/@rescript/belt/src/Belt_internalBuckets.res 966,624 968,061 +0.15%
packages/@rescript/belt/src/Belt_HashSetInt.res 850,520 851,780 +0.15%
packages/@rescript/belt/src/Belt_HashSetString.res 850,837 852,095 +0.15%
parse/RedBlackTree.res 362,852 363,388 +0.15%
packages/@rescript/runtime/Stdlib_Array.resi 728,603 729,675 +0.15%
packages/@rescript/belt/src/Belt_List.resi 758,744 759,816 +0.14%
packages/@rescript/runtime/Stdlib_TypedArray.res 785,351 786,442 +0.14%
packages/@rescript/belt/src/Belt_MutableMap.res 1,302,290 1,304,051 +0.14%
packages/@rescript/belt/src/Belt_HashSet.res 978,208 979,497 +0.13%
packages/@rescript/runtime/Stdlib.res 980,476 981,750 +0.13%
packages/@rescript/runtime/Primitive_hash.res 964,614 965,812 +0.12%
packages/@rescript/runtime/Stdlib_Array.res 1,281,101 1,282,682 +0.12%
packages/@rescript/belt/src/Belt_HashMapInt.res 1,060,707 1,062,007 +0.12%
packages/@rescript/belt/src/Belt_HashMapString.res 1,061,419 1,062,715 +0.12%
packages/@rescript/runtime/Stdlib_Result.res 1,268,255 1,269,724 +0.12%
packages/@rescript/belt/src/Belt_MapString.res 1,181,899 1,183,218 +0.11%
packages/@rescript/runtime/Primitive_object.res 1,154,866 1,156,154 +0.11%
packages/@rescript/belt/src/Belt_MapInt.res 1,181,363 1,182,680 +0.11%
packages/@rescript/belt/src/Belt_HashMap.res 1,200,049 1,201,371 +0.11%
packages/@rescript/belt/src/Belt_MutableSetString.res 1,665,801 1,667,599 +0.11%
packages/@rescript/belt/src/Belt_SetInt.res 1,289,624 1,290,971 +0.10%
packages/@rescript/belt/src/Belt_SetString.res 1,290,353 1,291,700 +0.10%
packages/@rescript/runtime/JsxEvent.res 1,090,874 1,091,998 +0.10%
packages/@rescript/runtime/Dom.res 1,071,712 1,072,790 +0.10%

Instructions

In total: 9,221,420,308 → 9,224,980,750 (+0.04%).

Benchmark Base Head Change
stress/InlineChain.res 138,211,120 138,540,277 +0.24%
packages/@rescript/belt/src/Belt_List.res 118,137,041 118,385,403 +0.21%
packages/@rescript/belt/src/Belt_internalAVLtree.res 136,418,943 136,620,812 +0.15%
stress/LetRec.res 1,377,898,294 1,379,803,216 +0.14%
packages/@rescript/runtime/JsxDOM.res 117,112,499 117,238,312 +0.11%
packages/@rescript/runtime/Stdlib_Temporal_PlainDateTime.res 25,529,043 25,555,676 +0.10%

Output size

In total: 25,987,723 → 25,991,048 (+0.01%).

Benchmark Base Head Change
output/playground/compiler.js 1,889,042 1,892,367 +0.18%

Pull request d5158ff compared with base 45dba2c in this run.

@github-actions

Copy link
Copy Markdown

…types under -bs-emit-ts

Why:
    Multi-module programs, non-function exports, tail-recursive functions
    and local refs or deferred initializations need five extensions under
    `-bs-emit-ts` so both `tsc --strict` and TScert accept the emitted
    TypeScript:
    - Same-package ML module imports use the emitted TypeScript suffix
      (`.res.ts`, `.mts`, `.cts`), and `Js_ts_collect` resolves cross-module
      type dependencies with `Bundler` resolution and that suffix so
      function signatures, value bindings and type declarations import
      types from `./Mod.res.ts`.
    - Top-level non-function bindings collect their monomorphic types from
      the typed tree, propagate annotations across `Lam_coercion`'s
      `Ident.rename`, and print immutable bindings as `export const x: T = …`
      rather than live `export let` bindings.
    - Inline export checks compare the printed name from `Ext_pp_scope`
      against `Ext_ident.convert id.name` (excluding `default`), so
      reserved names such as `eval` print `export function $$eval` while
      scope-collision renames stay in `export { … }`.
    - Tail-call lowering (`Lam_compile`) propagates parameter annotations
      and overload origins when introducing `_param`.
    - `Js_stmt_make.define_variable` retains `= undefined` under
      `-bs-emit-ts`, `Js_ts_collect` records monomorphic local binding
      types and record/tuple field types, `Lam_pass_sroa` propagates field
      types to scalar-replaced locals (such as `ref(None)`), and `Js_dump`
      annotates uninitialized or `undefined`-initialized locals.

JS modified (-bs-emit-ts cross-module imports and const/reserved exports):
Example:
    // Expr.res: type expr = Lit(int) | ...
    let zero = Lit(0)
    // Eval.res:
    let eval = (e: Expr.expr) => Expr.simplify(e)
Before (js):
    // Expr.res.ts
    let zero = { TAG: "Lit", _0: 0 };
    export { zero, }

    // Eval.res.ts
    import * as Expr from "./Expr.res.js";
    function $$eval(e: Expr_expr): Expr_expr {
      return Expr.simplify(e);
    }
    export { $$eval, }
After (js):
    // Expr.res.ts
    export const zero: expr = { TAG: "Lit", _0: 0 };

    // Eval.res.ts
    import * as Expr from "./Expr.res.ts";
    import type {expr as Expr_expr} from './Expr.res.ts';
    export function $$eval(e: Expr_expr): Expr_expr {
      return Expr.simplify(e);
    }

JS modified (-bs-emit-ts tail-call parameter and uninitialized local types):
Example:
    let rec unwrapNeg = (e: expr): expr =>
      switch e {
      | Neg(Neg(inner)) => unwrapNeg(inner)
      | _ => e
      }
    let find = (xs: array<int>) => {
      let found = ref(None)
      …
      found.contents
    }
Before (js):
    export function unwrapNeg(_e): expr {
      while (true) { … }
    }
    export function find(xs: number[]): (undefined | number) {
      let found;
      …
      return found;
    }
After (js):
    export function unwrapNeg(_e: expr): expr {
      while (true) { … }
    }
    export function find(xs: number[]): (undefined | number) {
      let found: (undefined | number) = undefined;
      …
      return found;
    }

Review: Does JavaScript or genType output change outside -bs-emit-ts? No:
all emission and annotation hooks are gated on `Js_ts_annot.enabled ()`.

Signed-off-by: Cristiano Calcagno <cristianoc@users.noreply.github.com>
Add a two-module AST and evaluator (`Expr` and `Eval`) to
`tests/build_tests/emit_ts` along with an audited `Primitive_int.d.mts`
contract for `Primitive_int.div`, exercising cross-module `.res` imports
of types and values, recursive variants, tail recursion, non-function
`const` exports, `result`, `@unboxed` and polymorphic variants, `ref`
with `while`/`for` loops, array writes, and mutable record fields.
`tsc.txt` remains empty (0 diagnostics), and all 12 generated modules
(59/59 units) verify under TScert `single-pass` (`0406f7e50`).

Signed-off-by: Cristiano Calcagno <cristianoc@users.noreply.github.com>
@cristianoc
cristianoc removed this pull request from stack #9214 November 24, 2026 04:28
@cristianoc
cristianoc marked this pull request as ready for review November 24, 2026 04:28
@cristianoc cristianoc changed the title TScert: print TypeScript for verification under experimental -bs-emit-ts DEMO: print TypeScript for TScert verification under experimental -bs-emit-ts Nov 24, 2026
Why:
    A mutable local binding (`property = Variable`, such as an SROA-unboxed
    `ref(All)` holding a string-union variant) widens in TypeScript when
    printed without a type annotation (`let filter = "All"` infers `string`,
    which fails when returned at `filter`). Annotating mutable locals with
    their collected monomorphic type keeps the narrowed union type intact.

JS modified (-bs-emit-ts mutable local bindings):
Example:
    let parseFilter = (flag: bool): TodoModel.filter => {
      let filter = ref(TodoModel.All)
      if flag { filter := TodoModel.Active }
      filter.contents
    }
Before (js):
    export function parseFilter(flag: boolean): TodoModel_filter {
      let filter = "All";
      if (flag) {
        filter = "Active";
      }
      return filter;
    }
After (js):
    export function parseFilter(flag: boolean): TodoModel_filter {
      let filter: TodoModel_filter = "All";
      if (flag) {
        filter = "Active";
      }
      return filter;
    }

Review: Does JavaScript output change outside -bs-emit-ts? No: the
annotation branch is gated on `Js_ts_annot.enabled ()`.

Signed-off-by: Cristiano Calcagno <cristianoc@users.noreply.github.com>
Add a usable, styled Todo web app split across three ReScript modules
(`TodoModel`, `TodoView`, `TodoApp`) plus a thin Node 26 HTTP adapter
(`todo-server.mts`) to `tests/build_tests/emit_ts`. The verified ReScript
core covers priorities, filters, search, inline editing, toggle-all,
clear-completed, HTML escaping, URL/query parsing, variant-driven routing,
and JSON responses, with zero `runtime-dts/` contracts. `tsc.txt` stays
empty (0 diagnostics), all 15 modules (95/95 units; 36/36 for the Todo
app) verify under TScert `single-pass` (`0406f7e50`), and all HTTP routes
pass live against `todo-server.mts` on Node 26.

Signed-off-by: Cristiano Calcagno <cristianoc@users.noreply.github.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant