diff --git a/.github/actions/solid-next/action.yml b/.github/actions/solid-next/action.yml new file mode 100644 index 000000000..528cff442 --- /dev/null +++ b/.github/actions/solid-next/action.yml @@ -0,0 +1,22 @@ +# Solid 2 at ref/SOLID_NEXT, built beside the repository (ref/scripts/solid-next.sh) — once per pin, then from the cache. +# A cache's path may not hold `..`: the one written so was never kept, and every run built Solid again (four minutes). +# Needs a Rust toolchain, Node and pnpm. +name: Solid next +description: Solid at ref/SOLID_NEXT, built or restored at ../solid-next +runs: + using: composite + steps: + - id: at + shell: bash + run: echo "dir=$(dirname "$GITHUB_WORKSPACE")/solid-next" >> "$GITHUB_OUTPUT" + - id: cache + uses: actions/cache@v4 + with: + path: ${{ steps.at.outputs.dir }} + key: solid-next-v2-${{ runner.os }}-${{ hashFiles('ref/SOLID_NEXT', 'ref/scripts/solid-next.sh') }} + - if: steps.cache.outputs.cache-hit != 'true' + shell: bash + run: | + sh ref/scripts/solid-next.sh + # what built the native compiler is not kept, only what it built + find "${{ steps.at.outputs.dir }}" -type d -name target -not -path "*/node_modules/*" -prune -exec rm -rf {} + diff --git a/.github/workflows/bench.yml b/.github/workflows/bench.yml new file mode 100644 index 000000000..18ca51102 --- /dev/null +++ b/.github/workflows/bench.yml @@ -0,0 +1,82 @@ +# The representative-task benchmark (bench/README.md): each task is a job a Solid user does with a library of the +# ecosystem — its good program accepted by both checkers, typed by the library's own types and run in Chromium, its +# one-line mistakes refused. The run is compared with bench/scorecard.json: a check that is green there may not turn +# red, and a check that is red is one its task's `known` gives the reason for. And the coverage suite: every package of +# the libraries bench/coverage/libraries.json lists, drafted whole and used once, compared with bench/coverage/coverage.json. +# +# The tasks over two machines, several at once (BENCH_JOBS), and the coverage suite over two. `--shard i/2` is every second task, entry and +# module no entry drafts; each shard holds the whole list (bench/coverage.mjs). +name: bench + +on: + push: + branches: [main] + paths: ["compiler/**", "ref/**", "runtime/**", "tooling/rx-language-server/**", "bench/**", ".github/workflows/bench.yml", ".github/actions/solid-next/**"] + pull_request: + paths: ["compiler/**", "ref/**", "runtime/**", "tooling/rx-language-server/**", "bench/**", ".github/workflows/bench.yml", ".github/actions/solid-next/**"] + workflow_dispatch: + +jobs: + bench: + name: ${{ matrix.name }} + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + include: + - { name: tasks 1/2, run: "--tasks-only --shard 1/2" } + - { name: tasks 2/2, run: "--tasks-only --shard 2/2" } + - { name: coverage 1/2, run: "--coverage-only --shard 1/2" } + - { name: coverage 2/2, run: "--coverage-only --shard 2/2" } + # 11 CP-8g: the same tasks type-checked by tsrs through the crate's content mapper, compared with rx-tsc + - { name: mapper, run: "" } + steps: + - uses: actions/checkout@v5 + - uses: dtolnay/rust-toolchain@stable + with: + targets: wasm32-unknown-unknown # the WebAssembly builds below + - uses: Swatinem/rust-cache@v2 + with: + workspaces: compiler + - uses: pnpm/action-setup@v4 + with: + version: 11.1.1 # solid-next's packageManager + - uses: actions/setup-node@v5 + with: + node-version: 24 + - name: Solid next, at the pin (the runtime and bench/package.json link ../solid-next) + uses: ./.github/actions/solid-next + - name: The crate (rxc, the Node-API build Solid's Vite plugin loads, and the WebAssembly builds the language server loads) + working-directory: compiler + run: | + npm ci + cargo build --release + npx napi build --platform --release --features node --manifest-path ./Cargo.toml -- --lib + # what rx-declare reads a package's code with (compiler/words): without it every draft is "the code could not be + # read" — no word proven, every one a question (DECISION.md "Bench on GitHub vs local"); and the crate's, which + # rx-tsc and rx-declare ask in process, as scripts/ci and scripts/setup.sh build them + cargo build --lib --release --target wasm32-unknown-unknown + cargo build -p rx-words --release --target wasm32-unknown-unknown + - name: The runtime + run: npm --prefix runtime ci && npm --prefix runtime run build + - name: The language server's packages (rx-tsc) + run: npm --prefix tooling/rx-language-server ci + - name: The libraries, and Chromium + run: | + # from the lockfile, as bench/harness.mjs installs them: every machine resolves the same tree + mkdir -p bench/.out/ws && cp bench/package.json bench/package-lock.json bench/.out/ws/ + (cd bench/.out/ws && npm ci --no-audit --no-fund --legacy-peer-deps && cp package-lock.json node_modules/.installed-from-lock && npx playwright install --with-deps chromium) + - name: The benchmark's own counting + if: matrix.name != 'mapper' + run: RXC=$GITHUB_WORKSPACE/compiler/target/release/rxc node bench/measure.test.mjs + - name: A generated declaration refuses nothing an import with none is accepted for + if: startsWith(matrix.name, 'tasks') + run: node --experimental-strip-types --no-warnings bench/generated.mjs --shard ${{ endsWith(matrix.name, '1/2') && '1/2' || '2/2' }} + - name: The benchmark, against bench/scorecard.json and bench/coverage/coverage.json + if: matrix.name != 'mapper' + env: + BENCH_JOBS: 4 # the machine is this job's alone: every core (by default, half) + run: node bench/run.mjs ${{ matrix.run }} --check --strict + - name: "The content mapper's cross-check: every task without a prepare step and examples/shop, by tsrs -p … --runExternalCode over `rxc project --store`, against rx-tsc by file, line, column, code and message (11 CP-8g)" + if: matrix.name == 'mapper' + run: node --max-old-space-size=2048 bench/mapper.mjs diff --git a/.github/workflows/editor.yml b/.github/workflows/editor.yml index 10042da9b..6ee0600aa 100644 --- a/.github/workflows/editor.yml +++ b/.github/workflows/editor.yml @@ -13,9 +13,9 @@ name: editor on: push: branches: [main] - paths: ["compiler/**", "tooling/**", ".github/workflows/editor.yml"] + paths: ["compiler/**", "tooling/**", "runtime/**", "ref/compile/rt-*.ts", "scripts/parallel.mjs", ".github/workflows/editor.yml", ".github/actions/solid-next/**"] pull_request: - paths: ["compiler/**", "tooling/**", ".github/workflows/editor.yml"] + paths: ["compiler/**", "tooling/**", "runtime/**", "ref/compile/rt-*.ts", "scripts/parallel.mjs", ".github/workflows/editor.yml", ".github/actions/solid-next/**"] workflow_dispatch: jobs: @@ -39,15 +39,23 @@ jobs: run: | cargo build --release --manifest-path compiler/Cargo.toml cargo build --lib --release --target wasm32-unknown-unknown --manifest-path compiler/Cargo.toml + cargo build -p rx-words --release --target wasm32-unknown-unknown --manifest-path compiler/Cargo.toml - name: Solid next (the types the tests check against) - run: sh ref/scripts/solid-next.sh && npm --prefix ref install + uses: ./.github/actions/solid-next + - name: ref/'s packages + run: npm --prefix ref install + - name: The runtime (test/tsc.js checks an entry against its types) + run: npm --prefix runtime ci && npm --prefix runtime run build - name: Language server tests working-directory: tooling/rx-language-server run: | npm ci - node test/run.js + # over the WebAssembly build, then (test/run.js) over rxc. words: what rx-declare reads from the code (09 + # MO-8v, MO-8w) — every function that does what a word must not cover is refused it, and its honest twin is + # given it; the audit; the draft; rx-verify + # (not test/generate.js, which runs `vite build` and needs the Node-API build this job does not make) + RX_JOBS=4 node ../../scripts/parallel.mjs "node test/checker.js" "node test/tsc.js" "node test/declare.js" "node test/verify.js" "node test/words.js" "node test/words-audit.js" "node test/words-cases.js --shard 1/2" "node test/words-cases.js --shard 2/2" "node test/run.js" RXC=$GITHUB_WORKSPACE/compiler/target/release/rxc node test/run.js - node test/tsc.js - name: Package the extension working-directory: tooling/vscode-rx run: | diff --git a/.github/workflows/runtime.yml b/.github/workflows/runtime.yml index edd57c77c..753521f9d 100644 --- a/.github/workflows/runtime.yml +++ b/.github/workflows/runtime.yml @@ -1,5 +1,6 @@ # The runtime's npm package, @reactivescript/runtime (runtime/): built from ref/compile/rt-web.ts and rt-server.ts, -# tested against the Solid release it names, with a program the crate compiles. +# tested against the Solid ref/ runs on (ref/SOLID_NEXT, built beside the repository: its devDependencies link +# ../solid-next, and `npm pack` ships none of them, runtime/pack.mjs), with a program the crate compiles. # # A release is a version bump merged to main, once the repository variable RELEASES is `on`: a version npm does not # have is published by trusted publishing (OIDC, no token) and tagged `runtime-v`. @@ -8,9 +9,9 @@ name: runtime on: push: branches: [main] - paths: ["runtime/**", "ref/compile/rt-web.ts", "ref/compile/rt-server.ts", "compiler/**", ".github/workflows/runtime.yml"] + paths: ["runtime/**", "ref/compile/rt-web.ts", "ref/compile/rt-server.ts", "ref/compile/prims-solid.ts", "ref/compile/solid-internals.ts", "ref/SOLID_NEXT", "ref/scripts/solid-next.sh", "compiler/**", ".github/workflows/runtime.yml", ".github/actions/solid-next/**"] pull_request: - paths: ["runtime/**", "ref/compile/rt-web.ts", "ref/compile/rt-server.ts", "compiler/**", ".github/workflows/runtime.yml"] + paths: ["runtime/**", "ref/compile/rt-web.ts", "ref/compile/rt-server.ts", "ref/compile/prims-solid.ts", "ref/compile/solid-internals.ts", "ref/SOLID_NEXT", "ref/scripts/solid-next.sh", "compiler/**", ".github/workflows/runtime.yml", ".github/actions/solid-next/**"] workflow_dispatch: jobs: @@ -22,9 +23,14 @@ jobs: - uses: Swatinem/rust-cache@v2 with: workspaces: compiler + - uses: pnpm/action-setup@v4 + with: + version: 11.1.1 # solid-next's packageManager - uses: actions/setup-node@v5 with: - node-version: 22 + node-version: 24 + - name: Solid next, at the pin (the runtime's devDependencies link ../solid-next) + uses: ./.github/actions/solid-next - name: The compiler's Node-API build (the test compiles a program) working-directory: compiler run: | @@ -37,6 +43,9 @@ jobs: npm run build npm test npm pack + - name: The peer range against npm's newest Solid (the same test, on a release) + working-directory: runtime + run: node npm.mjs - uses: actions/upload-artifact@v4 with: name: runtime diff --git a/.github/workflows/suites.yml b/.github/workflows/suites.yml new file mode 100644 index 000000000..096af20e5 --- /dev/null +++ b/.github/workflows/suites.yml @@ -0,0 +1,129 @@ +# The suites CONTRIBUTING.md lists ("Running the suite"), on every change to what they read: the crate's own tests, the +# reference implementation's (ref/: the interpreter over every scenario, the same scenarios lowered onto Solid, the +# compiled modules, streamed SSR and hydration in Chromium, the TSX projection), the crate against ref/ in each of its +# modes (CP-5: checked, client-only, whole-program, lowered, projected), and the three suites that run a guarantee +# rather than a list of cases (compiler/test/confined.mjs, drafts.mjs), with what an app must install to run at all +# (compiler/test/runtime-resolve.mjs). +# +# ref/ runs on Solid built from source at ref/SOLID_NEXT (ref/scripts/solid-next.sh: pnpm, and a Rust build of Solid's +# native compiler). That build is kept in a cache keyed by the pin, so it is made once per pin and restored after +# (.github/actions/solid-next; editor.yml's job reads the same one). +# +# ref/'s runners are one job, not several: with Solid restored and the SSR scenarios run by several processes it is about +# four minutes, half of them the setup each job of a split would do again (Solid, the crate, Chromium, the runtime). +name: suites + +on: + push: + branches: [main] + paths: ["compiler/**", "ref/**", "runtime/**", "scenarios/**", "examples/**", "bench/**", "spec/**", "scripts/**", "guide/**", ".github/workflows/suites.yml", ".github/actions/solid-next/**"] + pull_request: + paths: ["compiler/**", "ref/**", "runtime/**", "scenarios/**", "examples/**", "bench/**", "spec/**", "scripts/**", "guide/**", ".github/workflows/suites.yml", ".github/actions/solid-next/**"] + workflow_dispatch: + +jobs: + # the crate's own tests (compiler/src's units, compiler/tests/) + cargo: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + - uses: dtolnay/rust-toolchain@stable + - uses: Swatinem/rust-cache@v2 + with: + workspaces: compiler + key: test + - name: cargo test + working-directory: compiler + run: cargo test --release + + # ref/'s runners, and the crate against ref/ + ref: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + - uses: dtolnay/rust-toolchain@stable + with: + targets: wasm32-unknown-unknown # the WebAssembly builds below + - uses: Swatinem/rust-cache@v2 + with: + workspaces: compiler + - uses: pnpm/action-setup@v4 + with: + version: 11.1.1 # solid-next's packageManager + - uses: actions/setup-node@v5 + with: + node-version: 24 + - name: Solid next, at the pin + uses: ./.github/actions/solid-next + - name: ref/ (links ../solid-next), and Chromium + run: | + npm --prefix ref install + (cd ref && npx playwright install --with-deps chromium) + - name: The crate (rxc, and the Node-API build) + working-directory: compiler + run: | + npm ci + cargo build --release + npx napi build --platform --release --features node --manifest-path ./Cargo.toml -- --lib + # what rx-declare reads a package's code with (compiler/words), and the crate's, which it asks in process: + # ref/mutants and ref/srcmap read the benchmark's tasks over the drafts of their packages (bench/declared.mjs) + cargo build --lib --release --target wasm32-unknown-unknown + cargo build -p rx-words --release --target wasm32-unknown-unknown + - name: The runtime + run: npm --prefix runtime ci && npm --prefix runtime run build + - name: "the runtime as built: both builds, the request's and the render's state, and Solid's contract (the installed release and the pin)" + working-directory: runtime + run: SOLID_NEXT="${{ github.workspace }}/../solid-next" node test.mjs + - name: "a name is its binding's: every function of the language under every kind of binding (MO-1d)" + run: node --experimental-strip-types compiler/test/names.mjs + - name: "spellings: one mistake through many forms of JavaScript, refused by both checkers (02 W-1a, C-3)" + run: node --experimental-strip-types ref/spellings.ts + - name: "spec: every rule and diagnostic that is named is in it" + run: node scripts/spec-refs.mjs + - name: "the crate's structure: compiler/src's layering and file sizes, a ratchet (11 CP-9), and its planted defects" + run: node scripts/structure.mjs && node scripts/structure.test.mjs + - name: "ref: the interpreter over every scenario" + working-directory: ref + run: npm test + - name: "ref: the scenarios lowered onto Solid (the oracle)" + working-directory: ref + run: npm run oracle + - name: "ref: compiled modules" + working-directory: ref + run: npm run compiled + - name: "ref: streamed SSR and hydration in Chromium" + working-directory: ref + run: RX_JOBS=4 npm run ssr # it waits more than it works + - name: The language server's packages (the checker ref's types are asked of, and rx-tsc) + run: npm --prefix tooling/rx-language-server ci + - name: "ref: the TSX projection, checked by the tooling's checker (tsrs, TypeScript 7)" + working-directory: ref + run: npm run types + - name: "crate against ref/: checked, client-only (--spa), the whole program (--whole-program), lowered (--lower), projected (--project: the same text, each mapping the same text on both sides and the occurrence the syntax tree says), and each again with characters of several bytes (--text)" + working-directory: ref + run: RX_JOBS=4 node ../scripts/parallel.mjs "npm run -s crate" "npm run -s crate -- --spa" "npm run -s crate -- --whole-program" "npm run -s crate -- --lower" "npm run -s crate -- --project" "npm run -s crate -- --text" "npm run -s crate -- --text --lower" "npm run -s crate -- --text --project" + - name: "the guarantees, run: drafts (MO-10i)" + run: node compiler/test/drafts.mjs + - name: "the library build: a package written in .rx (MO-13e)" + run: node compiler/test/lib.mjs + - name: The libraries confined.mjs runs against (bench/package.json) + run: | + # from the lockfile, as bench/harness.mjs installs them: every machine resolves the same tree + mkdir -p bench/.out/ws && cp bench/package.json bench/package-lock.json bench/.out/ws/ + (cd bench/.out/ws && npm ci --no-audit --no-fund --legacy-peer-deps && cp package-lock.json node_modules/.installed-from-lock) + - name: "test262: the expressions .rx lexes itself, against test262's (ref/test262: both checkers, the crate's three targets run, ref's interpreter and compiler; the expected failures only shrink)" + run: RX_JOBS=2 node --max-old-space-size=2048 ref/test262/run.mjs + - name: "mutants: the examples' and the benchmark's programs broken a token at a time (ref/mutants: no crash or hang, one verdict from both checkers, few diagnostics, what is accepted compiled alike, run and typed; the expected failures only shrink)" + run: RX_JOBS=2 node --max-old-space-size=2048 ref/mutants/run.mjs + - name: "broken modules: what the importer of a module that does not parse, does not check, lacks an export or is not there is told, on every surface (ref/broken: rxc check, --json, rxc app, the Vite front end, ref's checker, the language server, rx-tsc; the expected failures only shrink)" + run: node --max-old-space-size=2048 ref/broken/run.mjs + - name: "source maps: each identifier of the compiled output (rxc lower, rxc app; dom, ssr, universal; production and development) and of the TSX projection (rxc project, --store) mapped onto a .rx line that holds it, and runtime errors (MO-10i's lent copy, ST-4d, DEV-3f, a helper's throw) on their .rx line (ref/srcmap; the expected failures only shrink)" + run: RX_JOBS=2 node --max-old-space-size=3072 ref/srcmap/run.mjs + - name: "the guarantees, run: the counterexamples and their controls, in Chromium (CN-7)" + run: node compiler/test/confined.mjs + - name: What unmounted is collected; a package under a JavaScript host + run: node compiler/test/leaks.mjs && node compiler/test/js-host.mjs + - name: "server fns in a Vite app: refused with the plugin's pass off, no body in a client bundle, each request's own app, failures across the wire (12 SF-7a)" + run: node compiler/test/server-fns.mjs + - name: "an app that lists only the compiler: the runtime nested, hoisted, and listed nowhere, under start mode's dev server and its build (CP-4a)" + run: node compiler/test/runtime-resolve.mjs diff --git a/.github/workflows/tree-sitter.yml b/.github/workflows/tree-sitter.yml new file mode 100644 index 000000000..373fc5a28 --- /dev/null +++ b/.github/workflows/tree-sitter.yml @@ -0,0 +1,38 @@ +# The tree-sitter grammar (tooling/tree-sitter-rx): src/ is generated but committed, since Zed compiles src/parser.c +# as it is, so check it is what grammar.js generates; then the corpus, and every tracked .rx file with no ERROR or +# MISSING node. +name: tree-sitter + +on: + push: + branches: [main] + paths: ["tooling/tree-sitter-rx/**", "**/*.rx", ".github/workflows/tree-sitter.yml"] + pull_request: + paths: ["tooling/tree-sitter-rx/**", "**/*.rx", ".github/workflows/tree-sitter.yml"] + workflow_dispatch: + +jobs: + grammar: + runs-on: ubuntu-latest + defaults: + run: + working-directory: tooling/tree-sitter-rx + steps: + - uses: actions/checkout@v5 + - uses: pnpm/action-setup@v4 + with: + version: 11.1.1 # as editor.yml + - uses: actions/setup-node@v5 + with: + node-version: 22 + - run: pnpm install --frozen-lockfile + - name: src/ is what grammar.js generates + run: | + pnpm run generate + git diff --exit-code -- src/ + - name: Corpus + run: pnpm test + - name: Every tracked .rx file + run: pnpm run parse:repo + - name: Queries + run: pnpm run query -- ../../examples/*.rx > /dev/null diff --git a/.gitignore b/.gitignore index af5ba1fb7..d537e51b5 100644 --- a/.gitignore +++ b/.gitignore @@ -11,3 +11,5 @@ compiler/compiler.wasi-browser.js compiler/wasi-worker.mjs compiler/wasi-worker-browser.mjs compiler/guide/ +/.out/ +/runtime/*.tgz diff --git a/CHANGELOG.md b/CHANGELOG.md index 72ea93c6b..54a8f61d4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,8 +2,1569 @@ ## Unreleased +**A row kept by itself stays as it was; a writer reached through a record's field is refused; messages that print the +edit** (round G, re-check 17) + +- **Fixed (wrong at run time, compiled only): a keyed row written into another source by itself or inside a record.** + `selected := todos[0]`, `snap := { row: todos[0] }` and `lastRow := t` in a source whose first value is `null` kept the + row the next whole write changed: every holder followed the edit, and a revert put back nothing, in both builds (the + interpreter was right). Such a source now holds what it is written, in every runtime (06 ST-4a). +- **New advice, `KEPT_ROW`:** where a source keeps a row by itself and the keyed list is written whole, the selection + no longer follows the edit; the advice prints the edit that keeps the key (`source selectedId: T["id"] | null := + null`, `selected = todos.find((r) => r.id == selectedId) ?? null`, `selectedId := t.id`). +- **Refused now (it showed the older answer): a writer reached through a record's field** in a `.then` or a library's + `handler` callback — `p.put(r)` of a context's value, `{ put } = use panel`, `props.api.put(r)`, the component's own + `api.put(r)`, `later(v, ms, p.put)` (06 AC-1n). The awaited form is printed, as for a prop's function. +- **Accepted now:** `import reads { f }` of a module with no `.d.rx`, called by a closure given to a library + (TanStack's `queryFn: (ctx) => fetchPhotos(ctx.pageParam)`): the only other word offered was `pure`, false of a fetch. +- **Messages that print the edit:** a closure's pattern parameter (`({ pageParam }) => …` prints `(ctx) => + fetchPhotos(ctx.pageParam)`); UNHANDLED_FAILURE read by an `if` or an attribute (the `{if …}` or the element + wrapped); TWO_ASYNC_WRITERS where no one action is printed (each write functional, `failure := _ => e.message`); + `` in `` (the ``); AWAIT_THEN_CALL for a prop's or a context's function (its steps as an action). +- **Development console:** Solid's `IMMUTABLE_UPDATE_IN_STORE` no longer fires on the runtime's own deliberate writes + (a held row left as it was, a path written whole), whose advice W-1a forbids following. +- **Docs:** the README's tsconfig targets ES2023 (the guide uses `toSorted`); libraries.md says a server fn's undeclared + failure reaches the browser as `Internal Server Error`; a per-keystroke history keeps its input's focus with a history + of copies. + +**A keyed list's history stays as it was; a callback's write through a call is refused** (round F, re-check 16) + +- **Fixed (wrong at run time): undo, redo and a saved copy of a keyed list.** `source todos: T[] key id` with + `past := p => [...p, todos]; todos := todos.map(…)` kept the rows themselves, and the keyed write changed them where + they were: the history showed the list as it is now, in both builds. A row that something else holds is now left as + it was, and the list takes the written row (06 ST-4a). *What changes for a program that relied on it:* a row kept in + another source (`selected := row`) no longer follows a later whole write of the list, as it never did for a list with + no key — read the row by its key (`selected = todos.find((t) => t.id == selectedId)`), or write the field along its + path. A row that is kept and then changed by a whole write is a new row: its region is made again. +- **Fixed: a guessed source kept in a history** followed every later write. What keeps it keeps its value. +- **Refused now (it showed the older answer): a callback that writes through a call** — `.then(done)` with a closure + that writes, `.then(r => set(r))`, `.then(r => props.onDone(r))`, a prop's function handed to a library's `handler` + parameter, and any of these in a handler written with no braces. `LATE_CALLBACK_WRITE` prints the awaited form where + it is accepted: in the handler, or as a declared action with a name of its own. +- **Accepted now:** `as T` (and `as const`) after a list, a record or a literal written out, in any scope: `{for col in + ["todo", "doing", "done"] as Col[] {`. +- **Messages:** a `.finally`'s steps are kept in the printed `try … finally`, with `onFlush` for a flag set before the + chain; AWAIT_THEN_CALL gives each printed action a name of its own; TWO_ASYNC_WRITERS prints the one action for an action + and a handler; ALIASED_STATE reads a list kept through an action's argument. +- **New advice, `PENDING_NEVER`:** `pending? x` of a source that only an action's write after its `await` changes, with + no `affects x`, is never true; the advice names the statement to write. +- **`rx-declare ./src/api.js --out ./src/api.d.rx`** run from the project's root names the module as the draft's own + file reaches it (it wrote `import("./src/api.js")`, which rx-tsc could not find). + +**A library's words are the app's: no library's declaration is shipped** (round D2, the declarations review's stages 0–2) + +- **Removed:** `@rx-types/solidjs__router`, `@rx-types/tanstack__solid-query` and `@rx-types/solid-i18next` (the + folders under `declarations/`, `shared.mjs`, `shared-not-held.json`). One of their words was false: + `uses(queryClient)` on `useQuery`, whose second argument is a client — `useQuery(opts, () => client)` reads no + provider, and was refused (`CONTEXT_NOT_FOUND`). It is accepted now. Solid's own, `@rx-types/solid-js`, stays. +- **A draft declares each context the package makes with no default** (`export context router`, `export context + queryClient`: named after the export, `Context` left off), with no word on any row (draft format 27). A project's + `extend fn useParams uses(router)`, and a router module's `export context router from "@solidjs/router"`, name it with + no other declaration. +- **What you write instead, printed where it is needed:** a callback the library calls later (`extend fn + useMutation(options: { onSuccess: handler })`), a class whose instance lives with the component (`extend class + QueryClient instantiates`), and now a router that renders each route record's `children` inside its `component` + (`extend fn createRouter nests(children in component)`, printed by `UNHANDLED_FAILURE` on a page whose layout holds + the failure), each with the file to paste it into, `rx-types/.d.rx`. `NOT_EXPORTED` for a context prints the + line and the file. With no word, a router or query hook outside its provider compiles (Solid's development build stops + it); with `uses`/`provides` in `rx-types/`, it is `CONTEXT_NOT_FOUND` (guide/libraries.md has the rows most apps write). + +**A smaller runtime in every bundle** (the runtime study's steps 0–2) + +- **Compiled modules import the runtime's helpers by name** (11 CP-4b): a bundler keeps what a program uses. A counter is + 18.8 KB gzip (was 54.6; plain Solid 11.7), 1,000 rows 30.1 (56.6), a search with an action and a guess 47.5 (58.0), a + page over server fns 43.6 (69.8); `bench/size.mjs` holds the four. Behaviour is unchanged. +- **A package compiled by an older version is refused where an app instantiates it**, saying to build it again: its + modules called the runtime through what they were handed, which no runtime hands out now. Rebuild `.rx` packages + (`rx-lib`). A JavaScript host's own factory given to `library()` is taken as before. + +**Correct code refused, and fixes that did not paste** (re-check 13's C2 and C3, round C2) + +- **New words, held by rx-verify:** `@rx-types/tanstack__solid-query`'s `QueryClient` is `instantiates`: `client = new + QueryClient()` where the component is made, or at the module's top level, is accepted with no word of yours (it was + `IO_IN_REACTIVE`). `useQuery`'s `data` is `pending fails(Error)`: a query's data read with no `errored` region above + it is refused, and with no `loading` region in a client-only build (it was accepted; rx-tsc said it was not checked). + Written inline in a prop, `client={new QueryClient()}` is now `INSTANTIATION_NOT_BOUND`, as every instantiating call + is, with the binding printed. +- **rx-verify:** holds a constructor's `instantiates` by running it (two calls, two instances of their own, nothing written + outside them), and its `failing` mutation no longer reads the part it replaces (a getter that throws, as a query's + `data` does, threw in the mutant too, and `fails` was "not evidence"). A shared declaration may say words over its own + draft with `extend` rows above `//@ drafted below`. rx-tsc counts a held `instantiates` as verified. +- **Messages that paste:** `ASSIGNMENT` on an element or a field of a local (`a[i - 1] = a[i]` in an updater) prints the + new list, `let a2 = a.with(i - 1, a[i])` (it printed `:=`, which is `WRITE_TO_NON_SOURCE` there); `UNBOUND` on a + built-in given as a value (`setInterval`) prints the module of the app's that exports it; `CALL_AT_TOP` on a primitive + called as a statement prints the binding, `timer = createTimer(…)`; `IO_IN_REACTIVE` on an io loader awaited in an + equation offers `reads` (`export reads fn fetchTeam`), which is true of a loader, where it offered `pure` alone; the + R-io-5 refusal of a `reads` class writes `new C(…)`, no `await`, and names `instantiates`. rx-tsc says what to write + beside TypeScript's TS2345 where Solid's accessor `() => e` is given to a `ref` parameter (write `e`). +- **Fixed:** rx-tsc and the editor placed an `ASSIGNMENT` at a correct `:=` before the wrong statement (35:36 where rxc + said 35:147). `rxc check` and `ref/check.ts` read the project as rx-tsc does — the tsconfig's + `reactivescript.spa`, else a vite.config that builds for the client alone — and say what `vite build` refuses without + `--spa` (`--no-spa` says not). In development, a method of a `pure`-imported object called in a view (`{marked.parse( + text)}` after `marked.use(…)`) is asked again by the MO-15d audit and told when it goes stale. +- **Docs:** `guide/libraries.md` no longer says `reads` is true of `new QueryClient()` (refused where it is bound): + `instantiates`, which the shared declaration says; a loader you await is `reads`. README: a query's `data` is checked + with the shared declaration alone. + +**Re-check 13, round C1: the run that started last writes, one rule** (06 AC-1l, AC-1h; 05 DV-32) + +- **Changed (semantics):** when a later run of the same action — declared, or a handler that awaits (AC-1b) — has + started, what an older run writes after its `await` is dropped, whatever it writes and however: its answer, a + constant (a cleared box, "no results"), a `catch` value, the answer through a fn, a helper action, a closure, or a + path such as `state.results`. Round A dropped only a write of the run's own answer to a whole source, and re-check 13 + found six spellings it missed (a handler, a constant, a `catch` value, a fn, a helper action, a path), each showing + the older query's answer in both builds with nothing said. Still landing from every run: functional writes + (`n := v => v + 1`, `xs := v => [...v, r]`), a path the run's own values choose (`done[id] := …`), a guess, and any + write before the run's first `await`. A write that reads another source (`last := tag + r`) is now dropped like any + other (round A let it land in the order the runs ended). +- **Refused:** a plain write after an `await` computed from its own source read there (`likes := likes + 1`, + `saved := [...saved, r]`) is `STALE_NEXT_READ` in both checkers: two runs out at once each read the same committed + value, so three quick clicks counted one (and plain Solid does the same). The message prints the functional write + from your own text (`likes := v => v + 1`), which counts three. `scenarios/S-action-1` held the shape and is + written functionally now. +- **Lowering:** every source's writer judges its writes by the run that makes them (`ref/compile/answers.ts`); a + handler that is an action lowers to `__rt.inferred((e) => function* () { … })`; a path write in an action whose keys + are written out passes `true`. `__rt.over` stays for an effect's callbacks only. +- **Tests:** `compiler/test/races.mjs` 18 → 70 checks (the re-check 13 shapes in both builds, the landing twins, the + refusals with their printed fix pasted and run; `RACES_TOOLS=c373472e` fails 27), `S-action-8` (interpreter, + compiled; the oracle's plain Solid recorded as DV-32 rows), a guide `before`/`after` pair under `STALE_NEXT_READ` + pasted by `compiler/test/pasted.mjs`. + +**Install from a checkout; a production bundle without the development checks; the router's layouts and TanStack +Query's mutation callbacks in the shared declarations** (re-check 12, the cold start) + +- **New:** `node scripts/pack-local.mjs` builds the compiler, the runtime and the language server from a checkout and + packs them, with the shared declarations, into `.out/local/`. The compiler's tarball carries this machine's native + binary (a plain `npm pack` of `compiler/` has none). README's *Install* now starts there and says that npm's 0.3.1 + packages are behind the repository; nothing is published. The review scorecard moved from README to `STATUS.md`. +- **Changed:** `@reactivescript/runtime`'s browser build is two files: `dist/web.dev.js` for the `development` + condition and `dist/web.js` for production, with every development-only part (the words' checks, `FALSE_WORD` and + the re-ask audit; the lending guard; `EFFECT_LOOP`'s values; hot replacement) left out. Production behaviour is the + same: Solid's production build has no `DEV` either way. A counter's bundle 60.3 → 55.3 KB gzip, the kanban board + 63.4 → 58.3 KB, the cold start's three apps 84.4 → 79.3, 69.8 → 64.7, 76.6 → 71.5 KB; `web.js` 80.2 → 50.1 KB. + `EFFECT_LOOP`'s production form (the inputs named, no values) stays in production. The runtime still pulls in most + of `@solidjs/signals` (spec/archive/known-limits-2026-11-29.md, *round B*). +- **New words, held by rx-verify:** `@rx-types/solidjs__router`'s `createRouter` `nests(children in component)`: a + page under a layout route that wraps `{props.children}` in `errored`/`loading` is covered by those regions (it was + refused: re-check 12's C2-1). `@rx-types/tanstack__solid-query`'s `useMutation` `uses(queryClient)` and `handler` on + `onSuccess`, `onError` and `onSettled`: the callbacks take a closure that writes with no word of yours, and a + `useMutation` outside `QueryClientProvider` is `CONTEXT_NOT_FOUND` (it was accepted, and `mutate` did nothing). +- **Messages:** `VIEW_FN_MISPLACED` on a view lambda given to a component a JS factory made (`{view (p) { … }} + `) names the factory and what to write (a layout route). The `PARSE` of `import * as v` imports a name the + module declares too under another (`email as vEmail`), so the import it prints pastes. `WRITE_TO_NON_SOURCE` on an + imported source says it is no source here. `rx-declare --why` no longer points at a crate's file. +- **Docs:** `guide/libraries.md` opens with *Which word do I write?* (a table by what the call does, and what to do + when you can't tell); `guide/async.md` opens with the submit-with-pending-and-error form; `guide/reference.md` says + why a keyed layer over a query resets a local reorder, and the shape that keeps it; `guide/language.md` says a + namespace import of JavaScript is refused; README no longer promises a note for a query's `data` read with no + regions. +**Re-check 12 and the cold start: answers in order, writes that never show, honest words** (06 AC-1l, AC-1c, AC-1d; +04 R-io-5, R-io-6; 02 W-1a, C-3a; 09 MO-6d, MO-10i, MO-15a–c; 08 CN-3d) + +- **Changed (semantics):** an answer is written by the run that asked last (AC-1l, DV-32). Two runs of one action out + at once (a search per keystroke), or two runs of an effect's apply each handing a callback out: a write of a whole + source whose value is the run's own (what it awaited, its parameters, locals made from them) lands only if no later + run has written that source with its own value. A write that reads anything else lands as before (`n := n + 1`, + `xs := [...xs, r]`). Before this, both builds showed the older query's answer, with nothing said. +- **New advice:** `UNSEEN_WRITE`, a declared action's write before an `await` that it writes again on every way to its + end (a `submitting` flag reset in `finally`): never shown. `ALIASED_STATE`, a source's list or record kept by itself in + another source and written along a path below it (an undo stack). `EFFECT_RELAY_TEAR` now also through an action of + the effect's block. +- **Fixed:** STALE_OWN_READ tells computed keys apart where it can (a parameter plus a number, `i + 1`, or plus a + parameter whose type has no 0, `by: -1 | 1`), and says so where it cannot. +- **Fixed:** the clock and chance (`new Date()`, `Date.now()`, `Math.random()`) are accepted where a `reads` call is, + made once (`source today := new Date()`); refused in a view, as before. +- **Docs and messages:** `pure` is true of a call determined by its arguments, the host's locale and zone and + configuration set where the program starts (R-io-6): `import pure { format } from "date-fns"` is honest where the + program never reconfigures date-fns later. The messages that offer `pure` say so; the once-position hint says when + `reads` is true and that a configuring call (`i18next.init`) belongs in a JavaScript module imported for its effect. +- **Fixed (development):** a `draft` the fn keeps and changes later, a `pure` fn that changes what its `ref` parameter + reads, and a lent copy a JS fn changes after the call are told (`FALSE_WORD [MO-10i]`, `[MO-15a]`, and the lend + guard's "kept what it was given"). Production is unchanged. +- **Fixed (rx-tsc, editor):** a project whose vite.config builds for the client alone is checked as that build is + (`ASYNC_OUTSIDE_LOADING_BOUNDARY`); a default import's `import pure`/`import reads` is counted; a shared declaration + whose package makes state that waits gets the note the README promises. +- **Tests:** `compiler/test/races.mjs` (AC-1l, both builds), `compiler/test/told.mjs` (both checkers and rx-tsc over the + reviews' shapes, with their fixes), words-dev +3, S-action-7. + +**The re-ask audit lets go of an unmounted part at once** (09 MO-15d) + +- **Fixed:** in a development build, the re-ask audit (370e6003) held each equation and call resting on a claimed + `pure` — its fn, its arguments, the copy of its answer, and through them the part that made it — until its next pass + (50 ms to 1 s later). A part unmounted between passes stayed alive with all it made. Each entry is now let go by its + computation's `onCleanup`, when it computes again or is disposed, and when nothing rests on a claim the audit's timer + is cleared and its window listeners are removed. Words-dev is unchanged (7 stale programs told, the twins silent). +- **Fixed (CI):** `compiler/test/leaks.mjs` passed locally and failed on GitHub (the development build, 3 to 6 parts + kept, against 2 allowed): a pass ran during the local collections, which waited 30 ms between them, but not on the + slower runner. Its pages now never fire a timer of 50 ms or more, and the collections run with no wait between them, + so nothing waits for a timer to be let go. With the old runtime it fails on every machine. + +**The Vite suite installs Solid's plugin once; the `pure` track is closed** + +- **Fixed (CI):** `t-vite` runs `node compiler/test/vite.mjs --install` before its three shards. The flag installs + Solid's Vite plugin, TanStack Router's plugin and the packed packages into `compiler/test/.out`, then exits. Before + this, each shard installed the plugin when it loaded, so in a fresh workspace three `npm install`s ran into one prefix + at once and one shard failed. +- **Docs:** the `pure` work (MO-15a–f) is closed. The 41 `import pure` sites in the review apps stay claimed and are + watched in development; the full fix (a signal per configuration) is not built. See the README's *Status after + review* and spec/archive/known-limits-2026-11-29.md. + +**`reads`: a call that writes nothing, asked where it is made once** (09 MO-15f, 04 R-io-5; +spec/archive/known-limits-2026-11-29.md) + +- **New word: `reads`** (`export reads fn f(…)`, `import reads { f } from "m"`): the call writes nothing that was there + before it, and reads what may change (the clock, a stored value, the host's locale, configuration). Accepted where a + call is made once — an equation of the module's top level that never changes, a source's first value, an awaited + call, a handler — and refused in a view, an equation that may compute again, an effect's inputs and a `fn` + (`IO_IN_REACTIVE`/`IO_IN_FN`, R-io-5), saying why it is not `pure`, that nothing will ask it again, and what to write + instead. `reads` stays a name everywhere but before `fn`/`class` in a row and after `import`. +- **New: rx-declare drafts `reads`** where the summaries (`compiler/words/src/own.rs`) prove the call quiet and not + `pure`, with the reason on the line above the row (`//@ reads: …`). Two quiet rules of their own: state that may + change is read only where nothing of it is let go, and stepping or testing what the package holds is a write. +- **Changed:** `import pure` over a drafted `reads` row is not believed where the answer would be kept (it is accepted + where the call is made once); an io call made once is told that `import reads` would do there; `reads` on the import + of a hand-written io row is `IMPORT_ROW_MISMATCH`. Drafts are written again (draft 26). +- **Checked:** development builds lend a `reads` call what it is given as they do any JS fn, and name the word when it + changes it; the call is not made twice nor asked again. rx-verify refutes a `reads` row by what a run shows it writes, + and by SV-7c's two sides; rx-tsc counts `reads` and `import reads` (MO-15b). +- **Not done:** "pure given configuration" (the study's §7.2 third row), which is not sound while a configuring export + is handed out; `marked.use` and `Decimal.set` write, and stay io. + +**The benchmark installs what `words-dev` claims `pure` of** (09 MO-15d) + +- **Fixed (CI):** `bench/package.json` installs date-fns 4.1.0, marked 16.4.2, decimal.js 10.6.0 and chess.js 1.4.0, + the versions `compiler/test/words-dev.mjs` was written against: a fresh workspace's `scripts/ci` failed `words-dev` + until they were linked by hand from the reviews' installs. No other test resolves a package the benchmark lacks. + +**`pure` read a second way: summaries of who owns what is written** (09 MO-15e; compiler/words/DESIGN.md, *Summaries*; +spec/archive/known-limits-2026-11-29.md) + +- **New: `rx-declare` proves `pure` where the reading of the call stops** (`compiler/words/src/own.rs`). Every function + of the package's graph is summarised once — what it calls, what it writes and who owns that, what it reads of a + module's state, what it names of the world — and the proof composed from the export down, the functions the call + answers proven as calls of their own. Three rules prove what was refused: a method's write of an object the call made + (an owned receiver, and fields that hold only what the call made), a module's scratch name set before it is read, and + a module's table filled only as it loads with what is written out there. Over the 283 modules the benchmark drafts: 7 rows newly `pure` (valibot's metadata actions and identity transformations), none lost; the adversarial suites (3,938 cases) and 29 new twins, none proven falsely. Where it refuses, `--why` + says why with the file and the line (`format: … it calls .getTimezoneOffset(), whose answer is the host's [date-fns/_lib/format/formatters.js:724]`). +- **Found:** the study's 24–33 of the review apps' 43 `import pure` sites are 0 under sound rules — the configuring + exports (valibot's `setGlobalConfig`, culori's `useMode`) write what those builders read; such a `pure` goes stale. + The 43 stay claims, each refused with its reason. +- **Changed:** drafts are written again (draft 25); `rx-tsc --rx-words` counts `import pure { x }` as proven where the + draft writes `pure fn x`. + +**Solid hooks are not `pure`: a shared declaration of solid-i18next, and the messages that taught `pure`** (09 MO-15c; +spec/archive/known-limits-2026-11-29.md) + +- **New: `@rx-types/solid-i18next`** (`declarations/solid-i18next`): rx-declare's draft, with `instantiates` on + `useTranslation`, `useLanguage`, `useI18n` held by rx-verify, its record and probe beside it. No context word: the + package's context defaults to the global i18next instance. `import pure { useTranslation }` is now + `IMPORT_ROW_MISMATCH`, saying the import goes without `pure`. +- **Changed (messages):** an undeclared module's call bound where the component is made is told its row needs no word + (`export fn persisted` is io, called once), not `export pure fn`; guide/libraries.md's wrapper rows lose their false + `pure` (`persisted`, `createAtom`). +- **Fixed (rx-verify):** a package that ships only `.jsx` runs compiled also when the probe imports it first, and in + rx-verify's own second processes (`instantiates` was "not run"). +- **Not shipped:** `@solid-primitives/storage`'s `makePersisted` and `@solid-primitives/history`'s `createUndoHistory`, + which `.rx` cannot call directly and which show no `instantiates` (declarations/shared-not-held.json). +- The benchmark installs solid-i18next 0.0.8 and i18next 25.10.10. + +**A `pure` answer that goes stale is told, in development** (09 MO-15d; spec/archive/known-limits-2026-11-29.md) + +- **New: the re-ask audit (`FALSE_WORD [MO-15d]`, development build only).** A `pure` claim (a row's, an `extend` + row's, or `import pure`) whose answer changes later for the same arguments — date-fns' `format` after + `setDefaultOptions`, `marked.parse` after `marked.use`, `new Decimal(1).div(3)` after `Decimal.set`, a chess board + claimed `pure` after `move()` — left the page stale with no sound: MO-15a's check makes the first calls twice at once, + and sees none of them. The development runtime now asks again, untracked, each live equation that rests on a claimed + `pure` call (and a claimed call made in a view), after the page has had a turn following a click, a key or an input, + and once a second; where the answer differs from what it holds it reports `FALSE_WORD [MO-15d]` once on the page's + `error` event, naming the import, its specifier and the word, and saying it went stale. It proves nothing — it is + *told when it goes stale* in place of *silent if false*. Not asked again: a promise's answer (a loader), a row that + also `instantiates`, a drafted row's words, a server row, an equation that reads its own `pre`. A claimed + constructor's instance is watched through what reads it, so a mutable instance only handlers call (TanStack Pacer's + `Debouncer`) is not told. `compiler/test/words-dev.mjs`: 7 stale programs told (none on 7ef57a24), 6 true twins + silent; the r7–r11 apps: one new tell, on the review's deliberately false `import pure { persisted }`, none on a correct + app. Cost: development about 25–50 ns more a computation of an equation, 45 ns–1.2 µs more where it rests on a claim, + about 0.6 µs an equation asked again in a pass; production none (`__rt.word` answers the function, `__rt.memo` is + Solid's `createMemo`). +- **Changed (development messages):** a default import is named as the program names it (`import pure Decimal from + "decimal.js"` says `Decimal`, not `default`), in MO-15a's messages too; a class whose row says `pure`, or that + `import pure` names, is bound through `__rt.word` (both emitters), which in production answers the class itself. + +**After the review: an effect loop is a named error, not a hung tab; what JavaScript is lent is a copy of its own** +(spec/02 C-3c; 09 MO-10i *Lending, step 1*; 08 CN-3b; 11 CP-4b; spec/archive/known-limits-2026-11-29.md) + +- **New: the effect-run breaker, in both builds (`EFFECT_LOOP`).** An effect whose apply changes its own input through + something C-3 cannot see — a handler prop, the view's own handler behind a `click()` or a `togglePopover()`, another + module's action, a setter JavaScript made, a query client, a dispatch in a helper, a callback a microtask delivers — + hung the tab in Solid's production build (and its development build too, where the loop went through a microtask). + The runtime now counts each effect's runs in a turn of the page: at 1,000 the effect is not applied again in that + turn, is owed one run in the next, and is stopped if that loops again. It reports `EFFECT_LOOP [C-3c] src/main.rx:5, + effect (n): …` on the page's `error` event — the module, the line and the inputs, which the compiler now gives the + runtime (`__rt.effect`'s fourth argument, both emitters). The nine probes of the reviews (known limits R2, R3, R7, + R11, R12, a false `handler`): before, 9 of 9 hang production; after, 0 hang in either build and each names its + effect. `createApp({ effectLoopLimit })` sets the count. The checkers are unchanged: the program is still accepted, + and the loop is still a mistake — a reported one. `compiler/test/loops.mjs` (in `scripts/ci`), `runtime/test.mjs`. +- **Changed: a JS fn is handed a copy of what it is lent** (lending, step 1). It was handed Solid's `deep(store)`, + which is the store's own objects where nothing was written since: in production a helper's change in place landed + in the store's data, unseen by the view, and was sent by the next save (known limit R10, now closed, and R5's second + half with it). Where nothing tracks the call (a handler, an action, an effect's apply) the value is now + `snapshot(store)` — no subscribing walk — and in every case the callee gets a copy. A handler's lend costs about + half of what it did (1,000 / 10,000 / 50,000 rows, production Chromium: 0.77 → 0.40, 8.8 → 4.3, 46.8 → 25.1 ms a call); an equation over a JS fn costs about a quarter more + (0.70 → 0.85, 8.0 → 9.8, 43.0 → 55.7 ms a computation: the copy on top of the walk it needs). A development build's error on such a change is as it was. + **Behaviour change:** a row a helper answers as it was given, written to a second path (`st.cur := + same(st.rows[0])`), is a row of its own, in both builds; it was the store's own row — one object under two paths — + only where that row had never been written. `compiler/test/lending.mjs`. +- **Known limits:** R2, R3, R7, R11, R12 and R8's remainder now say the named error in place of "the tab hangs", and + what is still wrong; R10 closed; R5's stale second half corrected; R13 still open, with its production form said. + +**Re-check 11, the final round: two cheap fixes, the rest known limits** (spec/06 ST-1; 09 MO-8t; +spec/archive/known-limits-2026-11-29.md) + +- **Fixed: a factory's class instance in a source made by its call, written by path** (`source h := makeWidget()`, + then `h.n := 7`) threw "a path write to an atomic source", at mount in an effect (K-1). The runtime sets the property + on the object the source holds and counts the source changed; the checkers cannot tell an interface from a record + alias, so they do not refuse it. `compiler/test/confined.mjs`. +- **Fixed: IO_IN_REACTIVE on a class's static method** (`DateTime.fromISO`, `Decimal.max`) printed `export pure fn + X.(…)`, which cannot be written (M-1). It prints `import pure { X } from "m"`, and `extend pure class X` + where the draft rows the class. `compiler/test/pasted.mjs`'s `io/class-static/*`. +- **Recorded as known limits:** K-2, M-2, M-3, M-4, K-3, S-1, and round L's open items L-A1, L-A2, L-B, L-C. README's + *Status after review* lists them. + +**Re-check 10: the classes the fresh apps came from, not the instances** (spec/06 ST-1, AC-1f; 02 W-1a, E-4; 07 §1c, §1d; +09 MO-8l, MO-8t, MO-10g; 99) + +- **Fixed: a property of an element or a class instance held in a source** (`video.volume := v`, `canvas.width := w`, + `bag.n := 7`) was accepted and threw ("a path write to an atomic source"; at mount in an effect). It is + WRITE_TO_NON_SOURCE, printing the JavaScript helper (its module, `.d.ts`, import and call), or the whole write for a + record that begins as `null`; STALE_OWN_READ and EFFECT_WRITES_OWN_SOURCE no longer misread it. +- **Fixed: `peek(source)` given to an `instantiates` class or fn where the component is made** was the store itself, and + the library's later push was dropped in production. It is lent, as every other way is (`compiler/test/lending.mjs`). +- **Fixed: `import d, { X } from "m"` and `f(...xs)`** parse; a spread is lent item by item, and refused where a place + has a rule (`ARGUMENT_COUNT`). +- **Fixed: IO_IN_REACTIVE and IO_IN_FN on a method's row** print the object's `import pure` and the `extend` rows. +- **Fixed: rx-declare left out `useTranslation` and dayjs's default**: a small-letter type is named by its module, an + `export =` value is the `default` row, and a draft says why it rows nothing for an export (format 24). +- **Fixed: a component's callback prop** that the row types to answer a value prints `extend component C(props: { onX: + handler })`. +- **New tests, each a ratchet:** `ref/syntax/run.mjs` (every form of the packages' documented examples read or refused + with the .rx spelling: 94 bare PARSEs → 0), `bench/drafts-complete.mjs` (every export a row or a reason: 93 → 66), + corpus.mjs over 8 codes (7,868 trials, 1,011 → 0 failing), lending.mjs (101 checks). + +**Re-check 9: a printed fix works over the corpus of declarations, not over cases** (spec/10 SV-7a; 09 MO-8v, MO-8y, +MO-10g; 02 W-1a; 99) + +- **Fixed: `x = new C(…)` over a class's row that `instantiates`** is constructed, `new` (both emitters called it as a + function: the io message's first spelling for a class and the guide's `new ReactiveMap(initial)` threw at mount). + RG-6's instantiation lends what it gives a JS import and passes a rest parameter every argument. +- **Fixed: printed `extend` rows that did not parse.** An `extend` row takes a rest parameter as the row writes it + (`(...args: handler)`); a list's items are the parameter's, and the message prints its word (`(source: handler)`, not + `{ 0: handler }`); for a project's own row it prints where the word goes as the row writes it (`after \`onIdle?:\``), + with the row's side, and no `pure` for a fn with a `draft` parameter. +- **Fixed: a closure where a handler is taken is imperative scope** whatever its body — `listen(() => bump())` was + `ACTION_CALLED_IN_OWNED_SCOPE` with the word written — and so are the items of a list the parameter takes (in an effect + too). `ACTION_CALLED_IN_OWNED_SCOPE` in a closure given to a JS fn prints the parameter's word (it printed nothing). +- **Fixed: what a method of a JavaScript class's instance answers** is JavaScript's, not a row of the source that holds + the instance (signature_pad's `let d = pad.toData(); d.pop()` was `MUTATION_IN_PLACE`). +- **Changed: an accessor of a function is drafted as the function it is** (`createUndoHistory(source: Many>)`), + so the README's list form types and a closure there is the accessor; a closure that answers a closure that writes (an + undo history's source) prints the helper that makes it, which no row word can say. +- **Added: compiler/test/corpus.mjs**, a CI step (`corpus`): every row of the benchmark's declarations, the calls that meet + each declaration-related refusal, each printed spelling pasted as printed, compiled, a sample run in Chromium; counts + and failures in compiler/test/corpus.json (a ratchet). On ac97fe44's checkers 647 of 3,510 trials failed; now 0. + pasted.mjs's appliers are shared with it (compiler/test/paste-apply.mjs), and its new cases run in Chromium. + +**Re-check 8's fresh sample: a library's class, a key map, and a fix that works when pasted** (spec/10 SV-7a; 09 MO-8k, +MO-8z, MO-10g; 99) + +- **Added: `new C(…)` of a class an import gives** is a call of its constructor, under its row's words (it was + `UNBOUND`, and the way through a one-line factory in a `.js` module). A class's row is `export class C(…)`, with a fn's + words; `rx-declare` drafts it, and `extend class C …` adds to it. +- **Added: a word on an index signature** — `{ [key: string]: handler (e: KeyboardEvent) => void }` — is every field's + the record does not name; a record after a named type (`T & { … }`) is read for its words. +- **Fixed: a package whose `exports` hides its types** (tinykeys) is typed by the project's declaration, and drafted + from its `types` file. +- **Changed: messages print a fix that works when pasted** — the import as written with `pure`, the row by its name, + kind and file, the words of an existing `extend` row, the factory's module and row; `compiler/test/pasted.mjs` + holds every code that prints one to a case (6 codes had one, 39 do), and lists the rest with why. +- **Fixed: the editor and rx-tsc** said "regular expression" for `xs.map((x) =>
  • )`, where `rxc` printed + `MARKUP_AS_EXPRESSION` and its `{for …}`. + +**The second review's library-seam findings: words over a draft, callbacks by their resolved type, a selective note** +(spec/09 MO-8y, MO-10g, MO-10m; 04 R-8; 07 §5; README) + +- **Added: a project's declaration is read over the draft** (MO-8y). `rx-types/.d.rx` no longer replaces the + package's declaration: an `export` row replaces that export's row, an `extend` row adds words to it and restates + nothing (`extend fn useQuery: { data: pending fails(Error) } uses(queryClient)`, `extend component Select(props: { + onChange: handler })`, `extend pure fn useQueryClient`), and every other export keeps the draft's row. A file that + held two rows gave `NOT_EXPORTED` for every other export, and a row that marked `data` had to restate the result's + shape; the practical path was a copy of the whole draft (37.7 kB for TanStack Query). A file written whole is read as + it was. +- **Changed: a hook's options are read as a component's props are** (MO-10g): a field typed as a function that answers + nothing is a handler with no word, one that answers a value is pure — and an action is judged as a closure is (a + closure given to `useMutation`'s `onSuccess` was refused and the same callback as an action accepted). A parameter + that is itself a function keeps the pure default. +- **Changed: drafts say what a callback answers as TypeScript resolves it** (draft 20): Kobalte's Select and Combobox + `onChange`, Formisch's `
    ` and TanStack Query's mutation callbacks are handlers on generated + declarations alone. +- **Fixed: a function type that answers a union is read whole** — `(v) => string | number` was read as answering nothing, + so a closure that writes was accepted in a prop the library computes with. +- **Changed: the note about a generated draft is selective** — printed for a package whose code reads a context, or makes + Solid's async state, that no row names; once per package, naming the hooks, importers sorted. +- **Fixed: a handler's snapshot of a library field that waits or fails** (`onClick={() => { log(todos.data.length) }}`) + is `UNGUARDED_SNAPSHOT`, as a snapshot of an awaited equation is (04 R-8). +- **Changed: messages** — `break` and `continue` in a loop say what to write (they were `UNBOUND break is not + declared here`); a `switch` as a fn's body, `x!.f`, a pattern as a closure's parameter or a loop's variable, `new + Set()`, `new Intl.NumberFormat(…)` and `encodeURIComponent` each say the form .rx writes. + +**The final review's ecosystem and ergonomics findings: library callbacks, built-ins, a handler's JavaScript, +overloads, the documents** (spec/09 MO-10g, MO-8v; 10 SV-7a; 02 W-1c; 07 §2, §5; 08 CN-1a, CN-2, CN-3b; 99; README) + +- **Changed: a declared JS component's function prop is a handler** unless its type answers a value (SC-4b) or the + declaration says `pure (…) => …`, a new word: Kobalte 2.0.0's controlled Dialog, Checkbox, TextField and Tabs + (`onChange={(v) => { tab := v }}`) are accepted on generated declarations alone, with no rows copied into `rx-types/`. + An action given to such a prop is accepted again; given to a pure one it stays refused. A fn's parameter keeps the + pure default. +- **Added: JavaScript's built-ins, a closed list** (10 SV-7a revised): `Math`, `Number`, `String`, `Boolean`, `JSON`, + `Array.isArray`/`from`/`of`, `Object.keys` and its reading statics, `parseInt`, `parseFloat`, `isNaN`, `isFinite`, + `new Date(…)` given a moment; `Date.now()`, `new Date()`, `Math.random()` and `console` in imperative code only. +- **Added: a handler's own JavaScript** — a `let` holding a primitive written again with `:=` (02 W-1c), `switch` (read + as the `if … else if …` it is, no fall-through but between empty cases), and `e as T` in imperative code; a C-style + `for` is told the loop over its steps. +- **Changed: of overloads that differ only by an accessor**, the draft's row is the accessor's, `ref` (MO-8v): + `createElementSize(box)` needs no hand-written row. +- **Fixed: the documents** — CN-1a's "no warning tier", 99's two statements on rx-tsc and its bins, the README's "no + check becomes a run-time check", CN-2's row for unkeyed `for` — say what the tools do. + +**The final review's soundness findings: effect loops, library data, a loop's turn** (spec/02 C-3, C-3b, W-1a; 09 MO-10m) + +- **Changed: C-3 reads an apply's run**, not only its statements: an action of the module it calls, a closure it calls, + a JS store's setter (`setS(…)`, `thing.set(…)`). `effect (count) { bump() }` with `action bump() { count := count + 1 }` + is `EFFECT_WRITES_OWN_SOURCE`, as the direct form was. +- **Added: C-3b**, effects that feed each other (`effect (a) { b := … }` beside `effect (b) { a := … }`, transitively): + `EFFECT_WRITES_OWN_SOURCE`, the cycle named step by step. It was two pieces of advice that never said "loop". +- **Changed: W-1a reads a loop's turn as the row itself**: `for (const t of todos) { t.tags.push("x") }` is + `MUTATION_IN_PLACE`, with the place to write instead (`todos[i].tags := v => [...v, x]`); a type step reads through an + alias now. +- **Restored: `pending` / `fails(…)` before a field of a declared result's record (MO-10m)** — withdrawn on 2026-11-23 + as one library's, back as Solid 2's: an async store's field holds and throws where it is read. TanStack Query's own + `useQuery`, declared so, gets `UNHANDLED_FAILURE`, the loading check and `CONTEXT_NOT_FOUND`; `bench/tasks/query-forward` + needs no JS module of its own. +- **Added: a note from rx-tsc and rx-declare** naming each generated draft that says no context and nothing that waits + or fails: what is not checked is said in the run. Known limit R1 (a router hook above the router) recorded. + +**Ecosystem pins: Kobalte 2.0.0 from npm; Solid stays at caba92afb** (DECISION.md, 2026-11-29) + +- **Changed: `@kobalte/core` is npm's 2.0.0** in bench/ and examples/rx-packages (was its `solid2` branch at 9c237a06, + built beside the repository). `ref/KOBALTE`, `ref/scripts/kobalte.sh` and `.github/actions/kobalte` are removed. +- **Added back: `bench/tasks/kobalte-select`**, green with no `known` entry: the warning known limit 3 kept as its red was + Kobalte's untracked read (kobalte#786). 45 tasks. +- **Fixed: rx-packages' Kobalte layer** sets `pointer-events` as 2.0.0's layer stack does; the dialog case matches the + original at every step. +- **Kept: Solid at caba92afb**: npm's 2.0.4 is 17 commits older and reopens DV-29 and DV-26's first half. Kept: the + Vite plugin fork (npm 3.0.1 has no `Frontend.buildStart`). + +**test262: the expressions .rx lexes itself** (ref/test262/README.md; the rsvelte #5431 idea) + +- **Added: `ref/test262`**, 854 of test262's expression-level tests (at 4e4505c343d6) as `.rx` equations, run in both + checkers, the crate's dom, ssr and universal modules, and `ref/`'s interpreter and compiler, each value held to Node's + (or, for `==`, to E-6's meaning); what `.rx` removes, and what JavaScript refuses, must be refused. In scripts/ci + (`test262`) and the suites workflow. The 268 failures of this tree are `ref/test262/expected-failures.json`, by case, + with their cause; the list only shrinks. Silent ones among them: `2.e1` is `2 .e1` (undefined), `--x` is `-(-x)`, + `() => { }` is `() => ({})`, `005` and `1__0` are accepted, and `??` mixed with `||` is accepted. + +**Positions: line ends and a byte-order mark** (spec/11 CP-8h, CP-8b; the architecture review of 2026-11-28, item 6) + +- **Fixed: a module saved with a byte-order mark is read** (11 CP-8h). It was a `PARSE` error on line 1 about writes in + `rxc check`, `ref/check.ts` and the build, while the editor showed none. The mark is passed over; offsets still count + it, columns do not (an editor shows none). `rx-tsc` and the language server place errors on line 1 so too. +- **Fixed: lone `\r` line ends are line ends** (11 CP-8h). Every diagnostic of a file saved with classic Mac line ends + was on line 1; lines are now counted as LSP counts them (`\n`, `\r\n`, `\r`) in the crate, `ref/`, `rxc check`, the + language server and `rx-tsc`, and the parser reads a lone `\r` as `\n`. +- **Fixed: a `//` comment ends at any line end** (11 CP-8h): `\r`, U+2028 and U+2029 too, as in JavaScript. A module + with lone `\r` line ends that began with a comment was read as empty and checked clean, and such a `.d.rx` declared + nothing. **Migration:** text after a U+2028 or U+2029 inside a `//` comment is now code, as JavaScript reads it. +- **Fixed: a parse error at the end of a CRLF line is placed past the line's text**, not between its `\r` and `\n`. +- **Added: `spans.rs` holds a statement's line to its span** (11 CP-8b), as it held declarations' and markup's. +- `ref/crate.ts --text` runs every program also with a byte-order mark, with lone `\r` line ends and after a comment + ended by one, and holds each to the program without on each side: the two checkers agreeing is not enough here. +- **Fixed: a name is mapped from where the parser read it** (11 CP-8a, CP-8c). The parser records a span for each declared + name, parameter, written type, write target, import name and path, and record key (`Program::names`); the projection + maps them from those, not by searching the node's text. A write to a source named `guess` (`guess guess := v`) was + mapped onto the word `guess`. `names_misplaced` also holds each name to a leaf of its node, and each such leaf to a + mapping. + +**The review of 25a35680** (spec/09 MO-10b, MO-8x) + +- **Fixed: a result read by its parts is the library's own object where it is handed to JavaScript** (09 MO-10b): an + argument of a JS fn or method, a prop of a JS component, a JS context's value. It was `.rx`'s wrapper, whose `ref` + parts are values, so `describe(picker)` crashed at run time (`p.files is not a function`) with every gate passing. +- **Fixed: a method of such a result keeps its `this`** (`picker.label()` rendered `n=undefined`), in the browser's, + the server's and the scenario runtime. +- **Fixed: a type parameter in scope is not the file's alias of the same name** (09 MO-8x): a row's own ``, a generic + function type's, `infer U`, a mapped key, and an alias body's own ``. +- **Fixed: an alias may hold a method named `fails` or `catches`** (09 MO-8x): `{ fails(): number }` was refused as a + row's word. +- **Fixed: a record written one field to a line is read field by field** (09 MO-8x): a line break ends a member as in + TypeScript; the crate's `rows` read such a record as one field and dropped its callbacks. +- **Added: `REF_PART_CALLED`** (09 MO-10b): a call of a `ref` part (`picker.files()`), or of a name bound to one, is + refused by `rxc check`. **Migration:** a declaration whose result was the library's type read as one value + (`createFilePicker(): FilePicker`) and is now written by its parts (`{ files: ref UploadFile[]; … }`) reads each + `ref` part as its value: write `picker.files`, not `picker.files()`. Only the type layer said so before, in a + production build; a development build crashed. A JavaScript fn that takes the accessor is given the library's object + whole (`describe(picker)` stays as it is). Every `.d.rx` and program in this repository already reads them so. + +**Development builds: keys and hot replacement** (spec/14; solidjs/reactivescript#99 and #100's ideas, re-implemented) + +- **Added: an edit under `vite dev` replaces the program in place and keeps its state** (14 DEV-3). The entry is a hot + boundary: an edit of any module of the program re-runs it without reloading the page, and every source whose + declaration is unchanged keeps its value (a structured one as a copy, a module's too); an atomic question shows its + last answer while it asks again. An edited declaration, a key with several live instances and a question with no + answer start fresh, and the console says which. A program that fails as it runs reloads the page. +- **Added: a development build keys each source** (14 DEV-1, DEV-2): `rxc app --dev [--root dir]`, `rxc compile + --dev`, the Node-API `app(…, devRoot)`. Production output is unchanged. +- **Added: a development client hydrates the production server's output** (14 DEV-4): `RX_DEV=1 npm run ssr` and + `npm run compiled` run every scenario so. + +**The projection's places** (spec/11 CP-8c) + +- **Fixed: a type error on what the projection writes around an expression starts where the expression does.** A + record's key (written quoted), an arrow, a binary or a conditional (written in parentheses), a record, an `await`, a + `ref` argument's accessor (`() => (a)`) each have a range of their own. Of the benchmark's 97 TypeScript errors, 18 + started one to three columns into the token TypeScript names (`ines:` for `lines:`); they now start on it. A content + mapper's flattening (TypeScript 7.1) agreed with rx-tsc's column on 78 of the 97; it does on all 97. Lines are unchanged. +- **Changed: a declared name, a parameter or a written type is mapped from its declaration's own text**, outside every + expression, statement or markup within it; `ref/crate.ts --project` checks each mapping against the syntax tree. No + mapping moved (0 of 50,772): the order the names are found in kept each in its place, but nothing checked it. + +**solidjs/reactivescript#98's findings, re-implemented** (spec/07 §3a and below) + +- **Fixed: a string's escapes are cooked as JavaScript's** (07 §3a). `"a\nb"` was the text `anb` and `"\x41"` was + `x41`, in both parsers. Escapes JavaScript refuses in a module are `PARSE`, and so is a lone surrogate. An attribute's + quoted value is JSX's text, backslashes kept (`pattern="\d+"`). A quoted string that runs past its line is `PARSE`. +- **Fixed: an empty fragment renders nothing in compiled code** (07 §4). The crate wrote `<>` as the text `null`. A + fragment among an element's children is now its children in both emitters: Solid's DOM compiler refuses a fragment + inside an element ("Fragments … are not implemented yet"). +- **Changed: JSX text keeps the white space of its line** (07 §4), as Solid's compiler reads it: ` · note` + keeps its space and `{n} ` its trailing one; indentation and line breaks between elements are still no text. + S-context-2's and S-module-45's frames gain the space their programs write. +- **Added: a member chain may go on on the next line** (07 §3), a line that begins with `.name` or `?.`. +- **Changed: `rxc check` reports every module** (11 CP-8f): each module that does not parse gives its parse error, and + the modules that import none of those are checked. It stopped at the first parse error. +- **Fixed: `n++` in a handler or action body is `ASSIGNMENT`** (99), wherever it fails: a handler with a `let` before + it was `JS_LOCAL` on the `let`, and an action's was a bare `PARSE`. +- **Changed: after an `await`, a handler's read of a source has its declared type** (13 TY-2a): a view branch + (`{if detail != null { … }}`) no longer narrows it there, as the branch may be gone; before the `await` it still does. +- **Added: `STYLE_SCOPE`** (07 CSS-2a): a component's `") else { return c.fail("expected ") }; let css = c.rest()[..end].to_string(); c.i += end + "".len(); - return Ok(ex(start, ExprKind::StyleMap { css, line }, c)); + return Ok(ex(start, ExprKind::StyleMap { css }, c)); } if SERVER_FN_EXPR.is_match(c.rest()) { c.keyword("server"); @@ -1896,7 +5814,15 @@ fn parse_primary(c: &mut Cursor) -> R { continue; } if c.peek() == '\\' { + cook_escape(c, &mut s)?; + continue; + } + if c.peek() == '\r' { + // 07 §3a: a template's line end is a line feed, as JavaScript cooks it (`\r\n` and `\r` alike) c.bump(); + c.eat("\n"); + s.push('\n'); + continue; } if !c.eof() { s.push(c.peek()); @@ -1914,28 +5840,88 @@ fn parse_primary(c: &mut Cursor) -> R { let mut s = String::new(); while !c.eof() && c.peek() != ch { if c.peek() == '\\' { - c.bump(); + cook_escape(c, &mut s)?; + continue; } - if !c.eof() { - s.push(c.peek()); + if c.peek() == '\n' || c.peek() == '\r' { + return c.fail("a quoted string ends on its line: a line break in it is `\\n`, or the string is a template (07 §3a)"); } + s.push(c.peek()); c.bump(); } c.expect(&ch.to_string())?; return Ok(ex(start, ExprKind::Lit(Lit::Str(s)), c)); } - if let Some(m) = NUMBER.find(c.rest()) { - let text = m.as_str().to_string(); - c.i += text.len(); - return Ok(ex(start, ExprKind::Lit(Lit::Num(text.replace('_', "").parse::().unwrap_or(f64::NAN))), c)); + if ch.is_ascii_digit() || (ch == '.' && c.peek_at(1).is_ascii_digit()) { + return match crate::lex::read_number(c.rest()) { + Ok((len, lit)) => { + c.i += len; + Ok(ex(start, ExprKind::Lit(lit), c)) + } + Err((off, msg)) => { + c.i += off; + c.fail(&msg) + } + }; + } + if ch == '/' { + return match crate::lex::read_regex(c.rest()) { + Ok((len, lit)) => { + c.i += len; + Ok(ex(start, ExprKind::Lit(lit), c)) + } + Err((off, msg)) => { + c.i += off; + c.fail(&msg) + } + }; } if c.eat("(") { c.ws(true); - let e = parse_expr(c)?; + let e = parse_seq(c)?; c.ws(true); c.expect(")")?; + c.parened.insert((e.span.start, e.span.end)); return Ok(e); } + // 10 SV-7a (2026-11-29): `new Date(…)`, a built-in that says it is made so + if c.keyword("new") { + c.ws(true); + let ns = c.i; + let Some(name) = c.ident() else { return c.fail("`new Name(…)`: a built-in that is made, `new Date(…)` (10 SV-7a)") }; + let f = ex(ns, ExprKind::Id(name.clone()), c); + c.ws(false); + if c.starts_with("<") { + // (2026-11-30, the third review's R3-8: the line this gave for a Set, `source seen: Set<…> := new Set()`, did + // not compile — `new` makes a Date alone, 10 SV-7a) + return c.fail(&if name == "Date" { + format!("`new {name}<…>`: a type argument is not written at `new` — the value's type is said where it is declared, `source at: {name} := new {name}(…)` (07 §2, 10 SV-7a)") + } else { + // (R9-4, 2026-12-04: since SV-7a's class rows, `new` makes a class a JavaScript import gives — what this + // said of a `.js` module's factory was stale) + format!("`new {name}<…>`: a type argument is not written at `new` — the value's type is said where it is held, `x: {name}<…> = new {name}(…)` (an equation) or `source x: {name}<…> := …` (07 §2, 10 SV-7a)") + }); + } + if c.starts_with(".") { + return c.fail(&format!("`new {name}.…`: `new` makes a built-in .rx binds by its own name (`new Date(…)`, 10 SV-7a); a member of a namespace (`Intl.NumberFormat`) is made in a JavaScript module the program imports, or the value's own method does it (`n.toLocaleString(…)`)")); + } + if !c.starts_with("(") { + return c.fail(&format!("`new {name}` is written with its arguments, `new {name}(…)` (10 SV-7a)")); + } + c.bump(); + c.ws(true); + let mut args = vec![]; + while !c.starts_with(")") { + args.push(parse_arg(c)?); + c.ws(true); + if !c.eat(",") { + break; + } + c.ws(true); + } + c.expect(")")?; + return Ok(ex(start, ExprKind::Call { f: Box::new(f), args, targs: None, make: true }, c)); + } if c.eat("[") { c.ws(true); let mut items = vec![]; @@ -1975,7 +5961,7 @@ fn parse_primary(c: &mut Cursor) -> R { Some(k) => k, None => { if c.peek() == '"' || c.peek() == '\'' { - match parse_primary(c)?.k { + match leaf(c)?.k { ExprKind::Lit(Lit::Str(s)) => s, _ => unreachable!(), } @@ -2013,8 +5999,18 @@ fn parse_primary(c: &mut Cursor) -> R { if c.keyword("null") { return Ok(ex(start, ExprKind::Lit(Lit::Null), c)); } - if c.recover && (c.i == 0 || c.src.as_bytes()[c.i - 1] == b'\n') && looks_like_decl(c) { - c.note("expression"); + if (c.i == 0 || c.src.as_bytes()[c.i - 1] == b'\n') && looks_like_decl(c) { + // 07 §3: a line break ends a declaration, so the expression it needs is not there — the next line is a declaration + // of its own (`export error E(id) =>` at the end of its line). Said where it is missing, by every parse (ref/mutants + // F3: the strict parse read `export` as a name, the editor's refused the next line) + let at = c.i; + c.i = c.src[..at].trim_end_matches(js_ws).len(); + let msg = "expression (a line break ends a declaration, 07 §3: the next line is a declaration of its own)"; + if !c.recover { + return c.fail(msg); + } + c.note(msg); + c.i = at; return Ok(ex(start, ExprKind::Id(String::new()), c)); } if let Some(id) = c.ident() { @@ -2047,19 +6043,18 @@ fn parse_markup(c: &mut Cursor, close: Close) -> R> { Close::Brace => Some("}".to_string()), Close::Tag(t) => Some(t.clone()), }; - let mut broke = false; + let mut text0 = 0; loop { - let start = c.i; if in_element { - let mut s = String::new(); - while !c.eof() && " \t\r\n".contains(c.peek()) { - s.push(c.peek()); + // 07 §4: the text up to the next node, as Solid's JSX reads it (`jsx_text`) + let s0 = c.i; + text0 = s0; + while !c.eof() && !"<{}".contains(c.peek()) { c.bump(); } - broke = s.contains('\n'); - let tag = close_text.as_deref().unwrap(); - if !s.is_empty() && !broke && !c.starts_with(&format!("", tag)) && !out.is_empty() { - out.push(Markup { kind: MarkupKind::Text(" ".into()), line: None, span: Span::NONE }); + let t = jsx_text(&c.src[s0..c.i]); + if !t.is_empty() { + out.push(Markup::new(MarkupKind::Text(t), Span::new(s0, c.i))); } } else { c.ws(true); @@ -2080,35 +6075,36 @@ fn parse_markup(c: &mut Cursor, close: Close) -> R> { c.bump(); return Ok(out); } - let line = c.line(); let m0 = c.i; if c.starts_with("<") { let mut m = parse_element(c)?; - m.line = Some(line); m.span = Span::new(m0, c.i); out.push(m); continue; } if c.starts_with("{") { - c.bump(); - c.ws(true); - if let Some(mut ctl) = parse_control(c)? { + let child = (|| -> R { + c.bump(); + c.ws(true); + if let Some(mut ctl) = parse_control(c)? { + c.ws(true); + c.expect("}")?; + ctl.span = Span::new(m0, c.i); + return Ok(ctl); + } + let e = parse_expr(c)?; c.ws(true); c.expect("}")?; - ctl.line = Some(line); - ctl.span = Span::new(m0, c.i); - out.push(ctl); - continue; + Ok(Markup::new(MarkupKind::Read(e), Span::new(m0, c.i))) + })(); + match child { + Ok(m) => out.push(m), + Err(err) => return if in_element { braceless_control(c, text0, m0, err) } else { Err(err) }, } - let e = parse_expr(c)?; - c.ws(true); - c.expect("}")?; - out.push(Markup { kind: MarkupKind::Read(e), line: Some(line), span: Span::new(m0, c.i) }); continue; } if !in_element { if let Some(mut ctl) = parse_control(c)? { - ctl.line = Some(line); ctl.span = Span::new(m0, c.i); out.push(ctl); continue; @@ -2118,7 +6114,6 @@ fn parse_markup(c: &mut Cursor, close: Close) -> R> { return c.fail("declaration after markup: a block is declarations, then its view"); } let mut s = String::new(); - let s0 = c.i; while !c.eof() && !"<{}\n".contains(c.peek()) { s.push(c.peek()); c.bump(); @@ -2128,13 +6123,12 @@ fn parse_markup(c: &mut Cursor, close: Close) -> R> { } if !in_element { if js_trim(&s).is_empty() { + if c.peek() == '}' { + return c.fail("expected a declaration or markup"); + } if c.peek() == '\n' { c.bump(); } - if c.i == start { - // the reference loops here forever (a stray `}`); this ends it - return c.fail("expected a declaration or markup"); - } continue; } if s.contains(":=") { @@ -2142,24 +6136,63 @@ fn parse_markup(c: &mut Cursor, close: Close) -> R> { } return c.fail("expected a declaration or markup"); } - if broke && matches!(out.last(), Some(Markup { kind: MarkupKind::Text(_), .. })) { - out.push(Markup { kind: MarkupKind::Text(" ".into()), line: None, span: Span::NONE }); - } - if !s.is_empty() { - let span = Span::new(s0, s0 + s.len()); - out.push(Markup { kind: MarkupKind::Text(s), line: None, span }); - } - if c.i == start { - // the reference loops here forever (a stray `}` in an element); this ends it - return c.fail("expected a declaration or markup"); + // in an element, what is left here is a stray `}`: the text before it was read above + return c.fail("expected a declaration or markup"); + } +} +/// 07 §4: a run of JSX text as Solid's compiler reads it (its `trim_jsx_text`, Babel's `trimWhitespace`): `\r` dropped; +/// where the run holds a line break, each line after the first loses its leading white space, the lines that are only +/// white space go, and the rest are joined by a space; then every run of white space is one space. So ` · note` +/// keeps its space, and the indentation between elements is nothing. +pub fn jsx_text(raw: &str) -> String { + let text = raw.replace('\r', ""); + let text = if text.contains('\n') { + text.split('\n').enumerate().map(|(i, l)| if i > 0 { l.trim_start_matches(js_ws) } else { l }).filter(|l| !l.chars().all(js_ws)).collect::>().join(" ") + } else { + text + }; + let (mut out, mut ws) = (String::with_capacity(text.len()), false); + for ch in text.chars() { + if js_ws(ch) { + if !ws { + out.push(' '); + } + ws = true; + } else { + out.push(ch); + ws = false; } } + out } /// Control forms of a view: `if c { … } else if d { … } else { … }`, `for x in e { … }`, `loading … { … }`, `errored …`, `portal …`. +/// 07 §4: a control form written inside an element without the braces it needs there (`
    errored fallback(e) { … } +/// { … }
    `): its words are read as the element's text, and the block after them as an expression child, which +/// fails inside the block (`expected '}' near 'class="error">…'`). Where the child does not parse and the text before +/// it ends with a control form's word that, read from there, is a whole control form, the failure says so, at the word; +/// anything else keeps the expression's failure. Only a failure is changed: no program parses otherwise than before. +fn braceless_control(c: &mut Cursor, text0: usize, brace: usize, err: ParseError) -> R { + let raw = &c.src[text0.min(brace)..brace]; + let line = raw.rfind('\n').map_or(raw, |n| &raw[n + 1..]); + let lead = line.len() - line.trim_start().len(); + let kw: String = line[lead..].chars().take_while(|ch| ch.is_ascii_alphabetic()).collect(); + if !matches!(kw.as_str(), "if" | "for" | "loading" | "errored") { + return Err(err); + } + let (at, was) = (brace - line.len() + lead, c.i); + c.i = at; + if !matches!(parse_control(c), Ok(Some(_))) { + c.i = was; // a recovering parse goes on from where the failure left it + return Err(err); + } + c.i = at; + c.fail(&format!("`{kw} …` inside an element is a child, written in braces: `{{{kw} … {{ … }}}}` — without them its words are the element's text and the block after them an expression (07 §4)")) +} + fn parse_control(c: &mut Cursor) -> R> { let save = c.i; - let mk = |kind| Some(Markup { kind, line: None, span: Span::NONE }); + let mk = |kind| Some(Markup::new(kind, Span::NONE)); if c.keyword("if") { c.ws(true); let cond = parse_expr(c)?; @@ -2238,7 +6271,7 @@ fn parse_control(c: &mut Cursor) -> R> { let mut classes = None; if c.eat("(") { c.ws(true); - err_name = Some(c.ident_or("error name")?); + err_name = Some(c.bound("error name")?); c.ws(false); if c.eat(":") { classes = parse_classes(c)?; @@ -2254,10 +6287,73 @@ fn parse_control(c: &mut Cursor) -> R> { let (decls, body) = parse_block_body(c)?; return Ok(mk(MarkupKind::Errored { fallback, decls, body, err_name, classes })); } + { + // MO-11k: `view (a, b) { … }`, only with names in the parentheses and a block after them + let save = c.i; + if c.keyword("view") { + c.ws(true); + // a named render prop + let mut prop = None; + if !c.starts_with("(") { + if let Some(n) = c.ident() { + if !KEYWORDS.contains(n.as_str()) { + prop = Some(n); + c.ws(true); + } + } + } + let mut params = vec![]; + let mut ok = c.eat("("); + while ok { + c.ws(true); + if c.eat(")") { + break; + } + match c.ident() { + Some(n) if !KEYWORDS.contains(n.as_str()) => params.push(c.binds(n)), + _ => { + ok = false; + break; + } + } + c.ws(true); + // (2026-12-01, the sixth review's N6-10: `view (r: Row)` was a bare "expected '}'") + if c.starts_with(":") { + let n = params.last().cloned().unwrap_or_default(); + return c.fail(&format!("view ({n}: …): a render prop's parameters are names alone — what each holds is what the component's prop declares (`children: ({n}: Row) => View`), and TypeScript reads it there: write `view ({n}) {{ … }}` (09 MO-11k)")); + } + if !c.eat(",") && !c.starts_with(")") { + ok = false; + } + } + if ok { + c.ws(true); + if c.eat("{") { + let (decls, body) = parse_block_body(c)?; + return Ok(mk(MarkupKind::Mview { prop, params, decls, body })); + } + } + } + c.i = save; + } if c.keyword("for") { c.ws(true); - let name = c.ident_or("for name")?; + // RG-2b (2026-11-29): `for (x, i) in xs` names the row's index as well, an equation (Solid's `` index accessor) + let paren = c.eat("("); + if paren { + c.ws(true); + } + let name = c.bound("for name")?; c.ws(true); + let mut index = None; + if paren { + c.expect(",")?; + c.ws(true); + index = Some(c.bound("for index")?); + c.ws(true); + c.expect(")")?; + c.ws(true); + } if !c.keyword("in") { return c.fail("in"); } @@ -2266,10 +6362,13 @@ fn parse_control(c: &mut Cursor) -> R> { c.ws(true); c.expect("{")?; let (decls, body) = parse_block_body(c)?; - return Ok(mk(MarkupKind::Mfor { name, xs, decls, body })); + return Ok(mk(MarkupKind::Mfor { name, index, xs, decls, body })); } Ok(None) } +/// MO-1: an import is the module's — in a block it was read as a declaration no loader resolves, bound as a JS import with +/// no declaration, and each use of its names was refused instead (ref/mutants F6). The same words in `ref/src/parse.ts`. +const IMPORT_IN_BLOCK: &str = "an import is the module's: it is written at the top level, with the module's other imports, and not in a block (09 MO-1) — move it above"; /// A reactive block body: declarations, then markup, up to the closing `}` (03). fn parse_block_body(c: &mut Cursor) -> R<(Vec, Vec)> { let mut decls = vec![]; @@ -2278,9 +6377,14 @@ fn parse_block_body(c: &mut Cursor) -> R<(Vec, Vec)> { if !looks_like_decl(c) { break; } + if c.starts_with("import ") { + return c.fail(IMPORT_IN_BLOCK); + } + let at = c.i; decls.extend(parse_decls1(c)?); c.ws(true); c.eat(";"); + c.progress(at, "declaration")?; } Ok((decls, parse_markup(c, Close::Brace)?)) } @@ -2319,9 +6423,24 @@ fn looks_like_decl(c: &mut Cursor) -> bool { c.i = save; r } +/// A component declared with a small letter (the same words in `ref/src/parse.ts`). +fn lower_component(name: &str) -> String { + let mut cap = name.chars(); + let cap: String = cap.next().map(|f| f.to_uppercase().chain(cap).collect()).unwrap_or_default(); + format!("component name: a component's name begins with a capital, `component {cap}(…)` — a tag that begins with a small letter is an element (RG-4a), so `<{name}>` would not apply it") +} +/// An attribute's name that ends at its `:`, and what to write instead (the same words in `ref/src/parse.ts`). +fn attr_namespace(name: &str, then_eq: bool) -> String { + let bare = name.trim_end_matches(':'); + if then_eq && name.ends_with(':') { + format!("attr: an attribute is given its value with `=`, not `:=` — `{bare}=…` (`{name}` names no attribute: a namespaced one is `on:click`, `prop:value`)") + } else { + format!("attr: `{name}` names no attribute — a namespaced one has a name after its `:`, `on:click`, `prop:value`") + } +} fn parse_element(c: &mut Cursor) -> R { c.expect("<")?; - let mk = |kind| Markup { kind, line: None, span: Span::NONE }; + let mk = |kind| Markup::new(kind, Span::NONE); if c.eat(">") { let children = parse_markup(c, Close::Tag(String::new()))?; return Ok(mk(MarkupKind::El { tag: String::new(), attrs: vec![], children })); @@ -2362,34 +6481,94 @@ fn parse_element(c: &mut Cursor) -> R { let span = Span::new(d0, c.i); c.ws(true); let e = parse_expr(c)?; - attrs.push(Attr { name: "...".into(), e, span }); + attrs.push(Attr::new("...".into(), e, span)); c.ws(true); c.expect("}")?; continue; } let Some(name) = c.tag_name() else { return c.fail("attr") }; + if name.ends_with(':') || name.contains("::") { + // JSX's namespaced name has a part after its `:` (ref/mutants F1: `class:="x"` was read as an attribute `class:`) + c.i = a0; + return c.fail(&attr_namespace(&name, c.src[a0 + name.len()..].starts_with('='))); + } let span = Span::new(a0, c.i); c.ws(false); if !c.eat("=") { - attrs.push(Attr { name, e: Expr::new(ExprKind::Lit(Lit::Bool(true)), span), span }); + attrs.push(Attr::new(name, Expr::new(ExprKind::Lit(Lit::Bool(true)), span), span)); continue; } c.ws(true); if c.eat("{") { c.ws(true); let e = parse_expr(c)?; - attrs.push(Attr { name, e, span }); + attrs.push(Attr::new(name, e, span)); c.ws(true); c.expect("}")?; + } else if let q @ ('"' | '\'') = c.peek() { + // 07 §3a: an attribute's quoted value is JSX's, its text as written — no escape is cooked (`pattern="\d+"`) + let s0 = c.i; + c.bump(); + let Some(end) = c.rest().find(q) else { return c.fail(&format!("expected '{q}'")) }; + let v = c.rest()[..end].to_string(); + c.i += end + 1; + attrs.push(Attr::new(name, ex(s0, ExprKind::Lit(Lit::Str(v)), c), span)); } else { let e = parse_primary(c)?; - attrs.push(Attr { name, e, span }); + attrs.push(Attr::new(name, e, span)); } } let children = parse_markup(c, Close::Tag(tag.clone()))?; Ok(mk(MarkupKind::El { tag, attrs, children })) } +#[cfg(test)] +mod text { + use super::*; + + /// A parse error beside a character of several bytes: an offset is a character's (`hint` read the last byte of the + /// text before; a declaration's words were looked for one byte on). + #[test] + fn a_failure_beside_a_wide_character_is_a_parse_error() { + for ch in ["é", "漢", "😀", "e\u{301}", "\u{feff}", "\u{2028}", "\u{85}"] { + for src in [format!("x = \"{ch}"), format!("x = \"{ch}\n"), format!("{ch}"), format!("

    {ch}"), format!("x = 1 + /* {ch}"), format!("x = `{ch}"), format!("{ch}=")] { + let refused = parse_program(&src).is_err(); + let (_, errors) = parse_program_recovering(&src); + assert!((refused && !errors.is_empty()) || ch.chars().all(js_ws), "{src:?}"); // (white space is a program) + } + for word in ["uses(c)", "instantiates", "provides(c)", "rejects(E)", "renders(H)"] { + let _ = parse_declarations(&format!("export context c from \"./c.js\"\nexport fn f(): number {ch}{word}\n")); + } + } + } + /// Newcomer test 2, entry 5: a control form inside an element without its braces (`expected '}' near + /// 'class="error">App er'`) says so, at its word; braced it parses; prose that only starts like one keeps its own + /// failure. ref/units.ts has the same unit. + #[test] + fn a_control_form_inside_an_element_without_braces_says_so() { + let said = |kids: &str| match parse_program(&format!("export default component App() {{\n

    \n {kids}\n
    \n}}\n")) { + Ok(_) => "ok".to_string(), + Err(e) => e.0, + }; + let errored = said("errored fallback(e) {

    App error: {e.message}

    } {\n

    ok

    \n }"); + assert!(errored.contains("line 3: `errored …` inside an element is a child, written in braces: `{errored … { … }}`") && errored.contains("07 §4"), "{errored}"); + assert!(said("loading fallback {

    …

    } {

    ok

    }").contains("`loading …` inside an element")); + assert!(said("for x in [1, 2] { {x} }").contains("`for …` inside an element")); + assert_eq!(said("{errored fallback(e) {

    {e.message}

    } {

    ok

    }}"), "ok"); + assert_eq!(said("if you can {\"read\"} this"), "ok"); + assert!(!said("loading { a b }").contains("inside an element")); + } + /// An editor's parse of a block that is not closed ends: a missing expression is an empty one, and no statement. + #[test] + fn an_open_block_ends() { + for src in ["action a() {", "effect () {", "action a() { if (x) {", "export default component App() {

    {", "x = draft(1) {", "action a() { try {", "action a() { for (const x of xs) {", "server fn f() {"] { + for tail in ["", "\n", "é", " let", " let x =", " n :=", " x.", " ;"] { + let (_, errors) = parse_program_recovering(&format!("{src}{tail}")); + assert!(!errors.is_empty(), "{src}{tail}"); + } + } + } +} #[cfg(test)] mod recovering { use super::*; @@ -2398,6 +6577,46 @@ mod recovering { p.decls.iter().filter_map(|d| d.name().map(|n| n.to_string())).collect() } + #[test] + fn an_arrow_whose_braces_are_a_record_notes_nothing() { + // C8 (2026-11-27): the block attempt's notes were kept when the body was read as a record, so rx-tsc said PARSE + let src = "export default component App() {\n source items := { name: \"a\" }\n \n}\n"; + let (_, errs) = parse_program_recovering(src); + assert!(errs.is_empty(), "{errs:?}"); + assert!(parse_program(src).is_ok()); + } + + /// A declaration file's rows are kept by its whole text: a text that differs anywhere is parsed, and what is kept is + /// what the parser answers. + #[test] + fn declarations_are_kept_by_their_whole_text() { + let kept = |s: &str| format!("{:?}", parse_declarations(s).unwrap()); + let parsed = |s: &str| format!("{:?}", parse_declaration_rows(s).unwrap().0); + let a = "export pure fn load(id: string): Promise\nexport error Gone\n"; + let b = a.replace("id: string", "id: number"); // as long, the same first words and the same last row + assert_eq!(a.len(), b.len()); + for s in [a, &b, a, &b] { + assert_eq!(kept(s), parsed(s), "{s}"); + } + assert_ne!(kept(a), kept(&b)); + } + + /// The fourth review's N4-2: `=` in a `switch`'s case was read, by the editor's parse, as an empty statement before it, + /// for ever (`rxc check` never answered; the WebAssembly build ran out of memory). Every loop that reads parts one + /// after another reads something on each turn or stops (`Cursor::progress`): each form answers ASSIGNMENT, as + /// `ref/` does, in both parses. + #[test] + fn a_turn_that_reads_nothing_is_a_parse_error() { + for body in ["switch (n) { case 2: n = 3 }", "switch (n) { case 2: { n = 3; break } }", "switch (n) { case 2: n = 3; break }", "switch (n) { default: n += 1 }", "if (n == 2) { n = 3 }", "n = 3", "let r = 1; r = 2"] { + let src = format!("export default component App() {{\n source n := 0\n \n}}\n"); + let strict = parse_program(&src).expect_err(&src); + assert_eq!(strict.3, "ASSIGNMENT", "{body}: {}", strict.0); + let (_, errs) = parse_program_recovering(&src); + assert!(errs.iter().any(|e| e.3 == "ASSIGNMENT"), "{body}: {errs:?}"); + } + assert_eq!(parse_stmts("switch (n) { case 2: n = 3 }").expect_err("a statement").3, "ASSIGNMENT"); + } + #[test] fn half_typed_member_and_expression_still_parse() { let src = "source user := { name: \"a\" }\nshown = user.\nnext = \nexport default component App() {\n

    {shown}

    \n}\n"; @@ -2418,10 +6637,361 @@ mod recovering { assert!(parse_program(src).is_err()); } + /// MO-8d: `component Picker
  • { props.onPick(n) }}>{n}
  • \n}\nfn twice(x: number): number => x * 2\nexport default component App() {\n { log(id) }} onDrop={id => { log(id) }} />\n}\n"; + let src = "type Pick = (id: number) => void\ncomponent Row(props: { id: number; onPick: (id: number) => void; onDrop: Pick }) {\n source n: number := peek(props.id())\n
  • { props.onPick(n) }}>{n}
  • \n}\nfn twice(x: number): number => x * 2\nexport default component App() {\n { log(id) }} onDrop={id => { log(id) }} />\n}\n"; let p = parse_program(src).expect("parses"); assert_eq!(names(&p), ["Pick", "Row", "twice", "App"]); } + #[test] + fn type_arguments_are_parsed_completely() { + // 07 §3: what TypeScript reads as type arguments is a call; anything else stays comparisons + for t in [ + "Todos", "string[]", "{ a: string; b?: number }[]", "A | B", "A & { x: 1 }", "Record", "Map", "[a: string, b?: number, ...rest: T[]]", + "(x: T) => U", "(x: T) => T", "new () => Foo", "K extends keyof T ? T[K] : never", "T[K]", "typeof foo.bar", "import(\"./x\").Y", "-1 | 0 | 1", + "\"a\" | 'b'", "`p-${string}`", "{ [K in keyof T]-?: T[K] }", "{ readonly [k: string]: number }", "{ (x: number): string; new (): Foo; m(a: T): void }", + "keyof T", "readonly string[]", "unique symbol", "T extends (infer U)[] ? U : never", "(x: unknown) => x is string", "A,", "Array>", "this", "{ +readonly [K in T]+?: 1 }", "{\n done: number\n items: string[]\n}", "`x${T}-${number}`", "`a${`b${string}`}`", "`k${{ a: 1 }[\"a\"]}`", + // R4: a `}` in a string inside a substitution does not end it + "`x${\"}\"}`", "`x${'}'}`", "`x${`}`}`", "`x${\"{\"}`", "{ k: `x${\"}\"}` }", "\"}\"", + ] { + assert!(looks_like_types(t), "{t} is a type list"); + } + for t in ["b[c+1]", "b && c", "b ? c : d", "b + c", "b - c", "b * c", "b(c)", "b = c", "b, c + 1", "!b", "b.c(d)", "b[c]()", "b[0] + 1", "{ a }", "b c", "", "typeof f(x)", "(b, c)", "b == c", "{ a: 1 b: 2 }", "`x${c+1}`", "`x${c(1)}`", "-\"1\"", "-'1'", "-`1`", "import(1)", "`x${\"}\" + 1}`", "`x${\"}\"`"] { + assert!(!looks_like_types(t), "{t} is not"); + } + } + #[test] + fn a_brace_in_a_string_type_argument_keeps_the_call() { + // R4 (RFC 11): `}` inside a string, in a template literal type or as a type argument, is not a closer + for (src, targs) in [("x = f<`k${\"}\"}` | T>(1)\n", "`k${\"}\"}` | T"), ("x = f<\"}\", T>(1)\n", "\"}\", T"), ("x = f<{ a: `${'}'}`; b: T }>(1)\n", "{ a: `${'}'}`; b: T }")] { + let p = parse_program(src).expect("parses"); + let json = crate::json::program(&p); + assert!(json.contains(&format!("\"targs\":{}", serde_json::to_string(targs).unwrap())), "{src}: {json}"); + } + } + /// 07 §2: a type's text is read by tokens: a bracket or a quote in a string, a template or a comment is no bracket. + #[test] + fn a_type_is_read_by_tokens() { + let said = |src: &str| { + let one = |d: JsDecl| match d { + JsDecl::Error { name, fields, .. } if !fields.is_empty() => format!("{name}({})", fields.join(",")), + JsDecl::Fn { name, params, ptypes, cbs, .. } if cbs.iter().any(|c| c.is_some()) => format!("{name}[{}]", callbacks_of(¶ms, &ptypes, &cbs).into_iter().map(|c| c.name).collect::>().join(",")), + JsDecl::Comp { name, props, .. } => format!("{name}{{{}}}", props.into_iter().map(|p| p.name).collect::>().join(",")), + d => d.name().to_string(), + }; + parse_declarations(src).expect(src).into_iter().map(one).collect::>().join(" ") + }; + for (src, want) in [ + ("export type T = { // {\n a: string\n}\nexport pure fn g(): number\n", "T g"), + ("export type T = { // don't (\r\n a: string }\r\nexport pure fn g(): number // it's\r\n", "T g"), + ("export pure fn g(a: string /* ) */): number\n", "g"), + ("export interface X { a: \"}\" }\nexport pure fn g(): number\n", "X g"), + ("export pure fn g\">(x: T): T\n", "g"), + ("export error E(f: () => void, b: string)\nexport pure fn g(): number\n", "E(f,b) g"), + ("export type T = `a${`}`}b`\nexport pure fn g(): T\n", "T g"), + ("export fn f(cb: handler (a: \")\") => void): void\n", "f[cb]"), + ("export component C(props: { a: string /* , b: ( */; c: number /* don't */ })\n", "C{a,c}"), + ("export pure fn g(): { a: string /* pending x, fails(E) y */ }\n", "g"), + ("export type T = { é: \"é)\" /* ünï ( */ }\nexport pure fn g(a: \"日本)\" | `é${\"}\"}`): number\n", "T g"), + ("export type T = `a${b\nexport type U = \"a\nexport type V = 'a\nexport pure fn g(): number\n", "T U V g"), + ("export pure fn g(): number\nexport error E(", "g E"), + ("export pure fn g(): number\nexport error E(é", "g E(é)"), + ("export pure fn g(): number\nexport error E(a: \"é", "g E(a)"), + ("export pure fn g(): number\nexport type T = \"a\\", "g T"), + ("export pure fn g(): number\nexport type T = `é${", "g T"), + ("export pure fn g(): number\nexport type T = a /* é", "g T"), + ("export pure fn g(): number\nexport interface X { é", "g X"), + ] { + assert_eq!(said(src), want, "{src}"); + } + for src in [ + "type T = { // }\n a: string }", + "source x: string /* := */ := \"a\"", + "interface X { a: \"}\" }", + "interface X {\n a: string // }\n}", + "fn f(x: string /* ) */, y: number): number => y", + "component A(props: { a: string /* } */ }) {

    {props.a}

    }", + "fn f(x: number): (a: number) => boolean => (a) => a > x", + "fn f(x: number): { a: boolean } => ({ a: x < 2 })", + "fn f(x: number): boolean => (x < 1)", + "x = [1].map((y: Array) => y >= 2)", + ] { + assert!(parse_program(&format!("{src}\nexport default component App() {{\n

    x

    \n}}\n")).is_ok(), "{src}"); + } + for (src, targs) in [("x = f */>(1)\n", "T /* > */"), ("x = f(1)\n", "T /* don't */"), ("x = f\n>(1)\n", "T // >")] { + let json = crate::json::program(&parse_program(src).expect(src)); + assert!(json.contains(&format!("\"targs\":{}", serde_json::to_string(targs).unwrap())), "{src}: {json}"); + } + // every name is a value's: compared, whatever a comment says + assert!(!crate::json::program(&parse_program("source a := 1\nsource b := 2\nsource c := 3\nx = a(c)\ny = a < b && /* it's */ c > (a)\n").expect("parses")).contains("targs")); + } + /// Text that nothing closes is read once, and no deeper than the stack: 20,000 lines of each (a second each, were it + /// quadratic, in an optimized build; the limit is for a slow machine). + #[test] + fn what_nothing_closes_is_read_once() { + for line in ["`a${b", "`a", "`a${'b", "\"a", "{ a: string", "a /* x", "(a", " bool { + let Some(after) = rest.strip_prefix("reads") else { return false }; + let t = after.trim_start(); + if t.len() == after.len() { return false; } + let word = |s: &str, w: &str| s.strip_prefix(w).is_some_and(|r| !r.starts_with(|c: char| c.is_alphanumeric() || c == '_' || c == '$')); + if row { return word(t, "fn") || word(t, "class"); } + if t.starts_with('{') { return true; } + let n = t.find(|c: char| !(c.is_alphanumeric() || c == '_' || c == '$')).unwrap_or(t.len()); + if n == 0 { return false; } + let r = t[n..].trim_start(); + r.starts_with(',') || word(r, "from") +} +/// MO-15f: the reason rx-declare wrote on the line above a `reads` row (`//@ reads: …`). +fn reads_why_above(src: &str, row0: usize) -> Option { + let start = src[..row0.min(src.len())].rfind('\n')?; + let prev_start = src[..start].rfind('\n').map_or(0, |i| i + 1); + src[prev_start..start].trim().strip_prefix("//@ reads: ").map(|s| s.trim_end().to_string()) +} + +/// 07 ruling 14: one `catch` per `try` — two kinds of failure handled apart nest two (round H, re-check 18's c08: a second +/// `catch` failed inside its own body, `expected '}'`, with no fix). The edits paste round after round: a third `catch` +/// nests once more. ref/src/parse.ts `secondCatch`. +pub fn second_catch(try_line: usize, line: usize) -> String { + format!("a `try` takes one `catch` (07 ruling 14: a typed `catch (e: A)` rethrows every other failure) — to handle two kinds apart, nest two `try`s: write `try {{ try` in place of `try` (line {try_line}) and `}} catch` in place of `catch` (line {line}); the inner `catch` takes its kind, the outer one the rest") } diff --git a/compiler/src/prelude.ts b/compiler/src/prelude.ts index f31a76ae7..46cd9af01 100644 --- a/compiler/src/prelude.ts +++ b/compiler/src/prelude.ts @@ -4,38 +4,53 @@ export declare function await_(v: T): Awaited; export declare function awaitS(v: T): T extends AsyncIterable ? U : Awaited; /** R-1: Solid's memo consumes a promise or a stream its function returns, so an equation's value is never one — `await` says * where it enters (`any`: not known here; Solid still consumes it). */ -type Async = 0 extends (1 & T) ? false : true extends (T extends PromiseLike | AsyncIterable ? true : false) ? true : false; -export declare function eq(v: T, ok: Async extends true ? "MISSING_AWAIT: an equation's value is a promise or a stream, which Solid consumes; write await e (or await* e for a stream)" : true): T; +/** [1]: a promise or a stream. Read by its length, so that a type parameter's, which is not known, is neither (TY-2): TypeScript + * takes `true` for a conditional it cannot decide when no instance of its check is sure to match. */ +type Async = 0 extends (1 & T) ? [] : true extends (T extends PromiseLike | AsyncIterable ? true : false) ? [1] : []; +export declare function eq(v: T, ok: [...Async]["length"] extends 1 ? "MISSING_AWAIT: an equation's value is a promise or a stream, which Solid consumes; write await e (or await* e for a stream)" : true): T; export declare function first(v: T, init: I): T | I; export declare function pre(init?: T): T; export declare function pending(v: unknown): boolean; -/** RG-4b: an object rest, \`{ a, ...rest } = e\` (Solid's \`omit\`). */ +/** RG-4b: an object rest, `{ a, ...rest } = e` (Solid's `omit`). */ export declare function omit(v: T, ...keys: K[]): Omit; export declare function caught(v: T, alt: (e: any) => R): T | R; export declare function raise(e: unknown): never; -/** W-1/W-6: a write checks its value (or its function of the slot) against the target — whose type alone decides it. */ -export declare function set(target: T): (v: T | ((p: T) => T)) => void; +/** W-1/W-6: a write checks its value (or its function of the slot) against the target — whose type alone decides it. A + * function is applied, so one is no value here, whatever the target holds: Solid's Setter says the same. */ +/** What a source of T is written with (W-6: a function is applied to what it held, so a function is no value to write). + * A type parameter may be a function, so no value of it is one to write: `x := () => v` stores `v` for every T. The + * name is the one the tooling's message reads (tooling/rx-language-server/src/checker.js, `written`). */ +type Written = Exclude; +export declare function set(target: T): (v: Written | ((p: T) => T)) => void; +/** …at a path, a draft's too: a function is applied to the path's value there as well (W-6). */ +export declare function setAt(target: T): (v: Written | ((p: T) => T)) => void; /** A source's type when none is written: its initializer's, widened — a source is written later (`""` is a string, * `null` and `[]` say nothing yet). With a written type, `src` is that type, not what the initializer narrows it to. */ export type Widen = 0 extends (1 & T) ? any : [T] extends [null | undefined] ? any : [T] extends [never[]] ? any[] : [T] extends [string] ? string : [T] extends [number] ? number : [T] extends [boolean] ? boolean : T; export declare function src(v: T): Widen; export declare function typed(v: T): T; +/** TY-2a: a source or an equation as a handler reads it after an `await`: of its declared type, which no `if` narrowed. */ +export declare function now(): T; type ElemOf = 0 extends (1 & X) ? any : X extends Iterable ? U : X extends ArrayLike ? U : any; -export declare function each(xs: X, f: (x: ElemOf) => JSX.Element): JSX.Element; +export declare function each(xs: X, f: (x: ElemOf, i: number) => JSX.Element): JSX.Element; // RG-2b: the row and its index /** 12 SF-6a: what crosses the wire — data. `Bad` is true where a function or an instance of a class is in it (`any`: not - * known here; the run-time check stands). A server fn's parameters and result must not be. */ -type Bad = 0 extends (1 & T) ? false : T extends string | number | boolean | bigint | null | undefined ? false : T extends Function ? true - : T extends readonly (infer U)[] ? Bad : T extends object ? (Object extends T ? false : true extends { [K in keyof T]-?: Bad }[keyof T] ? true : false) : true; + * known here; the run-time check stands). A server fn's parameters and result must not be. Read 8 levels deep: a type that + * holds itself (a comment's replies are comments) is data as far as that, and the run-time check stands past it. */ +type Bad = D["length"] extends 8 ? false : 0 extends (1 & T) ? false : T extends string | number | boolean | bigint | null | undefined ? false : T extends Function ? true + : T extends readonly (infer U)[] ? Bad : T extends object ? (Object extends T ? false : true extends { [K in keyof T]-?: Bad }[keyof T] ? true : false) : true; export declare function wire(f: (...a: A) => Promise, ok: true extends Bad ? "WIRE_VALUE: its result is not data (a function, or an instance of a class, does not cross)" : true extends Bad ? "WIRE_VALUE: a parameter is not data" : true): void; /** 07 §6: a view (`props.children: View`); R-f-10: the class a panic is. */ export type View = JSX.Element; export type Panic = Error; +/** CP-4a: an entry's default export, a function of the app (`createApp`'s, either build) giving the view `app.mount` takes. */ +export type Main = (app: object) => () => View; export interface Ctx { readonly __ctx: T } -export declare function ctx(d?: T): Ctx; +export declare function ctx(d?: () => T): Ctx; // the default is read where a part asks for it (it may name what the module declares after the context) export declare function use(c: Ctx): T; export declare function provide(c: Ctx, v: NoInfer): void; +export declare function provideOr(c: Ctx, v: NoInfer | undefined): void; export declare function effect(f: () => void | (() => void)): void; -export declare function draft(seed: T, f: (d: T) => void): T; +export declare function draft(seed: S, f: (d: T) => void): T; // ST-3: the draft has the equation's type where one is written, else its seed's export declare function len(x: unknown): number; export declare function until(p: () => T): Promise>; // AC-6: Solid's until — the first truthy value export declare function onSettled(f: () => void): void; // EF-7: imperative scope only, so no cleanup return @@ -44,7 +59,9 @@ export declare function str(x: unknown): string; export declare function map(xs: X, f: (x: ElemOf, i: number) => U): U[]; export declare function filter(xs: X, f: (x: ElemOf) => unknown): ElemOf[]; export declare function every(xs: X, f: (x: ElemOf) => unknown): boolean; +export declare function indexOf(xs: X, f: (x: ElemOf) => unknown): number; export declare function sum(xs: readonly number[]): number; export declare function fail(msg: string): never; export declare function fetch(key: string): Promise; export declare function log(...a: unknown[]): void; +export declare function view(v: T): Extract any>; // RG-4c: `` where it is optional, or plain content is taken as well diff --git a/compiler/src/project.rs b/compiler/src/project.rs index 11a521261..0c68cfb22 100644 --- a/compiler/src/project.rs +++ b/compiler/src/project.rs @@ -5,12 +5,14 @@ use crate::ast::*; use crate::modules::ModuleSet; +use crate::names::{in_prelude, language}; use crate::parse::JsDecl; -use crate::signature::{ExportSig, ModSig}; +use crate::dts::{declaration_file, signature_stub, types_path_of}; +use crate::tsx::{self as tx, Place, Tsx, VarKind}; +use crate::ast::{Program, Span}; use indexmap::{IndexMap, IndexSet}; use regex::Regex; -use serde_json::Value; -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::sync::LazyLock; /// The helpers every projection imports (`__`), and the prelude's names (`len`, `map`, …): `ref/types/project.ts`'s PRELUDE. @@ -18,111 +20,10 @@ pub const PRELUDE: &str = include_str!("prelude.ts"); static ROW_WORDS: LazyLock = LazyLock::new(|| Regex::new(r"^((?:io|pending|lane|fails\([^)]*\))\s+)+").unwrap()); static SOURCE_WORD: LazyLock = LazyLock::new(|| Regex::new(r"^source\s+").unwrap()); -const BUILTINS: [&str; 13] = ["len", "str", "map", "filter", "sum", "fail", "fetch", "every", "indexOf", "log", "until", "onSettled", "onFlush"]; -fn builtin(n: &str) -> bool { - BUILTINS.contains(&n) -} +/// MO-10f: a field's row words in a component's props type, after the field's `:` (group 2). +static PROP_ROWS: LazyLock = LazyLock::new(|| Regex::new(r"(:\s*)((?:pending\s+|fails\([^)]*\)\s*)+)").unwrap()); -/// One mapping: `len` bytes at `gen` in the projection are the same text as `len` bytes at `src` in the `.rx`. -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct Mapping { - pub gen: u32, - pub src: u32, - pub len: u32, -} - -/// A coarser correspondence: `glen` bytes at `gen` in the projection were written for the `len` bytes at `src` (an -/// expression, a statement, a declaration's line), not the same text. An editor maps through it what falls between -/// mappings (a type error on `(a + b)` starts at its parenthesis); it is listed innermost first. -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct Range { - pub gen: u32, - pub glen: u32, - pub src: u32, - pub len: u32, -} - -/// Text with the mappings of the pieces in it that came from the source. -#[derive(Default, Clone)] -struct Code { - s: String, - m: Vec, - r: Vec, -} -impl Code { - fn new() -> Self { - Code::default() - } - fn of(s: &str) -> Self { - Code { s: s.to_string(), m: vec![], r: vec![] } - } - /// All of this text was written for `sp`. - fn from(mut self, sp: Span) -> Self { - if !sp.is_none() { - self.r.push(Range { gen: 0, glen: self.s.len() as u32, src: sp.start, len: sp.end - sp.start }); - } - self - } - fn t(mut self, s: &str) -> Self { - self.s.push_str(s); - self - } - fn c(mut self, o: Code) -> Self { - self.push(o); - self - } - fn push(&mut self, o: Code) { - let at = self.s.len() as u32; - self.m.extend(o.m.into_iter().map(|m| Mapping { gen: m.gen + at, ..m })); - self.r.extend(o.r.into_iter().map(|r| Range { gen: r.gen + at, ..r })); - self.s.push_str(&o.s); - } - /// `text`, mapped to `src` when it was found there. - fn at(mut self, text: &str, src: Option) -> Self { - if let Some(src) = src { - self.m.push(Mapping { gen: self.s.len() as u32, src: src as u32, len: text.len() as u32 }); - } - self.s.push_str(text); - self - } - fn join(xs: Vec, sep: &str) -> Code { - let mut out = Code::new(); - for (i, x) in xs.into_iter().enumerate() { - if i > 0 { - out.s.push_str(sep); - } - out.push(x); - } - out - } -} - -/// The reference's `W`: lines, each with the `.rx` line it came from. -#[derive(Default)] -struct W { - buf: Code, - lines: Vec, - last: usize, -} -impl W { - fn new() -> Self { - W { buf: Code::new(), lines: vec![], last: 1 } - } - /// A statement or a markup item carries no line of its own (0): it is on its declaration's. - fn emit(&mut self, text: Code, line: usize) { - if line != 0 { - self.last = line; - } - let n = text.s.matches('\n').count() + 1; - if !self.lines.is_empty() { - self.buf.s.push('\n'); - } - self.buf.push(text); - for _ in 0..n { - self.lines.push(if line != 0 { line } else { self.last }); - } - } -} +pub use crate::tsx::{Mapping, Of, Range}; /// One projected file: its TSX, for each of its lines the `.rx` line it came from, and its mappings onto the `.rx`. pub struct Projected { @@ -131,7 +32,11 @@ pub struct Projected { pub lines: Vec, pub rx: String, pub mappings: Vec, + /// for each mapping, the node of the `.rx`'s syntax tree whose text it is (`names_misplaced`) + pub of: Vec, pub ranges: Vec, + /// `(start, length)` of the helper text the projection writes by design with no place in the `.rx` (`Place::design`) + pub generated: Vec<(u32, u32)>, } /// A written type, without its row words (`pending T` → `T`, 04 CN-4a) or a context's `source` (RG-7c). @@ -148,10 +53,18 @@ fn type_text(t: &Option) -> Option { } /// `JSON.stringify` of a literal. fn j(l: &Lit) -> String { - match crate::ast::lit_json(l) { - None => "undefined".into(), - Some(v) => serde_json::to_string(&v).unwrap(), + match l { + Lit::BigInt(d) => return format!("{d}n"), + Lit::Regex(p, f) => return format!("/{p}/{f}"), + Lit::Num(n) if !n.is_finite() => return "(1 / 0)".into(), + _ => {} } + if matches!(l, Lit::Undefined) { + return "undefined".into(); + } + let mut j = crate::json::Json::new(); + crate::json::lit(&mut j, l); + j.finish() } fn js_str(s: &str) -> String { serde_json::to_string(s).unwrap() @@ -168,32 +81,69 @@ pub fn projected_path(rx: &str) -> String { format!("{rx}.tsx") } +/// A declared name written again: the same leaf, as a node of its own (placed by it; it was found once, in its +/// declaration's text). +fn again(p: Place) -> Place { + Place { copy: p.copy.map(|c| crate::tsx::Copy { of: Of { node: Span { start: c.src, end: c.src + c.len }, found: false }, ..c }), ..Place::GEN } +} + +/// For each line of a projection, the `.rx` line of what starts first on it (a mapping or a range), else the line's before. +fn line_table(p: &crate::tsx::Printed, lines: &LineIndex) -> Vec { + // (a line is what `str::lines` counts: none after the last line end) + let starts: Vec = std::iter::once(0).chain(p.code.match_indices('\n').map(|(i, _)| i + 1)).filter(|&i| i < p.code.len()).collect(); + let mut first: Vec> = vec![None; starts.len()]; + let seen = p.mappings.iter().map(|m| (m.gen, m.src)).chain(p.ranges.iter().map(|r| (r.gen, r.src))); + for (g, s) in seen { + let l = starts.partition_point(|&x| x <= g as usize) - 1; + if first[l].is_none_or(|(g0, _)| g < g0) { + first[l] = Some((g, s)); + } + } + let mut last = 1; + first.iter().map(|f| { + if let Some((_, s)) = f { + last = lines.line(*s); + } + last + }).collect() +} + pub fn project_modules(set: &ModuleSet) -> Vec { project_modules_with(set, None) } /// `prelude`: where the projections import the prelude from, in place of `__prelude.ts` at the program's root (an editor /// writes it once, where the project's own `@solidjs/web` resolves). pub fn project_modules_with(set: &ModuleSet, prelude: Option<&str>) -> Vec { + project_some(set, prelude, None) +} +/// One module's projection, as `project_modules_with` writes it among the others (CP-8e: an editor's request is for one +/// file; each module is projected from the set alone, so the others need not be written to have it). +pub fn project_module_with(set: &ModuleSet, prelude: Option<&str>, rx: &str) -> Option { + project_some(set, prelude, Some(rx)).into_iter().find(|p| p.rx == rx) +} +fn project_some(set: &ModuleSet, prelude: Option<&str>, only: Option<&str>) -> Vec { let mut out = vec![]; let mut js_stubs: IndexMap> = IndexMap::new(); - for path in &set.order { + for path in set.order.iter().filter(|p| only.is_none_or(|o| o == p.as_str())) { let p = &set.programs[path]; let src = set.sources.get(path).map(|s| s.as_str()).unwrap_or(""); - let mut pr = Proj { w: W::new(), set, path, src, js_stubs: &mut js_stubs, used: IndexSet::new(), declared: HashSet::new(), prelude }; - pr.module(p); - let w = pr.w; - out.push(Projected { path: projected_path(path), code: w.buf.s, lines: w.lines, rx: path.clone(), mappings: w.buf.m, ranges: w.buf.r }); + let t = Tsx::new(); + let mut pr = Proj { t: &t, set, path, src, js_stubs: &mut js_stubs, used: IndexSet::new(), declared: HashSet::new(), ref_fns: HashMap::new(), ref_parts: HashMap::new(), views: crate::modules::ViewProps::of(set, &set.programs[path].decls), loose: HashSet::new(), props_of: None, types: crate::modules::types_of(set, path), prelude, written: HashSet::new(), scopes: vec![], held: HashSet::new(), bound: HashSet::new(), nodes: tree_nodes(p), depth: 0, lets: vec![] }; + let body = pr.module(p); + let printed = t.print(&body, src.len()); + let lines = line_table(&printed, &p.lines); + out.push(Projected { path: projected_path(path), code: printed.code, lines, rx: path.clone(), mappings: printed.mappings, of: printed.of, ranges: printed.ranges, generated: printed.generated }); } for (rx, sig) in &set.signatures { - out.push(Projected { path: format!("{rx}.d.ts"), code: signature_stub(sig), lines: vec![], rx: rx.strip_suffix(".rx").map(|s| format!("{s}.d.rx")).unwrap_or(rx.clone()), mappings: vec![], ranges: vec![] }); + out.push(Projected { path: format!("{rx}.d.ts"), code: signature_stub(sig), lines: vec![], rx: rx.strip_suffix(".rx").map(|s| format!("{s}.d.rx")).unwrap_or(rx.clone()), mappings: vec![], of: vec![], ranges: vec![], generated: vec![] }); } for (dts, decls) in &set.declarations { - let path = dts.strip_suffix(".d.rx").map(|s| format!("{s}.d.ts")).unwrap_or(dts.clone()); - out.push(Projected { path, code: declaration_file(decls), lines: vec![], rx: dts.clone(), mappings: vec![], ranges: vec![] }); + let path = types_path_of(dts).unwrap_or_else(|| dts.strip_suffix(".d.rx").map(|s| format!("{s}.d.ts")).unwrap_or(dts.clone())); + out.push(Projected { path, code: declaration_file(decls), lines: vec![], rx: dts.clone(), mappings: vec![], of: vec![], ranges: vec![], generated: vec![] }); } for (m, names) in js_stubs { let code = names.iter().map(|n| if n == "default" { "declare const __d: any; export default __d;".to_string() } else { format!("export declare const {n}: any;") }).collect::>().join("\n"); - out.push(Projected { path: m.clone(), code, lines: vec![], rx: m, mappings: vec![], ranges: vec![] }); + out.push(Projected { path: m.clone(), code, lines: vec![], rx: m, mappings: vec![], of: vec![], ranges: vec![], generated: vec![] }); } out } @@ -211,172 +161,361 @@ pub fn unverified(p: &Projected, src: &str) -> Vec { .collect() } -/// TY-4c: an `.rx` module read by its signature (MO-9) is typed by the `.d.ts` TypeScript emits from its projection (TY-1c); -/// none is shipped here, so its exports are `any`. -fn signature_stub(sig: &ModSig) -> String { - sig.exports - .iter() - .map(|(n, x)| match x { - ExportSig::Type => format!("export type {n} = any;"), - ExportSig::Comp { .. } => format!("export declare function {n}(props: any): any;"), - _ => format!("export declare const {n}: any;"), - }) - .collect::>() - .join("\n") +/// The names of a projection against the syntax tree of its `.rx` (CP-8): text that is the same on both sides may still be +/// the wrong occurrence of a name (a parameter's, mapped onto a read of it in the body). A mapping's node is the one it +/// claims to be the text of; the mapping must be inside it, and in no node within it (an expression, a statement, a +/// nested declaration, markup): a declared name, a parameter or a written type is in its declaration's own text, once. +pub struct NameCheck { + /// the mappings found by their text within a node (a declared name, a parameter, a written type, an import's names) + pub names: usize, + /// …of which the node's text holds the same word more than once + pub ambiguous: usize, + /// …and its own text too (outside the nodes within it): which of those it is, the order of the declaration says + pub own_ambiguous: usize, + pub misplaced: Vec, } -/// MO-8: a `.d.rx` as TypeScript's `.d.ts` for the same JS module. -fn declaration_file(decls: &[JsDecl]) -> String { - let own: IndexSet<&str> = decls.iter().filter(|d| matches!(d, JsDecl::Type { .. })).map(|d| d.name()).collect(); - let mut head: Vec = vec![]; - if decls.iter().any(|d| matches!(d, JsDecl::Comp { .. } | JsDecl::Fn { shape: crate::parse::Shape::Comp, .. })) { - // MO-11a: a field's types - if !own.contains("View") { - head.push("type View = import(\"@solidjs/web/jsx-runtime\").JSX.Element;".into()); - } - if !own.contains("Component") { - head.push("type Component

    = (props: P) => View;".into()); - } - } - head.into_iter() - .chain(decls.iter().map(|d| match d { - JsDecl::Comp { name, props, .. } => { - let fs: Vec = props.iter().map(|p| format!("{}{}: {};", p.name, if p.optional { "?" } else { "" }, p.ty.as_deref().unwrap_or("any"))).collect(); - format!("export declare function {name}(props: {{ {} }}): View;", fs.join(" ")) - } - JsDecl::Type { text, .. } => format!("export {text}"), - JsDecl::Error { name, .. } => format!("export declare class {name}$ extends Error {{}}\nexport declare const {name}: (message?: string) => {name}$;\nexport type {name} = {name}$;"), - JsDecl::Fn { name, params, ptypes, ret, .. } => { - let ps = params.iter().enumerate().map(|(i, n)| match ptypes.get(i).and_then(|t| t.as_ref()) { - Some(t) => format!("{n}: {t}"), - None => n.clone(), - }); - format!("export declare function {name}({}): {};", ps.collect::>().join(", "), ret.as_deref().unwrap_or("any")) +pub fn names_misplaced(p: &Projected, prog: &Program, src: &str) -> NameCheck { + let nodes = tree_nodes(prog); + let mut out = NameCheck { names: 0, ambiguous: 0, own_ambiguous: 0, misplaced: vec![] }; + // a node's own text holds each name it declares once: two of its names on one place are one found twice (a type + // written twice in a head, `fn f(x: T): T`, mapped both times to the first) + let mut placed: HashSet<(u32, u32, u32)> = HashSet::new(); + // CP-8a: a found name is in a leaf of its node (`Program::names`), and every own leaf of a node that holds a word the + // projection found for that node is where one of them was placed (a name put on a later leaf leaves its own unmapped) + // (each node's own leaves once: `Program::names` is sorted by start, so a node's are a run of it — scanning every leaf + // for every mapping made `rxc project` quadratic in the module, 3.6 s on 43,805 lines) + let mut owns: HashMap<(u32, u32), Vec> = HashMap::new(); + let mut words: HashMap<(u32, u32), Vec<(String, Mapping)>> = HashMap::new(); + for (m, &Of { node: of, found }) in p.mappings.iter().zip(&p.of) { + let (a, b) = (m.src, m.src + m.len); + let inside = !of.is_none() && of.start <= a && b <= of.end; + let in_leaf = !found || own(&mut owns, prog, &nodes, of).iter().any(|l| l.start <= a && b <= l.end); + if !inside || !in_leaf || in_child(&nodes, of, a, b) || (found && !placed.insert((of.start, of.end, a))) { + out.misplaced.push(*m); + } + if found && inside { + words.entry((of.start, of.end)).or_default().push((src.get(a as usize..b as usize).unwrap_or("").to_string(), *m)); + } + if found { + out.names += 1; + let word = src.get(a as usize..b as usize).unwrap_or(""); + if occurrences(of.text(src), word, 0).nth(1).is_some() { + out.ambiguous += 1; + if occurrences(of.text(src), word, of.start as usize).filter(|&i| !in_child(&nodes, of, i as u32, (i + word.len()) as u32)).nth(1).is_some() { + out.own_ambiguous += 1; + } } - })) - .collect::>() - .join("\n") - + "\n" + } + } + for ((s, e), ws) in &words { + let of = Span { start: *s, end: *e }; + // a name is a whole leaf: each own leaf that is the same name is one the projection placed a name on + let leaves = own(&mut owns, prog, &nodes, of); + for (w, m) in ws.iter().filter(|(_, m)| leaves.iter().any(|l| l.start == m.src && l.end == m.src + m.len)) { + if let Some(l) = leaves.iter().find(|l| l.text(src) == w && !ws.iter().any(|(_, x)| x.src == l.start)) { + out.misplaced.push(Mapping { gen: m.gen, src: l.start, len: m.len }); + } + } + } + out +} +/// The leaves of `of` that are its own (in no node within it), once per node. +fn own<'c>(cache: &'c mut HashMap<(u32, u32), Vec>, prog: &Program, nodes: &[Span], of: Span) -> &'c [Span] { + cache.entry((of.start, of.end)).or_insert_with(|| { + let lo = prog.names.partition_point(|l| l.start < of.start); + prog.names[lo..].iter().take_while(|l| l.start <= of.end).filter(|l| l.end <= of.end && !in_child(nodes, of, l.start, l.end)).copied().collect() + }) +} +/// Every span of a program's syntax tree (`spans::walk`), sorted by start, the longest first. +fn tree_nodes(prog: &Program) -> Vec { + let mut nodes: Vec = vec![]; + crate::spans::walk(prog, &mut |s| { + if !s.is_none() { + nodes.push(s) + } + }); + nodes.sort_by_key(|s| (s.start, std::cmp::Reverse(s.end))); + nodes.dedup(); + nodes +} +/// `a..b` overlaps a node within `of` (`nodes` sorted by start, the longest first). +fn in_child(nodes: &[Span], of: Span, a: u32, b: u32) -> bool { + let i = nodes.partition_point(|s| s.start < of.start); + nodes[i..].iter().take_while(|s| s.start < b).any(|s| *s != of && s.end <= of.end && a < s.end) +} +/// Where `word` is in `hay`, as a whole word when it is a word, each offset plus `base`. +fn occurrences<'h>(hay: &'h str, word: &'h str, base: usize) -> impl Iterator + 'h { + let wordy = word.starts_with(is_word); + hay.match_indices(word).filter_map(move |(i, _)| { + let before = hay[..i].chars().next_back(); + let after = hay[i + word.len()..].chars().next(); + (!word.is_empty() && (!wordy || (!before.is_some_and(is_word) && !after.is_some_and(is_word)))).then_some(base + i) + }) } -/// `JSON.stringify(stmts).includes('"k":"await"')`: an `await` anywhere in them, closures included. +/// TY-2a: the names a closure binds — its parameters, its `let`s and loop names, a `catch`'s, a nested arrow's. +fn bound_in(params: &[String], ss: &[Stmt]) -> HashSet { + fn walk(n: Node, out: &mut HashSet) { + match n { + Node::S(Stmt { k: StmtKind::Let { name, .. } | StmtKind::For { name, .. }, .. }) => { + out.insert(name.clone()); + } + Node::S(Stmt { k: StmtKind::Try { catch_name: Some(name), .. }, .. }) => { + out.insert(name.clone()); + } + Node::E(Expr { k: ExprKind::Fn { params, .. }, .. }) => out.extend(params.iter().cloned()), + _ => {} + } + children(n, true).into_iter().for_each(|c| walk(c, out)); + } + let mut out: HashSet = params.iter().cloned().collect(); + ss.iter().for_each(|s| walk(Node::S(s), &mut out)); + out +} +/// TY-2a: every name statements read. +fn ids_in(ss: &[Stmt]) -> HashSet { + fn walk(n: Node, out: &mut HashSet) { + if let Node::E(Expr { k: ExprKind::Id(name), .. }) = n { + out.insert(name.clone()); + } + children(n, true).into_iter().for_each(|c| walk(c, out)); + } + let mut out = HashSet::new(); + ss.iter().for_each(|s| walk(Node::S(s), &mut out)); + out +} +/// An `await` anywhere in them, closures included. fn has_await(ss: &[Stmt]) -> bool { - stmts_json(ss).to_string().contains("\"k\":\"await\"") + ss.iter().any(|s| crate::ast::has_await(Node::S(s))) } /// The names an expression reads, in the order the reference's walk meets them; a `pre` reads the previous instant, so /// nothing under it orders. fn free_ids(e: &Expr) -> IndexSet { - fn go(v: &Value, out: &mut IndexSet) { - match v { - Value::Array(xs) => xs.iter().for_each(|x| go(x, out)), - Value::Object(o) => { - if o.get("k").and_then(|k| k.as_str()) == Some("id") { - if let Some(n) = o.get("name").and_then(|n| n.as_str()) { - out.insert(n.to_string()); - } - } - if o.get("k").and_then(|k| k.as_str()) == Some("pre") { - return; - } - for (k, x) in o { - if k != "k" { - go(x, out); - } - } + fn go(n: Node, out: &mut IndexSet) { + match n { + Node::E(Expr { k: ExprKind::Id(name), .. }) => { + out.insert(name.clone()); } + Node::E(Expr { k: ExprKind::Pre { .. }, .. }) => return, _ => {} } + children(n, true).into_iter().for_each(|c| go(c, out)); } let mut out = IndexSet::new(); - go(&e.to_json(), &mut out); + go(Node::E(e), &mut out); out } +/// The sources a block's declarations write plainly (no path, not a context's): what has an alias of its declared type. +fn written_in(n: Node, out: &mut HashSet) { + if let Node::S(Stmt { k: StmtKind::Write { target, .. } | StmtKind::Optimistic { target, .. }, .. }) = n { + if target.path.is_empty() && !target.is_ctx() { + out.insert(target.name.clone()); + } + } + children(n, true).into_iter().for_each(|c| written_in(c, out)); +} +/// TY-2a: every name read in a closure that runs later — a handler, an action (declared, or a block), a statement-bodied +/// arrow (a superset: what is bound there is left in). +fn held_in(n: Node, inside: bool, out: &mut HashSet) { + match n { + Node::E(Expr { k: ExprKind::Id(name), .. }) if inside => { + out.insert(name.clone()); + } + Node::M(Markup { kind: MarkupKind::El { attrs, children: kids, .. }, .. }) => { + for a in attrs { + held_in(Node::E(&a.e), inside || is_handler(&a.name), out); + } + kids.iter().for_each(|m| held_in(Node::M(m), inside, out)); + return; + } + _ => {} + } + let later = matches!(n, Node::E(Expr { k: ExprKind::Fn { stmts: Some(_), .. }, .. }) | Node::S(Stmt { k: StmtKind::Action(_), .. }) | Node::D(Decl::Action { .. })); + children(n, true).into_iter().for_each(|c| held_in(c, inside || later, out)); +} -struct Proj<'a> { - w: W, - set: &'a ModuleSet, - path: &'a str, - src: &'a str, - js_stubs: &'a mut IndexMap>, +struct Proj<'s> { + /// W-1c (2026-11-29): the `let`s of the statement lists being written, innermost last — a write of one is the local's + lets: Vec>, + t: &'s Tsx, + set: &'s ModuleSet, + path: &'s str, + src: &'s str, + js_stubs: &'s mut IndexMap>, /// prelude names the module reads used: IndexSet, /// names the module declares (they shadow the prelude) declared: HashSet, - prelude: Option<&'a str>, + /// MO-10: declared JS fns with a `ref` parameter or result, by local name + ref_fns: HashMap, + /// MO-10b: equations bound to such a fn's tuple or record result + ref_parts: HashMap, + /// MO-11t: the props of the JS components this module imports that take a view + views: crate::modules::ViewProps, + /// RG-4c: what the component shows as a view that may be plain content, or nothing + loose: HashSet, + /// the props of the component being projected: their name, and their type with its aliases read + props_of: Option<(String, String)>, + types: crate::modules::Types, + prelude: Option<&'s str>, + /// the sources the module writes, and per block being projected the sources and the other names it declares + written: HashSet, + scopes: Vec<(HashSet, HashSet, HashSet)>, + /// every node of the module's syntax tree with a span (`tree_nodes`) + nodes: Vec, + /// TY-2a: the names read in a closure that runs later (a handler, an action), and those the closure being projected + /// binds itself (its parameters, its locals, anywhere in it) + held: HashSet, + bound: HashSet, + /// how deep in markup the children being written are (their layout: one a line) + depth: usize, } -impl Proj<'_> { +type Ex = tx::Ex; +type St = tx::St; + +impl<'s> Proj<'s> { // ---- where a name or a written type is, in the source ---- - /// The first whole-word `word` in `within`, at or after `from`. + /// The first whole-word `word` at or after `from` in a leaf of the node `within` (CP-8a, `Program::names`: where the + /// parser read a declared name, a parameter, a written type, a target, an import's name or path, a record's key) that + /// is its own — in no expression, statement, declaration or markup within it (a parameter is not the body's read of + /// it). A name is its leaf; a written type's text with its row words dropped is found in its leaf, in the order the + /// pieces are written. `names_misplaced` checks each mapping so made. fn find(&self, word: &str, within: Span, from: usize) -> Option { if within.is_none() || word.is_empty() { return None; } - let (a, b) = ((within.start as usize).max(from), within.end as usize); - let hay = self.src.get(a..b)?; - let wordy = word.starts_with(is_word); - hay.match_indices(word).find_map(|(i, _)| { - let before = hay[..i].chars().next_back(); - let after = hay[i + word.len()..].chars().next(); - (!wordy || (!before.is_some_and(is_word) && !after.is_some_and(is_word))).then_some(a + i) + let a = (within.start as usize).max(from); + let leaves = &self.set.programs.get(self.path)?.names; + let lo = leaves.partition_point(|s| s.start < within.start); + leaves[lo..].iter().take_while(|s| s.start < within.end).filter(|s| s.end <= within.end && s.end as usize > a && !in_child(&self.nodes, within, s.start, s.end)).find_map(|s| { + let b = (s.start as usize).max(a); + occurrences(self.src.get(b..s.end as usize)?, word, b).next() }) } - /// `word` as found in `within` from `*from` on, mapped; `*from` moves past it. - fn name(&self, word: &str, within: Span, from: &mut usize) -> Code { + /// `word` as found in `within` from `*from` on: where it is; `*from` moves past it. + fn name(&self, word: &str, within: Span, from: &mut usize) -> Place { let at = self.find(word, within, *from); if let Some(a) = at { *from = a + word.len(); } - Code::new().at(word, at) + Place::copy(word, at, Of { node: within, found: true }) + } + /// A name declared (or a parameter), found in `within`. + fn bind(&self, word: &str, within: Span, from: &mut usize) -> tx::Name { + let p = self.name(word, within, from); + self.t.bind(word, p) } /// A written type's text (row words dropped), found after `*from`. - fn ty(&self, t: &str, within: Span, from: &mut usize) -> Code { - self.name(t, within, from) + fn ty(&self, text: &str, within: Span, from: &mut usize) -> tx::Ty { + let p = self.name(text, within, from); + self.t.raw_type(text, p, &[]) + } + /// `T`, or nothing. + fn ann(&self, t: &Option, within: Span, from: &mut usize) -> Option { + type_text(t).map(|x| self.ty(&x, within, from)) } - /// `: T`, or nothing. - fn ann(&self, t: &Option, within: Span, from: &mut usize) -> Code { - match type_text(t) { - Some(x) => Code::of(": ").c(self.ty(&x, within, from)), - None => Code::new(), + /// Error classes as the type of what is caught (`A | B`, `Error` when none is written), each class found in `within` + /// from `*from` on. + fn classes(&self, classes: &Option>, within: Span, from: &mut usize) -> tx::Ty { + let Some(cs) = classes else { return self.gen_ty("Error") }; + let mut text = String::new(); + let mut pieces = vec![]; + for (i, c) in cs.iter().enumerate() { + if i > 0 { + text.push_str(" | "); + } + if let Some(cp) = self.name(c, within, from).copy { + pieces.push((text.len() as u32, cp)); + } + text.push_str(c); } + self.t.raw_type(&text, Place::GEN, &pieces) + } + /// The projection's own type text. + fn gen_ty(&self, text: &str) -> tx::Ty { + self.t.raw_type(text, Place::GEN, &[]) } /// `n` or `n: T` for a parameter list of names and their written types (no row words to drop). - fn params(&self, params: &[String], ptypes: &[Option], within: Span, from: &mut usize) -> Code { - let ps = params + fn params(&self, params: &[String], ptypes: &[Option], required: Option, within: Span, from: &mut usize) -> Vec { + params .iter() .enumerate() .map(|(i, n)| { - let c = self.name(n, within, from); - match ptypes.get(i).and_then(|t| t.as_ref()) { - Some(t) => c.t(": ").c(self.ty(t, within, from)), - None => c, - } + let b = self.bind(n, within, from); + // AC-1f: a parameter an action's call may leave out + let opt = required.is_some_and(|r| i >= r); + let t = ptypes.get(i).and_then(|t| t.as_ref()).map(|t| self.ty(t, within, from)); + self.t.param(b, opt, t) }) - .collect(); - Code::join(ps, ", ") + .collect() + } + /// A type parameter list, `<…>` as written, found in `within`. + fn tparams(&self, t: &Option, within: Span, from: &mut usize) -> Option { + let t = t.as_ref()?; + let mut p = self.name(t, within, from); + let inner = t.strip_prefix('<').and_then(|x| x.strip_suffix('>')); + let Some(inner) = inner else { return Some(self.t.raw_tparams(t, p)) }; + // the brackets are the printer's (which writes `` in TSX): the mapping is what is between them + if let Some(c) = p.copy.as_mut() { + c.src += 1; + c.len -= 2; + } + Some(self.t.raw_tparams(inner, p)) } - fn module(&mut self, p: &Program) { - let saved = std::mem::replace(&mut self.w, W::new()); - self.decls(&p.decls, "", true); + /// The module's statements: the prelude's imports, its declarations, its view, what JS imports from an entry. + fn module(&mut self, p: &Program) -> Vec { + let t = self.t; + let mut body = self.decls(&p.decls, true); if !p.view.is_empty() { - self.w.emit(Code::of("export const __view = ("), p.view[0].line.unwrap_or(1)); - self.markup(&p.view, " "); - self.w.emit(Code::of(");"), p.view[p.view.len() - 1].line.unwrap_or(1)); + let v = self.markup(&p.view); + // MO-1c: the mounted view of the module's default component maps nowhere, by design: what TypeScript says of the + // mount (a route page's component wants the props its router gives) is no error of the `.rx`, and an error with + // no place is dropped + let d = t.var_decl(t.gen(), VarKind::Const, t.bind("__view", Place::GEN), None, Some(v), false); + body.push(t.exported(true, t.key(Place::DESIGN), tx::Decl::Var(d))); + } + if p.decls.iter().any(|d| matches!(d, Decl::Component { is_default: true, .. })) { + // CP-4a: what JS imports from an entry + body.push(t.var(t.gen(), VarKind::Const, t.bind("__main", Place::GEN), Some(self.gen_ty("__.Main")), None, true)); + body.push(tx::St::ExportDefault(t.id("__main", Place::GEN))); } - let body = std::mem::replace(&mut self.w, saved); - let prelude: Vec = self.used.iter().filter(|n| !self.declared.contains(*n)).cloned().collect(); let types: Vec<&str> = ["View", "Panic"].into_iter().filter(|n| !self.declared.contains(*n)).collect(); let rel = self.prelude.map(|p| p.to_string()).unwrap_or_else(|| self.rel("__prelude.ts")); - let mut head = format!("import * as __ from \"{rel}\"; import type {{ {} }} from \"{rel}\";", types.join(", ")); - if !prelude.is_empty() { - head += &format!(" import {{ {} }} from \"{rel}\";", prelude.join(", ")); - } - self.w.emit(Code::of(&head), 0); - if !body.lines.is_empty() { - self.w.buf.s.push('\n'); - self.w.buf.push(body.buf); - self.w.lines.extend(body.lines); + let mut head = vec![]; + let ns = tx::Spec::Ns(t.bind("__", Place::GEN)); + // the prelude's imports: by design (where the `.rx` imports a prelude name, from its own prelude module, it is + // imported here from the prelude an editor writes) + head.push(self.import_as(Place::DESIGN, vec![ns], &rel, Place::GEN, false)); + let ts = types.iter().map(|n| self.import_name(n, n, Place::GEN, Place::GEN)).collect(); + head.push(self.import_as(Place::DESIGN, ts, &rel, Place::GEN, true)); + if !self.used.is_empty() { + let us = self.used.iter().map(|u| match u.split_once(" as ") { + Some((n, a)) => self.import_name(n, a, Place::GEN, Place::GEN), + None => self.import_name(u, u, Place::GEN, Place::GEN), + }); + let us: Vec<_> = us.collect(); + head.push(self.import_as(Place::DESIGN, us, &rel, Place::GEN, false)); } + head.extend(body); + head + } + fn import(&self, specs: Vec, from: &str, at: Place, kind: bool) -> St { + self.import_as(Place::GEN, specs, from, at, kind) + } + /// An import statement that is `whole` (the prelude's, `Place::DESIGN`). + fn import_as(&self, whole: Place, specs: Vec, from: &str, at: Place, kind: bool) -> St { + let t = self.t; + let k = t.key(whole); + tx::St::Import(k, kind, specs, t.string(from, at)) + } + fn import_name(&self, name: &str, alias: &str, n: Place, a: Place) -> tx::Spec { + let t = self.t; + // (one name written once: its place is the imported name's) + let a = if name == alias { Place::GEN } else { a }; + let imported = t.name(name, n); + tx::Spec::Named(imported, t.bind(alias, a)) } /// A path relative to this module's directory, for the prelude (at the root of the program). fn rel(&self, f: &str) -> String { @@ -389,48 +528,141 @@ impl Proj<'_> { } // ---- declarations, in dependency order (functions are hoisted; values are not) ---- - fn decls(&mut self, ds: &[Decl], ind: &str, top: bool) { - let ex = |d: &Decl| if top && d.exported() { "export " } else { "" }; + /// A write names the alias of its source's type when the nearest block that declares its name declares a source. + fn aliased(&self, name: &str) -> bool { + for (src, other, _) in self.scopes.iter().rev() { + if src.contains(name) { + return true; + } + if other.contains(name) { + return false; + } + } + false + } + /// TY-2a: a read of `name` in a closure that runs later is of a source or an equation (the nearest block that declares + /// the name declares one), whose type alias the closure reads it by. + fn held_slot(&self, name: &str) -> bool { + for (_, other, slots) in self.scopes.iter().rev() { + if slots.contains(name) { + return true; + } + if other.contains(name) { + return false; + } + } + false + } + /// TY-2a: after a statement that awaits, a handler or an action reads a source or an equation as it is then, not as + /// the view branch around it (or a check before the `await`) narrowed it: the branch may no longer hold. The rest of + /// the statements are a block that binds each slot it reads again, to a value of the slot's declared type (`{ const + /// detail = __.now<__w_detail>(); …`). What the closure binds itself is its own. Sorted, as `ref/types/project.ts`. + fn shadows(&self, rest: &[Stmt]) -> Vec { + let t = self.t; + let inner = bound_in(&[], rest); + let mut out: Vec = ids_in(rest).into_iter().filter(|n| !self.bound.contains(n) && !inner.contains(n) && self.held_slot(n)).collect(); + out.sort(); + out.iter() + .map(|n| { + let v = t.call_helper("now", Some(t.targs(vec![self.gen_ty(&format!("__w_{n}"))])), vec![]); + // (by design: the slot bound again has no one place in the `.rx`) + t.var(t.key(Place::DESIGN), VarKind::Const, t.bind(n, Place::GEN), None, Some(v), false) + }) + .collect() + } + /// A write is typed by what its source was declared to hold, not by what an `if` around it narrowed a read of it to + /// (`if (a) { a := undefined }`): a source the module writes has an alias of its type beside it, `type __w_a = typeof + /// a`, which a type query at the write would not be (it narrows as a read does). + fn decls(&mut self, ds: &[Decl], top: bool) -> Vec { + if top { + for d in ds { + written_in(Node::D(d), &mut self.written); + held_in(Node::D(d), false, &mut self.held); + } + } + let src = ds.iter().filter_map(|d| match d { + Decl::Source { name, .. } if self.written.contains(name) => Some(name.clone()), + _ => None, + }); + let other = ds.iter().flat_map(|d| match d { + Decl::Source { .. } => vec![], + Decl::Import { names, .. } => names.iter().map(|n| n.alias.clone()).collect(), + _ => d.name().map(|n| vec![n.to_string()]).unwrap_or_default(), + }); + let slots = ds.iter().filter_map(|d| match d { + Decl::Source { name, .. } | Decl::Eq { name, .. } if self.held.contains(name) => Some(name.clone()), + _ => None, + }); + // (the block's: its view and its tail are in it too — who calls this ends it, `self.scopes.pop()`) + self.scopes.push((src.collect(), other.collect(), slots.collect())); + // N7-3 (2026-12-02, the seventh review's N3): what an equation holds of a `ref` part is known before the block's + // actions are written, which come before its equations: `dz.files` read in an action is its value there, as in an + // equation or a handler (it was the accessor, and TypeScript refused what it was given to, TS2345) for d in ds { + if let Decl::Eq { name, e, .. } = d { + if let Some(sh @ (crate::parse::Shape::Items(_) | crate::parse::Shape::Fields(_))) = self.ref_shape(e) { + self.ref_parts.insert(name.clone(), sh); + } + } + } + let mut out = vec![]; + self.decls_in(ds, top, &mut out); + out + } + fn decls_in(&mut self, ds: &[Decl], top: bool, out: &mut Vec) { + let t = self.t; + let ex = |d: &Decl| top && d.exported(); + // what the module binds at its top; a nested name shadows the prelude's where it stands + for d in ds.iter().filter(|_| top) { if let Some(n) = d.name() { self.declared.insert(n.to_string()); } + if let Decl::Import { names, .. } = d { + self.declared.extend(names.iter().map(|n| n.alias.clone())); + } } for d in ds { let sp = d.span(); let mut at = sp.start as usize; match d { - Decl::Import { .. } => self.import_decl(d, ind), - Decl::TypeDecl { text, line, .. } => { - let c = Code::of(ind).t(ex(d)).c(self.name(text, sp, &mut at)); - self.w.emit(c, *line); + Decl::Import { .. } => self.import_decl(d, out), + Decl::TypeDecl { text, .. } => { + let p = self.name(text, sp, &mut at); + let lead = if ex(d) { "export " } else { "" }; + out.push(t.raw_stmt(&format!("{lead}{text}"), Place::GEN, p.copy.map(|c| (lead.len() as u32, c)))); } - Decl::Error { name, params, ptypes, msg, line, .. } => { + Decl::Error { name, params, ptypes, msg, .. } => { + let e = if ex(d) { "export " } else { "" }; let fields = params.iter().enumerate().map(|(i, n)| format!("declare {n}: {};", ptypes.get(i).and_then(|t| t.as_deref()).unwrap_or("any"))).collect::>().join(" "); - let nm = self.name(name, sp, &mut at); - let ps = self.params(params, ptypes, sp, &mut at); - let body = match msg { - Some(m) => Code::of("{ void (").c(self.expr(m, false, None)).t(&format!("); return new {name}$(); }}")), - None => Code::of(&format!("new {name}$()")), + out.push(t.raw_stmt(&format!("{e}class {name}$ extends Error {{ {fields} }}"), Place::GEN, None)); + let np = self.name(name, sp, &mut at); + let nm = t.bind(name, np); + let ps = self.params(params, ptypes, None, sp, &mut at); + let made = || t.raw(&format!("new {name}$()"), Place::GEN); + let f = match msg { + Some(m) => { + let v = self.expr(m, false, None); + let void = t.unary(t.gen(), tx::Un::Void, v); + t.arrow_block(t.gen(), false, ps, Some(self.gen_ty(&format!("{name}$"))), vec![t.expr_stmt(t.gen(), void), t.ret(t.gen(), Some(made()))]) + } + None => t.arrow_ret(t.gen(), ps, self.gen_ty(&format!("{name}$")), made()), }; - let c = Code::of(&format!("{ind}{}class {name}$ extends Error {{ {fields} }}\n{ind}{}const ", ex(d), ex(d))) - .c(nm) - .t(" = (") - .c(ps) - .t(&format!("): {name}$ => ")) - .c(body) - .t(&format!(";\n{ind}{}type {name} = {name}$;", ex(d))); - self.w.emit(c, *line); - } - Decl::Context { name, ty, dflt, line, .. } => { - let nm = self.name(name, sp, &mut at); - let t = match type_text(ty) { + let decl = t.var_decl(t.gen(), VarKind::Const, nm, None, Some(f), false); + out.push(t.exported(ex(d), t.gen(), tx::Decl::Var(decl))); + // the type the class is known by: the declared name again, onto its leaf (as `type __w_x`) + out.push(t.raw_stmt(&format!("{e}type {name} = {name}$"), Place::GEN, again(np).copy.map(|c| ((e.len() + 5) as u32, c)))); + } + Decl::Context { name, ty, dflt, .. } => { + let nm = self.bind(name, sp, &mut at); + let ty = match type_text(ty) { Some(x) => self.ty(&x, sp, &mut at), - None => Code::of("any"), + None => self.gen_ty("any"), }; - let dv = dflt.as_ref().map(|e| self.expr(e, false, None)).unwrap_or_default(); - let c = Code::of(ind).t(ex(d)).t("const ").c(nm).t(" = __.ctx<").c(t).t(">(").c(dv).t(");"); - self.w.emit(c, *line); + // read where a part asks for it + let dv: Vec = dflt.as_ref().map(|e| t.arrow(t.gen(), false, vec![], self.expr(e, false, None))).into_iter().collect(); + let v = t.call_helper("ctx", Some(t.targs(vec![ty])), dv); + let decl = t.var_decl(t.gen(), VarKind::Const, nm, None, Some(v), false); + out.push(t.exported(ex(d), t.gen(), tx::Decl::Var(decl))); } _ => {} } @@ -439,56 +671,108 @@ impl Proj<'_> { let sp = d.span(); let mut at = sp.start as usize; match d { - Decl::Fn { name, params, decls, tail, line, ret, .. } => { - let nm = self.name(name, sp, &mut at); - let ps = Code::join( - params - .iter() - .map(|p| { - let n = self.name(&p.name, sp, &mut at); - n.c(self.ann(&p.ty, sp, &mut at)) - }) - .collect(), - ", ", - ); + Decl::Fn { name, params, decls, tail, ret, tparams, .. } => { + let nm = self.bind(name, sp, &mut at); + let tp = self.tparams(tparams, sp, &mut at); + let ps = params + .iter() + .map(|p| { + let n = self.bind(&p.name, sp, &mut at); + let ty = self.ann(&p.ty, sp, &mut at); + t.param(n, p.opt, ty) + }) + .collect(); let r = self.ann(ret, sp, &mut at); - let head = Code::of(ind).t(ex(d)).t("function ").c(nm).t("(").c(ps).t(")").c(r); - if decls.is_empty() { - let t = self.expr(tail, false, None); - self.w.emit(head.t(" { return ").c(t).t("; }"), *line); + let mut body = vec![]; + if !decls.is_empty() { + body = self.decls(decls, false); + } + let tv = self.expr(tail, false, None); + body.push(t.ret(t.gen(), Some(tv))); + if !decls.is_empty() { + self.scopes.pop(); + } + let f = t.function(t.gen(), false, nm, tp, ps, r, body); + out.push(t.exported(ex(d), t.gen(), tx::Decl::Fn(Box::new(f)))); + } + Decl::Component { name, props, decls, view, props_type, no_props, tparams, .. } => { + let nm = self.bind(name, sp, &mut at); + let tp = self.tparams(tparams, sp, &mut at); + // TY-3d (2026-11-24): `component C()` declares no props, and takes none — a function of nothing + if *no_props { + let mut body = self.decls(decls, false); + let v = self.markup(view); + body.push(t.ret(t.gen(), Some(v))); + self.scopes.pop(); + let f = t.function(t.gen(), false, nm, tp, vec![], None, body); + out.push(t.exported(ex(d), t.gen(), tx::Decl::Fn(Box::new(f)))); continue; } - self.w.emit(head.t(" {"), *line); - self.decls(decls, &format!("{ind} "), false); - let t = self.expr(tail, false, None); - self.w.emit(Code::of(&format!("{ind} return ")).c(t).t(&format!(";\n{ind}}}")), *line); - } - Decl::Component { name, props, decls, view, line, props_type, .. } => { - let nm = self.name(name, sp, &mut at); - let pn = self.name(props, sp, &mut at); + let pp = self.name(props, sp, &mut at); + // (props the `.rx` destructures, `component Card({ title })`, are named by the loader: by design) + let pn = t.bind(props, if pp.copy.is_none() { Place::DESIGN } else { pp }); let pt = match props_type { - Some(t) => Code::of(": ").c(self.ty(t, sp, &mut at)), - None => Code::of(": any"), + // MO-10f: a field's row words (`data: pending fails(Error) T`) are `.rx`'s, not TypeScript's: the + // type is written without them, each piece between them mapped where it is + Some(ty) => { + let mut text = String::new(); + let mut pieces = vec![]; + let mut last = 0; + let piece = |s: &str, text: &mut String, pieces: &mut Vec<(u32, crate::tsx::Copy)>, at: &mut usize| { + if let Some(c) = self.name(s, sp, at).copy { + pieces.push((text.len() as u32, c)); + } + text.push_str(s); + }; + for m in PROP_ROWS.captures_iter(ty) { + let words = m.get(2).unwrap(); + piece(&ty[last..words.start()], &mut text, &mut pieces, &mut at); + last = words.end(); + } + piece(&ty[last..], &mut text, &mut pieces, &mut at); + t.raw_type(&text, Place::GEN, &pieces) + } + None => self.gen_ty("any"), + }; + let shown = crate::modules::shown(props, props_type.as_deref(), decls, view, &self.types, tparams.as_deref()); + let was = std::mem::replace(&mut self.loose, shown.iter().filter(|(_, v)| v.mixed || v.optional).map(|(f, _)| format!("{props}.{f}")).collect()); + let was_props = std::mem::replace(&mut self.props_of, props_type.as_deref().map(|ty| (props.clone(), crate::modules::expand_type(ty, &crate::modules::without(&self.types, tparams.as_deref()), 0)))); + let mut body = self.decls(decls, false); + let v = self.markup(view); + body.push(t.ret(t.gen(), Some(v))); + self.scopes.pop(); + self.loose = was; + self.props_of = was_props; + let f = t.function(t.gen(), false, nm, tp, vec![t.param(pn, false, Some(pt))], None, body); + out.push(t.exported(ex(d), t.gen(), tx::Decl::Fn(Box::new(f)))); + } + Decl::Action { name, params, ptypes, body, .. } | Decl::Server { name, params, ptypes, body, .. } => { + let np = self.name(name, sp, &mut at); + let nm = t.bind(name, np); + let required = match d { + Decl::Action { required, .. } => *required, + _ => None, }; - self.w.emit(Code::of(ind).t(ex(d)).t("function ").c(nm).t("(").c(pn).c(pt).t(") {"), *line); - self.decls(decls, &format!("{ind} "), false); - self.w.emit(Code::of(&format!("{ind} return (")), *line); - self.markup(view, &format!("{ind} ")); - self.w.emit(Code::of(&format!("{ind} );\n{ind}}}")), *line); - } - Decl::Action { name, params, ptypes, body, line, .. } | Decl::Server { name, params, ptypes, body, line, .. } => { - let nm = self.name(name, sp, &mut at); - let ps = self.params(params, ptypes, sp, &mut at); + let ps = self.params(params, ptypes, required, sp, &mut at); let r = match d { - Decl::Server { ret: Some(r), .. } => Code::of(": Promise<").c(self.ty(r, sp, &mut at)).t(">"), - _ => Code::new(), + Decl::Server { ret: Some(r), .. } => { + let p = self.name(r, sp, &mut at); + Some(t.raw_type(&format!("Promise<{r}>"), Place::GEN, &p.copy.map(|c| (8, c)).into_iter().collect::>())) + } + Decl::Action { ret: Some(r), .. } => Some(self.ty(r, sp, &mut at)), // AC-1i: answers at the call + _ => None, }; - self.w.emit(Code::of(ind).t(ex(d)).t("async function ").c(nm).t("(").c(ps).t(")").c(r).t(" {"), *line); - self.stmts(body, &format!("{ind} ")); - self.w.emit(Code::of(&format!("{ind}}}")), *line); + let is_async = !matches!(d, Decl::Action { ret: Some(_), .. }); + let was = std::mem::replace(&mut self.bound, bound_in(params, body)); + let ss = self.stmts(body); + self.bound = was; + let f = t.function(t.gen(), is_async, nm, None, ps, r, ss); + out.push(t.exported(ex(d), t.gen(), tx::Decl::Fn(Box::new(f)))); if matches!(d, Decl::Server { .. }) { // SF-6a, statically where the types are known - self.w.emit(Code::of(&format!("{ind}__.wire({name}, true);")), *line); + // (the declared name again, onto its leaf) + let w = t.call_helper("wire", None, vec![t.id(name, again(np)), t.bool_(true)]); + out.push(t.expr_stmt(t.gen(), w)); } } _ => {} @@ -498,58 +782,127 @@ impl Proj<'_> { let sp = d.span(); let mut at = sp.start as usize; match d { - Decl::Source { name, init, line, ty, .. } => { - let nm = self.name(name, sp, &mut at); + Decl::Source { name, init, ty, .. } => { + let np = self.name(name, sp, &mut at); + let nm = t.bind(name, np); let a = self.ann(ty, sp, &mut at); + let iv = self.expr(init, false, None); let v = match type_text(ty) { - Some(t) => Code::of(&format!("__.typed<{t}>(")).c(self.expr(init, false, None)).t(")"), - None => Code::of("__.src(").c(self.expr(init, false, None)).t(")"), + Some(x) => t.call_helper("typed", Some(t.targs(vec![self.gen_ty(&x)])), vec![iv]), + None => t.call_helper("src", None, vec![iv]), }; - self.w.emit(Code::of(ind).t(ex(d)).t("const ").c(nm).c(a).t(" = ").c(v).t(";").from(sp), *line); + let decl = t.var_decl(t.key(Place::atom(sp)), VarKind::Const, nm, a, Some(v), false); + out.push(t.exported(ex(d), t.key(Place::atom(sp)), tx::Decl::Var(decl))); + if self.written.contains(name) || self.held.contains(name) { + out.push(self.alias(name, np)); + } } - Decl::Eq { name, e, line, ty, .. } => { - let nm = self.name(name, sp, &mut at); + Decl::Eq { name, e, ty, .. } => { + let np = self.name(name, sp, &mut at); + let nm = t.bind(name, np); let a = self.ann(ty, sp, &mut at); - let v = Code::of("__.eq(").c(self.expr(e, false, Some(name))).t(", true)"); // R-1: no promise without `await` - self.w.emit(Code::of(ind).t(ex(d)).t("const ").c(nm).c(a).t(" = ").c(v).t(";").from(sp), *line); + // MO-10b: a `ref` result is read as its value + let x = self.ref_shape(e); + if let Some(sh @ (crate::parse::Shape::Items(_) | crate::parse::Shape::Fields(_))) = &x { + self.ref_parts.insert(name.clone(), sh.clone()); + } + let whole = matches!(x, Some(crate::parse::Shape::Part(crate::parse::Part::Ref))); + let mut v = self.expr(e, false, Some(name)); + if whole { + v = t.call(t.gen(), v, None, vec![]); + } + let v = t.call_helper("eq", None, vec![v, t.bool_(true)]); // R-1: no promise without `await` + let decl = t.var_decl(t.key(Place::atom(sp)), VarKind::Const, nm, a, Some(v), false); + out.push(t.exported(ex(d), t.key(Place::atom(sp)), tx::Decl::Var(decl))); + if self.held.contains(name) { + out.push(self.alias(name, np)); + } } - Decl::Provide { name, e, line, .. } => { - let nm = self.name(name, sp, &mut at); + Decl::Provide { name, e, .. } => { + let np = self.name(name, sp, &mut at); + let nm = t.id(name, np); let v = self.expr(e, false, None); - self.w.emit(Code::of(&format!("{ind}__.provide(")).c(nm).t(", ").c(v).t(");"), *line); + // RG-4c: a view the component may not have been given is provided as it is — the context then holds none, + // and what shows it shows nothing (`item?: (o) => View`, `provide item = props.item`) + let optional = match (&e.k, &self.props_of) { + (ExprKind::Member { o, p, .. }, Some((props, ty))) if matches!(&o.k, ExprKind::Id(n) if n == props) => { + crate::modules::field_type(ty, p).is_some_and(|(t, opt)| opt && matches!(crate::modules::view_type(t.trim()), Some((false, _)))) + } + _ => false, + }; + let c = t.call_helper(if optional { "provideOr" } else { "provide" }, None, vec![nm, v]); + out.push(t.expr_stmt(t.gen(), c)); } _ => {} } } for d in ds { - if let Decl::Effect { inputs, body, line, .. } = d { - self.w.emit(Code::of(&format!("{ind}__.effect(() => {{")), *line); + if let Decl::Effect { inputs, body, .. } = d { + let mut ss = vec![]; for (i, e) in inputs.iter().enumerate() { let v = self.expr(e, false, None); - self.w.emit(Code::of(&format!("{ind} const ${i} = ")).c(v).t(";"), *line); + ss.push(t.var(t.gen(), VarKind::Const, t.bind(&format!("${i}"), Place::GEN), None, Some(v), false)); } - self.stmts(body, &format!("{ind} ")); - self.w.emit(Code::of(&format!("{ind}}});")), *line); + ss.extend(self.stmts(body)); + let f = t.arrow_block(t.gen(), false, vec![], None, ss); + let c = t.call_helper("effect", None, vec![f]); + out.push(t.expr_stmt(t.gen(), c)); } } } + /// MO-10b: the shape of what a call of a declared fn with `ref` parts answers (`makeBox()`: `{ items: ref … }`). + fn ref_shape(&self, e: &Expr) -> Option { + match &e.k { + ExprKind::Call { f, .. } => match &f.k { + ExprKind::Id(g) => self.ref_fns.get(g).and_then(|d| if let JsDecl::Fn { shape, .. } = d { Some(shape.clone()) } else { None }), + _ => None, + }, + _ => None, + } + } + /// `type __w_x = typeof x`: the declared name again, onto its leaf (placed by it, a node of its own). + fn alias(&self, name: &str, declared: Place) -> St { + let t = self.t; + let q = t.type_of(t.id_ref(name, again(declared))); + tx::St::Decl(t.type_alias(t.gen(), t.bind(&format!("__w_{name}"), Place::GEN), q)) + } - fn import_decl(&mut self, d: &Decl, ind: &str) { - let Decl::Import { names, from, line, resolved, declared, .. } = d else { return }; + fn import_decl(&mut self, d: &Decl, out: &mut Vec) { + let t = self.t; + let Decl::Import { names, from, resolved, declared, reexport, .. } = d else { return }; let sp = d.span(); - for n in names { - if builtin(&n.name) { - // the prelude's own (`import { log } from "./prelude"`) - self.declared.remove(&n.alias); - } - } - for n in names.iter().filter(|n| builtin(&n.name)) { - self.used.insert(n.name.clone()); + // the prelude's own (`import { log } from "./prelude"`) + for n in names.iter().filter(|n| in_prelude(d, &n.name, self.set.conformance)) { + self.used.insert(if n.name == n.alias { n.name.clone() } else { format!("{} as {}", n.name, n.alias) }); } - let rest: Vec<&ImportName> = names.iter().filter(|n| !builtin(&n.name)).collect(); + let mut rest: Vec<&ImportName> = names.iter().filter(|n| !in_prelude(d, &n.name, self.set.conformance)).collect(); if rest.is_empty() { return; } + // MO-6g: a name the import cannot give is a stand-in, `any` to TypeScript (the mistake is the checker's to say, once, + // at the import: TS2307, TS2614, TS2724 were said beside it); an import left with no name is not written + let gone = self.standins(d, &rest); + if !gone.is_empty() { + let mut at = sp.start as usize; + for n in rest.iter().filter(|n| gone.contains(&n.name)) { + let b = self.bind(&n.alias, sp, &mut at); + out.push(t.var(t.gen(), VarKind::Const, b, Some(self.gen_ty("any")), None, true)); + } + rest.retain(|n| !gone.contains(&n.name)); + if rest.is_empty() { + return; + } + } + if let Some(dp) = declared { + for n in &rest { + let x = self.set.declarations.get(dp).and_then(|ds| ds.iter().find(|y| matches!(y, JsDecl::Fn { name, .. } if *name == n.name))); + if let Some(x @ JsDecl::Fn { refs, shape, .. }) = x { + if refs.iter().any(|r| *r) || shape.has_ref() { + self.ref_fns.insert(n.alias.clone(), x.clone()); + } + } + } + } if resolved.is_none() && declared.is_none() { // a JS module with no declaration: `any` let key = self.mod_path(from) + ".ts"; @@ -559,31 +912,117 @@ impl Proj<'_> { } } let mut at = sp.start as usize; - let def = rest.iter().find(|n| n.name == "default").map(|n| self.name(&n.alias, sp, &mut at)); - let parts: Vec = rest + // MO-6e: a name the module also imports to use it (`import { A }` beside `export { A }`) is bound by that import + let plain: HashSet = if *reexport { + self.set.programs.get(self.path).map(|p| p.decls.iter().flat_map(|x| match x { Decl::Import { names, reexport: false, .. } => names.iter().map(|n| n.alias.clone()).collect::>(), _ => vec![] }).collect()).unwrap_or_default() + } else { + HashSet::new() + }; + let mine: Vec<&ImportName> = rest.iter().copied().filter(|n| !plain.contains(&n.alias)).collect(); + let def = mine.iter().find(|n| n.name == "default").map(|n| (n, self.name(&n.alias, sp, &mut at))); + // each part's places: its name, and its alias when it has one + let parts: Vec<(&ImportName, Place, Place)> = mine .iter() .filter(|n| n.name != "default") .map(|n| { if n.name == n.alias { - self.name(&n.name, sp, &mut at) + let p = self.name(&n.name, sp, &mut at); + (*n, p, p) } else { let a = self.name(&n.name, sp, &mut at); - a.t(" as ").c(self.name(&n.alias, sp, &mut at)) + let mut b = self.name(&n.alias, sp, &mut at); + // MO-11q: `Select$Root` is a member of `import * as Select`: a range onto the namespace's name + if let (None, Some((head, _))) = (b.copy, n.alias.split_once('$')) { + if let Some(h) = self.find(head, sp, sp.start as usize) { + b = Place::atom(Span { start: h as u32, end: (h + head.len()) as u32 }); + } + } + (*n, a, b) } }) .collect(); - let mut c = Code::of(ind).t("import "); - let has_parts = !parts.is_empty(); - if let Some(def) = def { - c = c.c(def).t(if has_parts { ", " } else { "" }); + // MO-13d: an import whose declaration is a printed signature is typed as the .rx module the signature stands for + // (TY-4c: `x.rx.d.ts`, beside it), so its specifier is that module's, and maps nowhere + // MO-6e: a package's entry, as TypeScript reads it + let (spec, spec_at) = match (resolved, crate::modules::is_rx(from)) { + (Some(r), false) => (crate::modules::relative_module(self.path, r), Place::GEN), + _ => { + let q = js_str(from); + let fa = self.find(&q[1..q.len() - 1], sp, at).map(|a| a - 1).filter(|a| self.src[*a..].starts_with(&q)); + (from.clone(), Place::copy(&q, fa, Of { node: sp, found: false })) + } + }; + if !mine.is_empty() { + let mut specs = vec![]; + if let Some((n, p)) = def { + specs.push(tx::Spec::Default(t.bind(&n.alias, p))); + } + for (n, a, b) in &parts { + specs.push(self.import_name(&n.name, &n.alias, *a, *b)); + } + out.push(self.import(specs, &spec, spec_at, false)); + } + if *reexport { + // MO-6e: a re-export's names again, each onto the leaf its import maps it to; one a plain import binds as well + // is written as it is + let mut from = at; + let specs: Vec<(tx::Name, tx::Name)> = rest + .iter() + .map(|n| { + let mapped = parts.iter().find(|(m, _, _)| m.alias == n.alias); + let (lp, ep) = match mapped { + Some((_, a, b)) if n.name != "default" => (again(*a), again(*b)), + // a name a plain import binds as well is mapped here, in the re-export's own text + None if plain.contains(&n.alias) && n.name == n.alias => { + let p = self.name(&n.name, sp, &mut from); + (p, p) + } + _ => (Place::GEN, Place::GEN), + }; + let local = t.name(&n.name, lp); + let exported = t.name(&n.alias, if n.name == n.alias { lp } else { ep }); + let exported = if n.name == n.alias { t.name(&n.alias, Place::GEN) } else { exported }; + let local = if n.name == n.alias { t.name(&n.name, lp) } else { local }; + (local, exported) + }) + .collect(); + out.push(tx::St::ExportFrom(specs, t.string(&spec, Place::GEN))); } - if has_parts { - c = c.t("{ ").c(Code::join(parts, ", ")).t(" }"); + } + /// MO-6g: the names of an import that it cannot give — from `""`, from an `.rx` module that is not there or does not + /// parse (an editor's load, CP-8e), or that the module (or a JS module's declaration) does not export. + fn standins(&self, d: &Decl, names: &[&ImportName]) -> HashSet { + let Decl::Import { from, resolved, declared, .. } = d else { return HashSet::new() }; + let all = || names.iter().map(|n| n.name.clone()).collect(); + if from.is_empty() { + return all(); } - let q = js_str(from); - let fa = self.find(&q[1..q.len() - 1], sp, at).map(|a| a - 1).filter(|a| self.src[*a..].starts_with(&q)); - c = c.t(" from ").at(&q, fa).t(";"); - self.w.emit(c, *line); + let given: HashSet = if let Some(r) = resolved.as_ref().filter(|_| crate::modules::is_rx(from)) { + if self.set.parse_errors.iter().any(|e| e.2.as_deref() == Some(r.as_str())) { + return all(); + } + if let Some(p) = self.set.programs.get(r) { + p.decls + .iter() + .flat_map(|x| match x { + Decl::Import { names, reexport: true, .. } => names.iter().map(|n| n.alias.clone()).collect::>(), + Decl::Component { is_default: true, name, .. } => vec!["default".to_string(), name.clone()], + _ if x.exported() => x.name().into_iter().map(String::from).collect(), + _ => vec![], + }) + .collect() + } else if let Some(sig) = self.set.signatures.get(r) { + sig.exports.keys().cloned().collect() + } else { + return all(); + } + } else if let Some(ds) = declared.as_ref().filter(|dp| !crate::parse::is_generated(dp) && !self.set.drafted.contains_key(*dp)).and_then(|dp| self.set.declarations.get(dp)) { + // (MO-8l: a name a generated draft has no row for is an undeclared import, `any` already — not a missing one) + names.iter().filter(|n| ds.iter().any(|y| y.name() == n.name || y.name().starts_with(&format!("{}.", n.name)))).map(|n| n.name.clone()).collect() + } else { + return HashSet::new(); + }; + names.iter().filter(|n| !given.contains(&n.name)).map(|n| n.name.clone()).collect() } /// A JS import's module, from the program's root (where the stubs are written). fn mod_path(&self, from: &str) -> String { @@ -639,96 +1078,166 @@ impl Proj<'_> { } // ---- imperative scope ---- - fn stmts(&mut self, ss: &[Stmt], ind: &str) { + fn stmts(&mut self, ss: &[Stmt]) -> Vec { + self.lets.push(HashSet::new()); + let out = self.stmts_in(ss); + self.lets.pop(); + out + } + fn stmts_in(&mut self, ss: &[Stmt]) -> Vec { + // TY-2a: the statements after one that awaits, in a block of their own (`shadows`) + let Some(k) = ss.iter().position(|s| has_await(std::slice::from_ref(s))).filter(|k| k + 1 < ss.len()) else { return self.stmts_plain(ss) }; + let mut out = self.stmts_plain(&ss[..=k]); + let sh = self.shadows(&ss[k + 1..]); + if sh.is_empty() { + out.extend(self.stmts(&ss[k + 1..])); + return out; + } + let mut inner = sh; + inner.extend(self.stmts(&ss[k + 1..])); + out.push(self.t.block(inner)); + out + } + fn stmts_plain(&mut self, ss: &[Stmt]) -> Vec { + let t = self.t; + let mut out = vec![]; for s in ss { let sp = s.span; let mut at = sp.start as usize; + let here = || t.key(Place::atom(sp)); match &s.k { StmtKind::Let { name, e, ty } => { - let nm = self.name(name, sp, &mut at); + let nm = self.bind(name, sp, &mut at); let a = self.ann(ty, sp, &mut at); let v = self.expr(e, true, None); - self.w.emit(Code::of(&format!("{ind}let ")).c(nm).c(a).t(" = ").c(v).t(";").from(sp), 0); + out.push(t.var(here(), VarKind::Let, nm, a, Some(v), false)); + if let Some(f) = self.lets.last_mut() { + f.insert(name.clone()); + } + } + // W-1c: a local written again + StmtKind::Write { target, e } if !target.is_ctx() && target.path.is_empty() && self.lets.iter().any(|f| f.contains(&target.name)) => { + let tg = self.target(target, sp, &mut at); + let v = self.expr(e, true, None); + out.push(t.expr_stmt(here(), t.assign(t.gen(), tg, v))); } StmtKind::Expr(e) => { let v = self.expr(e, true, None); - self.w.emit(Code::of(ind).c(v).t(";").from(sp), 0); + out.push(t.expr_stmt(here(), v)); } StmtKind::Return(e) => { - let v = match e { - Some(e) => Code::of(" ").c(self.expr(e, true, None)), - None => Code::new(), - }; - self.w.emit(Code::of(&format!("{ind}return")).c(v).t(";").from(sp), 0); + let v = e.as_ref().map(|e| self.expr(e, true, None)); + out.push(t.ret(here(), v)); } StmtKind::Throw(e) => { let v = self.expr(e, true, None); - self.w.emit(Code::of(&format!("{ind}throw ")).c(v).t(";").from(sp), 0); + out.push(tx::St::Throw(here(), v)); } StmtKind::Write { target, e } | StmtKind::Optimistic { target, e } => { - let t = self.target(target, sp, &mut at); + let tg = self.target(target, sp, &mut at); let v = self.expr(e, true, None); - self.w.emit(Code::of(&format!("{ind}__.set(")).c(t).t(")(").c(v).t(");").from(sp), 0); + let set = if !target.path.is_empty() { + t.call_helper("setAt", None, vec![tg]) + } else if !target.is_ctx() && self.aliased(&target.name) { + t.call_helper("set", Some(t.targs(vec![self.gen_ty(&format!("__w_{}", target.name))])), vec![tg]) + } else { + t.call_helper("set", None, vec![tg]) + }; + let c = t.call(t.gen(), set, None, vec![tx::Arg::Ex(v)]); + out.push(t.expr_stmt(here(), c)); } StmtKind::Refresh(n) | StmtKind::Affects(n) => { - let nm = self.name(n, sp, &mut at); - self.w.emit(Code::of(&format!("{ind}void ")).c(nm).t(";"), 0); + let p = self.name(n, sp, &mut at); + let k = t.gen(); + let v = t.unary(k, tx::Un::Void, t.id(n, p)); + out.push(t.expr_stmt(t.gen(), v)); } StmtKind::Action(body) => { - self.w.emit(Code::of(&format!("{ind}void (async () => {{")), 0); - self.stmts(body, &format!("{ind} ")); - self.w.emit(Code::of(&format!("{ind}}})();")), 0); + let ss = self.stmts(body); + let f = t.arrow_block(t.gen(), true, vec![], None, ss); + let c = t.call(t.gen(), f, None, vec![]); + let v = t.unary(t.gen(), tx::Un::Void, c); + out.push(t.expr_stmt(t.gen(), v)); } - StmtKind::Sif { c, t, f } => { + StmtKind::Sif { c, t: th, f } => { let v = self.expr(c, true, None); - self.w.emit(Code::of(&format!("{ind}if (")).c(v).t(") {"), 0); - self.stmts(t, &format!("{ind} ")); - self.w.emit(Code::of(&format!("{ind}}} else {{")), 0); - self.stmts(f, &format!("{ind} ")); - self.w.emit(Code::of(&format!("{ind}}}")), 0); - } - StmtKind::Try { body, catch_name, catch_classes, handler, fin } => { - self.w.emit(Code::of(&format!("{ind}try {{")), 0); - self.stmts(body, &format!("{ind} ")); - if let Some(h) = handler { - let bind = match catch_name { - Some(n) => format!(" const {n} = __e as {};", catch_classes.as_ref().map(|c| c.join(" | ")).unwrap_or("Error".into())), - None => String::new(), - }; - self.w.emit(Code::of(&format!("{ind}}} catch (__e) {{{bind}")), 0); - self.stmts(h, &format!("{ind} ")); - } - if let Some(f) = fin { - self.w.emit(Code::of(&format!("{ind}}} finally {{")), 0); - self.stmts(f, &format!("{ind} ")); - } - self.w.emit(Code::of(&format!("{ind}}}")), 0); + let a = self.stmts(th); + let b = self.stmts(f); + out.push(tx::St::If(v, a, b)); + } + StmtKind::For { name, e, body } => { + let nm = self.bind(name, sp, &mut at); + let v = self.expr(e, true, None); + let ss = self.stmts(body); + out.push(tx::St::ForOf(nm, v, ss)); + } + StmtKind::Try { body, catch_name, catch_classes, handler, fin, catch_at } => { + let b = self.stmts(body); + let h = handler.as_ref().map(|h| { + let mut hs = vec![]; + if let Some(n) = catch_name { + let mut from = *catch_at as usize; + let v = t.as_(t.gen(), t.id("__e", Place::GEN), self.classes(catch_classes, sp, &mut from)); + // the caught error's name where it is written (CP-8a, the parser's `catch_at`) + let at = (*catch_at as usize).checked_sub(0).filter(|&a| a != 0 && self.src.get(a..a + n.len()) == Some(n.as_str())); + hs.push(t.var(t.gen(), VarKind::Const, t.bind(n, Place::copy(n, at, Of { node: sp, found: false })), None, Some(v), false)); + } + hs.extend(self.stmts(h)); + (t.bind("__e", Place::GEN), hs) + }); + let f = fin.as_ref().map(|f| self.stmts(f)); + out.push(tx::St::Try(b, h, f)); } } } + out } - fn target(&mut self, t: &Target, within: Span, at: &mut usize) -> Code { - let nm = self.name(&t.name, within, at); - let mut s = if t.is_ctx() { Code::of("__.use(").c(nm).t(")") } else { nm }; - for p in &t.path { - s = match p { + fn target(&mut self, tg: &Target, within: Span, at: &mut usize) -> Ex { + let t = self.t; + let p = self.name(&tg.name, within, at); + let mut s = if tg.is_ctx() { t.call_helper("use", None, vec![t.id(&tg.name, p)]) } else { t.id(&tg.name, p) }; + for seg in &tg.path { + s = match seg { PathSeg::Name(n) => { - let m = self.name(n, within, at); - s.t(".").c(m) + let mut p = self.name(n, within, at); + if let Some(c) = p.copy.as_mut() { + // the dot is written before it + c.lead = 0; + } + t.member(t.gen(), s, t.name(n, p), false) + } + PathSeg::Expr(e) => { + let i = self.expr(e, true, None); + t.computed(t.gen(), s, i, false) } - PathSeg::Expr(e) => s.t("[").c(self.expr(e, true, None)).t("]"), }; } s } // ---- expressions: `imp` imperative scope (a real `await`); `me` the equation being defined (its own `pre`) ---- - fn expr(&mut self, e: &Expr, imp: bool, me: Option<&str>) -> Code { - self.expr_text(e, imp, me).from(e.span) + /// The expression, and a range onto its `.rx` span. + fn expr(&mut self, e: &Expr, imp: bool, me: Option<&str>) -> Ex { + let x = self.expr_text(e, imp, me); + if e.span.is_none() { + // a node the loader made has no span (CP-8a): its text is the compiler's, by design + self.t.set_design(x.key()); + } else { + self.t.set_atom(x.key(), e.span); + } + // 07 §2 (2026-11-29): `e as T`, TypeScript's — its type is written after the expression + if let Some(c) = &e.cast { + let mut from = e.span.end as usize; + let ty = self.ty(c, Span::new(e.span.end as usize, self.src.len()), &mut from); + return self.t.as_(self.t.gen(), x, ty); + } + x } - fn expr_text(&mut self, e: &Expr, imp: bool, me: Option<&str>) -> Code { + fn expr_text(&mut self, e: &Expr, imp: bool, me: Option<&str>) -> Ex { + let t = self.t; let sp = e.span; let src_at = |text: &str| -> Option { (!sp.is_none() && sp.text(self.src) == text).then_some(sp.start as usize) }; + let of = Of { node: sp, found: false }; macro_rules! go { ($x:expr) => { self.expr($x, imp, me) @@ -736,252 +1245,567 @@ impl Proj<'_> { } match &e.k { ExprKind::Lit(l) => { - let t = j(l); - let at = src_at(&t); - Code::new().at(&t, at) + let text = j(l); + let at = src_at(&text); + t.raw(&text, Place::copy(&text, at, of)) } ExprKind::Id(n) => { - if builtin(n) && !self.declared.contains(n) { + if language(n, self.declared.contains(n), self.set.conformance).is_some() { self.used.insert(n.clone()); } let at = src_at(n); - Code::new().at(n, at) + t.id(n, Place::copy(n, at, of)) } ExprKind::Pre { name, init } => { let mut from = sp.start as usize; if me == Some(name.as_str()) { match init { - Some(i) => Code::of("__.pre(").c(go!(i)).t(")"), - None => Code::of("__.pre()"), + Some(i) => { + let v = go!(i); + t.call_helper("pre", None, vec![v]) + } + None => t.call_helper("pre", Some(t.targs(vec![self.gen_ty("any")])), vec![]), } } else { - let nm = self.name(name, sp, &mut from); - let iv = init.as_ref().map(|i| go!(i)).unwrap_or_default(); - Code::of("__.pre(").c(iv).t(")") + let p = self.name(name, sp, &mut from); + let q = t.type_of(t.id_ref(name, p)); + let iv: Vec = init.as_ref().map(|i| go!(i)).into_iter().collect(); + t.call_helper("pre", Some(t.targs(vec![q])), iv) } } ExprKind::Peek(x) | ExprKind::Latest(x) => go!(x), - ExprKind::Pending(x) => Code::of("__.pending(").c(go!(x)).t(")"), + ExprKind::Pending(x) => { + let v = go!(x); + t.call_helper("pending", None, vec![v]) + } ExprKind::Await { e: x, init, stream } => { if imp { - return Code::of("(await ").c(go!(x)).t(")"); + let v = go!(x); + return t.await_(t.gen(), v); } - let v = Code::of(if *stream { "__.awaitS(" } else { "__.await_(" }).c(go!(x)).t(")"); + let v = go!(x); + let v = t.call_helper(if *stream { "awaitS" } else { "await_" }, None, vec![v]); match init { - Some(i) => Code::of("__.first(").c(v).t(", ").c(go!(i)).t(")"), + Some(i) => { + let iv = go!(i); + t.call_helper("first", None, vec![v, iv]) + } None => v, } } - ExprKind::If { c, t, f } => Code::of("(").c(go!(c)).t(" ? ").c(go!(t)).t(" : ").c(go!(f)).t(")"), - ExprKind::Throw(x) => Code::of("__.raise(").c(go!(x)).t(")"), + ExprKind::If { c, t: a, f } => { + let (c, a, f) = (go!(c), go!(a), go!(f)); + t.cond(t.gen(), c, a, f) + } + ExprKind::Throw(x) => { + let v = go!(x); + t.call_helper("raise", None, vec![v]) + } ExprKind::Catch { e: x, name, classes, alt } => { let v = go!(x); let a = go!(alt); - Code::of("__.caught(").c(v).t(&format!(", ({}: {}) => ", name.as_deref().unwrap_or("__e"), classes.as_ref().map(|c| c.join(" | ")).unwrap_or("Error".into()))).c(a).t(")") + // the caught error's name and its classes, found in the expression's own text + let mut from = sp.start as usize; + let np = match name { + Some(n) => self.name(n, sp, &mut from), + None => Place::GEN, + }; + let cls = self.classes(classes, sp, &mut from); + let p = t.param(t.bind(name.as_deref().unwrap_or("__e"), np), false, Some(cls)); + let f = t.arrow(t.gen(), false, vec![p], a); + t.call_helper("caught", None, vec![v, f]) } ExprKind::Tpl(parts) => { - let mut c = Code::of("`"); + let mut quasis = vec![]; + let mut xs = vec![]; + let mut cur = String::new(); for p in parts { match p { - TplPart::Str(s) => c = c.t(&escape_tpl(s)), - TplPart::Expr(x) => c = c.t("${").c(go!(x)).t("}"), + TplPart::Str(s) => cur.push_str(&escape_tpl(s)), + TplPart::Expr(x) => { + quasis.push(std::mem::take(&mut cur)); + xs.push(go!(x)); + } } } - c.t("`") + quasis.push(cur); + t.template(quasis, xs) } ExprKind::Member { o, p, opt } => { // `.p` with its dot, so that a position just after the dot (what is being typed) is mapped too let dot = format!(".{p}"); let at = (!sp.is_none() && sp.text(self.src).ends_with(dot.as_str())).then(|| sp.end as usize - dot.len()); - go!(o).t(if *opt { "?" } else { "" }).at(&dot, at) + let call = match &o.k { + ExprKind::Id(on) => matches!(self.ref_parts.get(on), Some(crate::parse::Shape::Fields(fs)) if fs.iter().any(|f| &f.0 == p && f.1 == crate::parse::Part::Ref)), + _ => false, + }; + let mut pp = Place::copy(&dot, at, of); + if let Some(c) = pp.copy.as_mut() { + c.lead = 1; + } + let ov = go!(o); + let m = t.chain(ov, |o| t.member(t.gen(), o, t.name(p, pp), *opt), *opt); + if call { + t.chain(m, |f| t.call(t.gen(), f, None, vec![]), false) // MO-10b + } else { + m + } + } + ExprKind::Index { o, i, opt } => { + let call = match (&o.k, &i.k) { + (ExprKind::Id(on), ExprKind::Lit(Lit::Num(v))) => matches!(self.ref_parts.get(on), Some(crate::parse::Shape::Items(items)) if *v >= 0.0 && v.fract() == 0.0 && items.get(*v as usize) == Some(&crate::parse::Part::Ref)), + _ => false, + }; + let ov = go!(o); + let iv = go!(i); + let m = t.chain(ov, |o| t.computed(t.gen(), o, iv, *opt), *opt); + if call { + t.chain(m, |f| t.call(t.gen(), f, None, vec![]), false) // MO-10b + } else { + m + } } - ExprKind::Index { o, i, opt } => go!(o).t(if *opt { "?.[" } else { "[" }).c(go!(i)).t("]"), - ExprKind::StyleMap { css, .. } => Code::of(&class_map(css)), - ExprKind::Call { f, args } => { + ExprKind::StyleMap { css, .. } => t.raw(&class_map(css), Place::GEN), + ExprKind::Call { f, args, make: true, .. } => { + // 10 SV-7a: `new Date(…)` let fc = go!(f); - let a = args.iter().map(|a| go!(a)).collect(); - fc.t("(").c(Code::join(a, ", ")).t(")") + let a: Vec = args.iter().map(|a| self.arg(a, imp, me)).collect(); + t.new_(t.gen(), fc, a) + } + ExprKind::Call { f, args, targs, .. } => { + // MO-10a: a `ref` argument is an accessor + let refs: Vec = match &f.k { + ExprKind::Id(g) => self.ref_fns.get(g).map(|d| if let JsDecl::Fn { refs, .. } = d { refs.clone() } else { vec![] }).unwrap_or_default(), + _ => vec![], + }; + let fc = go!(f); + let a: Vec = args + .iter() + .enumerate() + .map(|(i, a)| { + if refs.get(i).copied().unwrap_or(false) { + let v = go!(a); + tx::Arg::Ex(t.arrow(t.key(Place::atom(a.span)), false, vec![], v)) + } else { + self.arg(a, imp, me) + } + }) + .collect(); + // 07 §3: type arguments, as written + let ta = targs.as_ref().map(|ty| t.raw_targs(ty, Place::GEN)); + t.chain(fc, |f| t.call(t.gen(), f, ta, a), false) } ExprKind::Arr(items) => { - let a = items.iter().map(|a| go!(a)).collect(); - Code::of("[").c(Code::join(a, ", ")).t("]") + let xs = items + .iter() + .map(|a| match &a.k { + ExprKind::Spread(x) => { + let v = go!(x); + tx::Arg::Spread(t.key(Place::atom(a.span)), v) + } + _ => tx::Arg::Ex(go!(a)), + }) + .collect(); + t.array(t.gen(), xs) } ExprKind::Rec(fields) => { + // a key is written quoted: a range onto where it is written (its quotes too), in the record's own text + let mut from = sp.start as usize; let fs = fields .iter() .map(|f| match f { - Field::Spread(x) => Code::of("...").c(go!(x)), - Field::Kv { key, v } => Code::of(&js_str(key)).t(": ").c(go!(v)), + Field::Spread(x) => { + from = from.max(x.span.end as usize); + let v = go!(x); + t.spread_prop(v) + } + Field::Kv { key, v } => { + let at = self.find(key, sp, from).map(|a| { + let q = self.src[..a].chars().next_back().filter(|q| matches!(q, '"' | '\'') && self.src[a + key.len()..].starts_with(*q)); + q.map_or((a, key.len()), |_| (a - 1, key.len() + 2)) + }); + if let Some((a, n)) = at { + from = a + n; + } + from = from.max(v.span.end as usize); + let kp = at.map_or(Place::GEN, |(a, n)| Place::atom(Span { start: a as u32, end: (a + n) as u32 })); + let vv = go!(v); + t.prop(key, kp, vv) + } }) .collect(); - Code::of("({ ").c(Code::join(fs, ", ")).t(" })") + t.object(t.gen(), fs) } - ExprKind::Spread(x) => Code::of("...").c(go!(x)), + ExprKind::Spread(x) => go!(x), // (a spread is written where it stands: an array's item, a call's argument) ExprKind::Omit { e: x, keys } => { - let ks: String = keys.iter().map(|k| format!(", {}", js_str(k))).collect(); - Code::of("__.omit(").c(go!(x)).t(&ks).t(")") + let mut a = vec![go!(x)]; + a.extend(keys.iter().map(|k| t.raw(&js_str(k), Place::GEN))); + t.call_helper("omit", None, a) } - ExprKind::Fn { params, body, stmts } => { + ExprKind::Fn { params, body, stmts, ptypes } => { let mut from = sp.start as usize; - let ps = Code::join(params.iter().map(|p| self.name(p, sp, &mut from)).collect(), ", "); + let ps = self.params(params, ptypes, None, sp, &mut from); // 07 §3: a parameter's type let Some(ss) = stmts else { - return Code::of("((").c(ps).t(") => ").c(self.expr(body, imp, me)).t(")"); + let v = self.expr(body, imp, me); + return t.arrow(t.gen(), false, ps, v); }; - let inner = self.nested(|me| me.stmts(ss, " ")); - Code::of(if has_await(ss) { "(async (" } else { "((" }).c(ps).t(") => {\n").c(inner).t("\n})") + let was = std::mem::replace(&mut self.bound, bound_in(params, ss)); + let inner = self.stmts(ss); + self.bound = was; + t.arrow_block(t.gen(), has_await(ss), ps, None, inner) } ExprKind::ServerFn { params, ptypes, ret, body } => { let mut from = sp.start as usize; - let ps = self.params(params, ptypes, sp, &mut from); - let r = match ret { - Some(r) => Code::of(": Promise<").c(self.ty(r, sp, &mut from)).t(">"), - None => Code::new(), - }; - let inner = self.nested(|me| me.stmts(body, " ")); + let ps = self.params(params, ptypes, None, sp, &mut from); + let r = ret.as_ref().map(|r| { + let p = self.name(r, sp, &mut from); + t.raw_type(&format!("Promise<{r}>"), Place::GEN, &p.copy.map(|c| (8, c)).into_iter().collect::>()) + }); + let inner = self.stmts(body); + let f = t.arrow_block(t.gen(), true, ps, r, inner); // SF-1d: an async function, its wire checked (TY-5a) - Code::of("((__f) => (__.wire(__f, true), __f))(async (").c(ps).t(")").c(r).t(" => {\n").c(inner).t("\n})") + let w = t.call_helper("wire", None, vec![t.id("__f", Place::GEN), t.bool_(true)]); + let k = t.gen(); + let seq = t.seq(k, vec![w, t.id("__f", Place::GEN)]); + let wrap = t.arrow(t.gen(), false, vec![t.param(t.bind("__f", Place::GEN), false, None)], seq); + t.call(t.gen(), wrap, None, vec![tx::Arg::Ex(f)]) } ExprKind::Draft { seed, body } => { let s = go!(seed); - let inner = self.nested(|me| me.stmts(body, " ")); - Code::of("__.draft(").c(s).t(", (d) => {\n").c(inner).t("\n})") + let inner = self.stmts(body); + let f = t.arrow_block(t.gen(), false, vec![t.param(t.bind("d", Place::GEN), false, None)], None, inner); + t.call_helper("draft", None, vec![s, f]) } ExprKind::Use(n) => { let mut from = sp.start as usize + 3; - Code::of("__.use(").c(self.name(n, sp, &mut from)).t(")") + let p = self.name(n, sp, &mut from); + t.call_helper("use", None, vec![t.id(n, p)]) } ExprKind::Bin { op, l, r } => { + let (l, r) = (go!(l), go!(r)); + match op.as_str() { + "&&" => t.bin(t.gen(), tx::Op::And, l, r), + "||" => t.bin(t.gen(), tx::Op::Or, l, r), + "??" => t.bin(t.gen(), tx::Op::Coalesce, l, r), + "," => t.seq(t.gen(), vec![l, r]), + o => t.bin(t.gen(), tx::Op::Bin(crate::oxc::binary(match o { + "==" => "===", + "!=" => "!==", + o => o, + }).as_str()), l, r), + } + } + ExprKind::Un { op, e: x } => { + let v = go!(x); let o = match op.as_str() { - "==" => "===", - "!=" => "!==", - o => o, + "!" => tx::Un::Not, + "-" => tx::Un::Neg, + "+" => tx::Un::Plus, + "typeof" => tx::Un::Typeof, + "~" => tx::Un::BitNot, + "void" => tx::Un::Void, + "delete" => tx::Un::Delete, + o => unreachable!("unary {o}"), }; - Code::of("(").c(go!(l)).t(&format!(" {o} ")).c(go!(r)).t(")") + t.unary(t.gen(), o, v) } - ExprKind::Un { op, e: x } => Code::of("(").t(op).c(go!(x)).t(")"), } } - /// What `f` writes, as one piece of text (a closure's body). - fn nested(&mut self, f: impl FnOnce(&mut Self)) -> Code { - let saved = std::mem::replace(&mut self.w, W::new()); - f(self); - std::mem::replace(&mut self.w, saved).buf + /// A call's argument: a spread where it stands. + fn arg(&mut self, a: &Expr, imp: bool, me: Option<&str>) -> tx::Arg { + match &a.k { + ExprKind::Spread(x) => { + let v = self.expr(x, imp, me); + let k = self.t.key(Place::atom(a.span)); + self.t.spread(k, v) + } + _ => tx::Arg::Ex(self.expr(a, imp, me)), + } } // ---- views: JSX over Solid's JSX types ---- - fn markup(&mut self, ms: &[Markup], ind: &str) { + /// A list of markup as a fragment (`null` when there is none). + fn markup(&mut self, ms: &[Markup]) -> Ex { if ms.is_empty() { - self.w.emit(Code::of(&format!("{ind}null")), 0); - return; + return self.t.null(); } - self.w.emit(Code::of(&format!("{ind}<>")), ms[0].line.unwrap_or(0)); + let kids = self.children(ms.iter()); + self.t.fragment(kids) + } + /// Markup's children, each on a line of its own: white space with a line break, which JSX drops (a layout, for a + /// reader and for the line table, `line_table`). + fn children<'m>(&mut self, ms: impl Iterator) -> Vec { + self.depth += 1; + let mut out = vec![]; for m in ms { - self.child(m, &format!("{ind} ")); + for c in self.child(m) { + out.push(self.layout(self.depth)); + out.push(c); + } + } + self.depth -= 1; + if !out.is_empty() { + out.push(self.layout(self.depth)); } - self.w.emit(Code::of(&format!("{ind}")), ms[ms.len() - 1].line.unwrap_or(0)); + out + } + fn layout(&self, depth: usize) -> tx::Child { + let t = self.t; + tx::Child::Text(t.gen(), format!("\n{}", " ".repeat(depth + 1)).into()) } - fn region(&mut self, decls: &[Decl], view: &[Markup], ind: &str, line: usize) { + fn region(&mut self, decls: &[Decl], view: &[Markup]) -> Ex { if decls.is_empty() { - self.markup(view, ind); - return; + return self.markup(view); } - self.w.emit(Code::of(&format!("{ind}(() => {{")), line); - self.decls(decls, &format!("{ind} "), false); - self.w.emit(Code::of(&format!("{ind} return (")), line); - self.markup(view, &format!("{ind} ")); - self.w.emit(Code::of(&format!("{ind} );\n{ind}}})()")), line); + let t = self.t; + let mut ss = self.decls(decls, false); + let v = self.markup(view); + ss.push(t.ret(t.gen(), Some(v))); + self.scopes.pop(); + let f = t.arrow_block(t.gen(), false, vec![], None, ss); + t.call(t.gen(), f, None, vec![]) + } + /// `{x}` + fn contain(&self, x: Ex, at: Place) -> tx::Child { + tx::Child::Ex(self.t.key(at), x) } - fn child(&mut self, m: &Markup, ind: &str) { - let line = m.line.unwrap_or(0); + /// A render prop's function: `(params) => (region)`, its parameters found in `within`. + fn render_fn(&mut self, params: &[String], within: Span, decls: &[Decl], body: &[Markup]) -> Ex { + let t = self.t; + let mut from = within.start as usize; + let ps = params.iter().map(|q| t.param(self.bind(q, within, &mut from), false, None)).collect(); + let v = self.region(decls, body); + t.arrow(t.gen(), false, ps, v) + } + fn child(&mut self, m: &Markup) -> Vec { + let t = self.t; let sp = m.span; - let i2 = format!("{ind} "); match &m.kind { - MarkupKind::Text(s) => self.w.emit(Code::of(&format!("{ind}{{{}}}", js_str(s))), line), - MarkupKind::Style(_) => {} + MarkupKind::Text(s) => vec![self.contain(t.raw(&js_str(s), Place::GEN), Place::GEN)], + MarkupKind::Style(_) => vec![], MarkupKind::Read(e) => { let v = self.expr(e, false, None); - self.w.emit(Code::of(&format!("{ind}{{")).c(v).t("}").from(sp), line); + vec![self.contain(v, Place::atom(sp))] } MarkupKind::El { tag, attrs, children } => { if tag.is_empty() { - self.w.emit(Code::of(&format!("{ind}<>")), line); - for c in children { - self.child(c, &i2); + let kids = self.children(children.iter()); + return vec![self.frag_child(kids)]; + } + let made = self.element_of(m, tag, attrs, children); + // markup the loader made (a render prop it forwards) has no span (CP-8a): the compiler's, by design + if sp.is_none() { + for c in &made { + t.set_design(c.key()); } - self.w.emit(Code::of(&format!("{ind}")), line); - return; } - let tag_at = (!sp.is_none() && sp.text(self.src)[1..].starts_with(tag.as_str())).then_some(sp.start as usize + 1); - let mut a = Code::new(); + made + } + _ => self.child_other(m), + } + } + fn element_of(&mut self, m: &Markup, tag: &str, attrs: &[Attr], children: &[Markup]) -> Vec { + let t = self.t; + let sp = m.span; + { + { + let tag_at = (!sp.is_none() && sp.text(self.src)[1..].starts_with(tag)).then_some(sp.start as usize + 1); + let mut a: Vec = vec![]; for at in attrs { // 07 §4: a spread, as JSX's if at.name == "..." { - a = a.t(" {...").c(self.expr(&at.e, false, None)).t("}"); + let v = self.expr(&at.e, false, None); + a.push(tx::Attr::Spread(v)); continue; } let name_at = (!at.span.is_none() && at.span.text(self.src) == at.name).then_some(at.span.start as usize); - a = a.t(" ").at(&at.name, name_at); - if !matches!(at.e.k, ExprKind::Lit(Lit::Bool(true))) { - a = a.t("={").c(self.expr(&at.e, is_handler(&at.name), None)).t("}"); + // (an attribute the loader adds has no span, CP-8a: the compiler's, by design) + let np = if at.span.is_none() { Place::DESIGN } else { Place::copy(&at.name, name_at, Of { node: at.span, found: false }) }; + let name = self.attr_name(&at.name, np); + // MO-11t: a component given by name to a prop typed `View` is the component applied, which is what + // the library's type takes (an element) and what types its props (it is given none) + if let Some(n) = self.views.given(tag, &at.name, &at.e) { + let n_at = (!at.e.span.is_none() && at.e.span.text(self.src) == n).then_some(at.e.span.start as usize); + let el = self.element(n, Place::copy(n, n_at, Of { node: at.e.span, found: false }), vec![], None); + a.push(tx::Attr::Attr(name, Some(el))); + continue; } + let v = if matches!(at.e.k, ExprKind::Lit(Lit::Bool(true))) { + None + } else { + let x = self.expr(&at.e, is_handler(&at.name), None); + Some(x) + }; + a.push(tx::Attr::Attr(name, v)); } - let open = Code::of(&format!("{ind}<")).at(tag, tag_at).c(a); - if children.is_empty() { - self.w.emit(open.t(" />"), line); - return; + let tag_span = tag_at.map_or(Span::NONE, |at| Span { start: at as u32, end: (at + tag.len()) as u32 }); + // RG-4c: optional, or plain content is taken as well + if self.loose.contains(tag) { + let el = self.element("V$", Place::atom(tag_span), a, None); + let f = t.arrow(t.gen(), false, vec![t.param(t.bind("V$", Place::GEN), false, None)], el); + let shown = t.call_helper("view", None, vec![t.raw(tag, Place::copy(tag, tag_at, Of { node: sp, found: false }))]); + return vec![self.contain(t.call(t.gen(), f, None, vec![tx::Arg::Ex(shown)]), Place::GEN)]; } - self.w.emit(open.t(">"), line); - for c in children { - self.child(c, &i2); + // RG-4c: the view a context holds, shown with what its type says + if let Some(u) = crate::modules::used_in(tag) { + // (the tag stands where it was written: an argument it lacks is reported there) + let el = self.element("V$", Place::atom(tag_span), a, None); + let f = t.arrow(t.gen(), false, vec![t.param(t.bind("V$", Place::GEN), false, None)], el); + let held = t.call_helper("use", None, vec![t.raw(u, Place::copy(u, tag_at.map(|x| x + 4), Of { node: sp, found: false }))]); + return vec![self.contain(t.call(t.gen(), f, None, vec![tx::Arg::Ex(held)]), Place::GEN)]; } + let mut tag_p = Place::copy(tag, tag_at, Of { node: sp, found: false }); let close_at = self.src.get(..sp.end as usize).filter(|s| !sp.is_none() && s.ends_with(&format!(""))).map(|_| sp.end as usize - tag.len() - 1); - self.w.emit(Code::of(&format!("{ind}"), line); + let mut close_p = Place::copy(tag, close_at, Of { node: sp, found: false }); + // MO-11q: a namespace's member, `Select.Root` in the `.rx`, is `Select$Root` after the loader — not the same + // text, so a range onto the member as written (an error on the tag, a prop it lacks, is placed there) + if tag_at.is_none() && tag.contains('$') && !sp.is_none() { + let dotted = tag.replace('$', "."); + let text = sp.text(self.src); + if text[1..].starts_with(dotted.as_str()) { + tag_p = Place::atom(Span { start: sp.start + 1, end: sp.start + 1 + dotted.len() as u32 }); + } + if close_at.is_none() && text.ends_with(&format!("")) { + let at = sp.end - dotted.len() as u32 - 1; + close_p = Place::atom(Span { start: at, end: at + dotted.len() as u32 }); + } + } + // MO-11k: named render props are attributes + let named: Vec<&Markup> = children.iter().filter(|c| matches!(&c.kind, MarkupKind::Mview { prop: Some(_), .. })).collect(); + for v in &named { + let MarkupKind::Mview { prop: Some(p), params, decls, body } = &v.kind else { continue }; + // the prop's name where the render prop writes it + let pp = self.name(p, v.span, &mut (v.span.start as usize)); + let f = self.render_fn(params, v.span, decls, body); + a.push(tx::Attr::Attr(self.attr_name(p, pp), Some(f))); + } + let kids: Vec<&Markup> = children.iter().filter(|c| !matches!(&c.kind, MarkupKind::Mview { prop: Some(_), .. })).collect(); + if kids.is_empty() { + return vec![self.element_child(tag, tag_p, a, None)]; + } + let cs = self.children(kids.into_iter()); + vec![self.element_child(tag, tag_p, a, Some((cs, close_p)))] } - MarkupKind::Mif { c, t, t_decls, f, f_decls } => { + } + } + fn child_other(&mut self, m: &Markup) -> Vec { + let t = self.t; + let sp = m.span; + match &m.kind { + MarkupKind::Text(_) | MarkupKind::Style(_) | MarkupKind::Read(_) | MarkupKind::El { .. } => unreachable!(), + MarkupKind::Mif { c, t: th, t_decls, f, f_decls } => { let v = self.expr(c, false, None); - self.w.emit(Code::of(&format!("{ind}{{")).c(v).t(" ? ("), line); - self.region(t_decls, t, &i2, line); - self.w.emit(Code::of(&format!("{ind}) : (")), line); - self.region(f_decls, f, &i2, line); - self.w.emit(Code::of(&format!("{ind})}}")), line); + let a = self.region(t_decls, th); + let b = self.region(f_decls, f); + vec![self.contain(t.cond(t.gen(), v, a, b), Place::GEN)] + } + MarkupKind::Mview { params, decls, body, .. } => { + // MO-11k: the render prop, as the function the component's types expect + let f = self.render_fn(params, sp, decls, body); + vec![self.contain(f, Place::GEN)] } - MarkupKind::Mfor { name, xs, decls, body } => { + MarkupKind::Mfor { name, index, xs, decls, body } => { let mut from = sp.start as usize; - let nm = self.name(name, sp, &mut from); + let nm = self.bind(name, sp, &mut from); + let mut ps = vec![t.param(nm, false, None)]; + if let Some(i) = index { + let ix = self.bind(i, sp, &mut from); + ps.push(t.param(ix, false, None)); + } let v = self.expr(xs, false, None); - self.w.emit(Code::of(&format!("{ind}{{__.each(")).c(v).t(", (").c(nm).t(") => ("), line); - self.region(decls, body, &i2, line); - self.w.emit(Code::of(&format!("{ind}))}}")), line); + let r = self.region(decls, body); + let f = t.arrow(t.gen(), false, ps, r); + vec![self.contain(t.call_helper("each", None, vec![v, f]), Place::GEN)] } MarkupKind::Loading { on, fallback, decls, body } => { + let mut out = vec![]; if let Some(on) = on { let v = self.expr(on, false, None); - self.w.emit(Code::of(&format!("{ind}{{void ")).c(v).t("}"), line); + out.push(self.contain(t.unary(t.gen(), tx::Un::Void, v), Place::GEN)); } - self.w.emit(Code::of(&format!("{ind}{{(")), line); - self.markup(fallback, &i2); - self.w.emit(Code::of(&format!("{ind})}}{{(")), line); - self.region(decls, body, &i2, line); - self.w.emit(Code::of(&format!("{ind})}}")), line); + let fb = self.markup(fallback); + out.push(self.contain(fb, Place::GEN)); + let r = self.region(decls, body); + out.push(self.contain(r, Place::GEN)); + out } MarkupKind::Portal { to, decls, body } => { + let mut out = vec![]; if let Some(to) = to { let v = self.expr(to, false, None); - self.w.emit(Code::of(&format!("{ind}{{void ")).c(v).t("}"), line); + out.push(self.contain(t.unary(t.gen(), tx::Un::Void, v), Place::GEN)); } - self.w.emit(Code::of(&format!("{ind}{{(")), line); - self.region(decls, body, &i2, line); - self.w.emit(Code::of(&format!("{ind})}}")), line); + let r = self.region(decls, body); + out.push(self.contain(r, Place::GEN)); + out } MarkupKind::Errored { fallback, decls, body, err_name, classes } => { - let head = format!("{ind}{{(({}: {}) => (", err_name.as_deref().unwrap_or("__err"), classes.as_ref().map(|c| c.join(" | ")).unwrap_or("Error".into())); - self.w.emit(Code::of(&head), line); - self.markup(fallback, &i2); - self.w.emit(Code::of(&format!("{ind}))(null!)}}{{(")), line); - self.region(decls, body, &i2, line); - self.w.emit(Code::of(&format!("{ind})}}")), line); + // the error's name and its classes where the `errored` writes them + let mut from = sp.start as usize; + let np = match err_name { + Some(n) => self.name(n, sp, &mut from), + None => Place::GEN, + }; + let cls = self.classes(classes, sp, &mut from); + let p = t.param(t.bind(err_name.as_deref().unwrap_or("__err"), np), false, Some(cls)); + let fb = self.markup(fallback); + let f = t.arrow(t.gen(), false, vec![p], fb); + let k = t.gen(); + let none = t.non_null(k, t.null()); + let c = t.call(t.gen(), f, None, vec![tx::Arg::Ex(none)]); + let r = self.region(decls, body); + vec![self.contain(c, Place::GEN), self.contain(r, Place::GEN)] + } + } + } + fn frag_child(&self, kids: Vec) -> tx::Child { + let t = self.t; + let k = t.gen(); + tx::Child::Frag(k, kids) + } + /// An attribute's name: a word, or `ns:name`. + fn attr_name(&self, name: &str, p: Place) -> tx::AttrName { + let t = self.t; + match name.split_once(':') { + Some((ns, n)) => { + let a = t.name(ns, p); + tx::AttrName::Ns(a, t.name(n, Place::GEN)) + } + None => tx::AttrName::Id(t.name(name, p)), + } + } + /// An element's name as oxc's parser reads it: lowercase or hyphenated a `JSXIdentifier`, else a reference, and a + /// member (`Kit.Part`) a member expression; its first piece is `p`'s. + fn tag_name(&self, tag: &str, p: Place) -> tx::Tag { + let t = self.t; + let parts: Vec<&str> = tag.split('.').collect(); + if parts.len() == 1 { + if tag.as_bytes()[0].is_ascii_lowercase() || tag.contains('-') { + return tx::Tag::Ident(t.name(tag, p)); } + return tx::Tag::Ref(t.name(tag, p)); } + // (the first piece maps the whole member: the dots are the same text on both sides) + let mut c = p.copy; + if let Some(c) = c.as_mut() { + c.len = tag.len() as u32; + } + let first = t.name(parts[0], Place { copy: c, ..p }); + tx::Tag::Member(first, parts[1..].iter().map(|q| t.name(q, Place::GEN)).collect()) + } + /// ``, or `kids` (the closing tag `close`'s). + fn element(&self, tag: &str, p: Place, attrs: Vec, kids: Option<(Vec, Place)>) -> Ex { + Ex::El(Box::new(self.element_parts(tag, p, attrs, kids))) + } + fn element_child(&self, tag: &str, p: Place, attrs: Vec, kids: Option<(Vec, Place)>) -> tx::Child { + tx::Child::El(Box::new(self.element_parts(tag, p, attrs, kids))) + } + fn element_parts(&self, tag: &str, p: Place, attrs: Vec, kids: Option<(Vec, Place)>) -> tx::El { + let t = self.t; + let name = self.tag_name(tag, p); + let kids = kids.map(|(cs, cp)| (cs, self.tag_name(tag, cp))); + // (the element's key after its tags', as it was built) + tx::El { k: t.gen(), tag: name, attrs, kids } } } @@ -1016,3 +1840,61 @@ fn class_map(css: &str) -> String { let fields: Vec = r.class_map.into_iter().map(|c| format!("{}: \"\" as string", js_str(&c.class_name))).collect(); format!("({{ {} }} as const)", fields.join(", ")) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::modules::load_modules; + use std::collections::HashMap; + + #[test] + fn an_entry_default_is_the_apps_main_and_its_component_keeps_its_mappings() { + let files: HashMap<&str, &str> = [ + ("app/main.rx", "import { Badge } from \"./badge.rx\"\nexport default component App() {\n source n := 0\n \n}\n"), + ("app/badge.rx", "export component Badge(props: { n: number }) {\n {props.n}\n}\n"), + ] + .into_iter() + .collect(); + let set = load_modules("app/main.rx", &|p| files.get(p).map(|s| s.to_string())).expect("loads"); + let out = project_modules(&set); + let main = out.iter().find(|p| p.rx == "app/main.rx").unwrap(); + assert!(main.code.ends_with("\ndeclare const __main: __.Main;\nexport default __main;\n"), "{}", main.code); + assert_eq!(main.code.matches("export default").count(), 1); + assert_eq!(main.lines.len(), main.code.lines().count()); + let at = main.code.find("export function App(").unwrap() + "export function ".len(); + let src = files["app/main.rx"].find("App").unwrap(); + assert!(main.mappings.iter().any(|m| m.gen as usize == at && m.src as usize == src && m.len == 3)); + let dep = out.iter().find(|p| p.rx == "app/badge.rx").unwrap(); + assert!(!dep.code.contains("export default"), "{}", dep.code); + assert!(PRELUDE.contains("export type Main = (app: object) => () => View;")); + } + + /// CP-8: a parameter is mapped to its declaration's own text, not to a read of it in the body (which is the same text, + /// and which `unverified` cannot tell from it); `names_misplaced` finds a mapping moved there, or found twice. + #[test] + fn a_name_maps_to_its_own_occurrence_and_the_check_sees_another() { + let src = "fn step(n: number, by: number): number => n + by\nexport default component App() {\n source n := 0\n action add(k: number) { n := step(n, k) }\n \n}\n"; + let files: HashMap<&str, &str> = [("main.rx", src)].into_iter().collect(); + let set = load_modules("main.rx", &|p| files.get(p).map(|s| s.to_string())).expect("loads"); + let prog = &set.programs["main.rx"]; + let mut main = project_modules(&set).into_iter().find(|p| p.rx == "main.rx").unwrap(); + assert!(unverified(&main, src).is_empty()); + let c = names_misplaced(&main, prog, src); + assert!(c.misplaced.is_empty(), "{:?}", c.misplaced); + assert!(c.names >= 6 && c.ambiguous >= 2, "{} {}", c.names, c.ambiguous); + // the parameter `n` of `step`: at its declaration, the first `n` of the line + let i = main.mappings.iter().position(|m| m.src as usize == src.find("n:").unwrap() && m.len == 1).expect("the parameter is mapped"); + assert!(main.of[i].found); + // moved onto the body's `n` (`n + by`): the same text, so it holds, but it is inside the body's expression + main.mappings[i].src = src.find("n + by").unwrap() as u32; + assert!(unverified(&main, src).is_empty()); + assert!(!names_misplaced(&main, prog, src).misplaced.is_empty()); // (and its own leaf is left unmapped) + // the return type `number` mapped onto the first parameter's: one place of the head found twice + main.mappings[i].src = src.find("n:").unwrap() as u32; + let ret = src.find("): number").unwrap() + 3; + let j = main.mappings.iter().position(|m| m.src as usize == ret).expect("the return type is mapped"); + main.mappings[j].src = src.find("number").unwrap() as u32; + assert!(unverified(&main, src).is_empty()); + assert!(!names_misplaced(&main, prog, src).misplaced.is_empty()); + } +} diff --git a/compiler/src/scope.rs b/compiler/src/scope.rs new file mode 100644 index 000000000..cb4591fc6 --- /dev/null +++ b/compiler/src/scope.rs @@ -0,0 +1,545 @@ +//! The scoped visitor (`ref/src/scope.ts`): every expression of a tree with the names bound around it, the one way down +//! a tree with its scope (rsvelte P5, oxc's `Visit`); and the tree changed in place where the scope does not matter. The +//! walks built on them: a namespace import's members named, a fn that only names values, the names a body calls. + +use crate::ast::*; + +// ---------------------------------------------------------------- the scoped visitor +/// The names bound around a node, innermost last, each with where the declaration or the `let` that binds it starts (its +/// span's start, the binding's identity: `ref/src/scope.ts` names it by its line; -1 for a parameter, props, a loop's variable, a caught error, a draft's `d`). A block's declarations are bound in all of +/// it (a component may be applied above its declaration), a statement list's `let`s in all of the list; an import and a +/// provision bind nothing here: what is bound stands between a mention and the module's imports. `ref/src/scope.ts`. +#[derive(Default)] +pub struct Scope<'a> { + bound: Vec<(&'a str, i64)>, +} +impl<'a> Scope<'a> { + /// The innermost binding of `name`: where it starts, -1 for one with no place of its own. + pub fn at_of(&self, name: &str) -> Option { + self.bound.iter().rev().find(|b| b.0 == name).map(|b| b.1) + } + pub fn binds(&self, name: &str) -> bool { + self.bound.iter().any(|b| b.0 == name) + } +} +/// What a pass asks of every expression of a tree, with the names bound around it (rsvelte's and oxc's `Visit`). The walk +/// (`walk_block`, `walk_stmts`) is the one way down a tree with its scope. +pub trait Visit<'a> { + /// An expression, before the expressions inside it. + fn expr(&mut self, e: &'a Expr, scope: &Scope<'a>); +} +fn param(n: &str) -> (&str, i64) { + (n.trim_start_matches("..."), -1) +} +/// A tree walked with its scope (`Scope`), handing each expression to `v`. +pub struct Walk<'a, 'v, V: Visit<'a>> { + pub v: &'v mut V, + pub scope: Scope<'a>, +} +impl<'a, 'v, V: Visit<'a>> Walk<'a, 'v, V> { + pub fn new(v: &'v mut V) -> Self { + Walk { v, scope: Scope::default() } + } + fn with(&mut self, more: impl IntoIterator, go: impl FnOnce(&mut Self)) { + let n = self.scope.bound.len(); + self.scope.bound.extend(more); + go(self); + self.scope.bound.truncate(n); + } + fn lets(ss: &'a [Stmt]) -> impl Iterator { + ss.iter().filter_map(|s| if let StmtKind::Let { name, .. } = &s.k { Some((name.as_str(), s.span.start as i64)) } else { None }) + } + /// A block, after the names `more` (parameters, props): its declarations, then `rest`, each with every declaration of + /// the block bound. + pub fn block(&mut self, more: impl IntoIterator, ds: &'a [Decl], rest: impl FnOnce(&mut Self)) { + let declared = ds.iter().filter(|d| !matches!(d, Decl::Import { .. } | Decl::Provide { .. })).filter_map(|d| Some((d.name()?, d.span().start as i64))); + let more: Vec<(&'a str, i64)> = more.into_iter().chain(declared).collect(); + self.with(more, |w| { + w.decls(ds); + rest(w); + }); + } + /// A statement list, after the names `more` (parameters), with its `let`s bound in all of it. + pub fn stmts(&mut self, more: impl IntoIterator, ss: &'a [Stmt]) { + let more: Vec<(&'a str, i64)> = more.into_iter().chain(Self::lets(ss)).collect(); + self.with(more, |w| ss.iter().for_each(|s| w.stmt(s))); + } + fn opt(&mut self, e: &'a Option>) { + if let Some(e) = e { + self.expr(e); + } + } + pub fn expr(&mut self, e: &'a Expr) { + self.v.expr(e, &self.scope); + match &e.k { + ExprKind::Lit(_) | ExprKind::Id(_) | ExprKind::Use(_) | ExprKind::StyleMap { .. } => {} + ExprKind::Bin { l, r, .. } => { + self.expr(l); + self.expr(r); + } + ExprKind::Un { e, .. } | ExprKind::Peek(e) | ExprKind::Latest(e) | ExprKind::Pending(e) | ExprKind::Spread(e) | ExprKind::Omit { e, .. } | ExprKind::Throw(e) | ExprKind::Member { o: e, .. } => self.expr(e), + ExprKind::Pre { init, .. } => self.opt(init), + ExprKind::Await { e, init, .. } => { + self.expr(e); + self.opt(init); + } + ExprKind::If { c, t, f } => { + self.expr(c); + self.expr(t); + self.expr(f); + } + ExprKind::Tpl(parts) => parts.iter().for_each(|p| { + if let TplPart::Expr(e) = p { + self.expr(e); + } + }), + ExprKind::Index { o, i, .. } => { + self.expr(o); + self.expr(i); + } + ExprKind::Call { f, args, .. } => { + self.expr(f); + args.iter().for_each(|a| self.expr(a)); + } + ExprKind::Arr(items) => items.iter().for_each(|x| self.expr(x)), + ExprKind::Rec(fields) => fields.iter().for_each(|x| match x { + Field::Kv { v, .. } => self.expr(v), + Field::Spread(e) => self.expr(e), + }), + ExprKind::Fn { params, body, stmts, .. } => self.with(params.iter().map(|p| param(p)), |w| { + w.expr(body); + if let Some(ss) = stmts { + w.stmts([], ss); + } + }), + ExprKind::Draft { seed, body } => { + self.expr(seed); + self.stmts([("d", -1)], body); + } + ExprKind::Catch { e, name, alt, .. } => { + self.expr(e); + self.with(name.iter().map(|n| param(n)), |w| w.expr(alt)); + } + ExprKind::ServerFn { params, body, .. } => self.stmts(params.iter().map(|p| param(p)), body), + } + } + fn stmt(&mut self, s: &'a Stmt) { + match &s.k { + StmtKind::Write { target, e } | StmtKind::Optimistic { target, e } => { + for p in &target.path { + if let PathSeg::Expr(x) = p { + self.expr(x); + } + } + self.expr(e); + } + StmtKind::Let { e, .. } | StmtKind::Expr(e) | StmtKind::Throw(e) => self.expr(e), + StmtKind::Refresh(_) | StmtKind::Affects(_) => {} + StmtKind::Action(body) => self.stmts([], body), + StmtKind::Sif { c, t, f } => { + self.expr(c); + self.stmts([], t); + self.stmts([], f); + } + StmtKind::For { name, e, body } => { + self.expr(e); + self.stmts([param(name)], body); + } + StmtKind::Return(e) => { + if let Some(e) = e { + self.expr(e); + } + } + StmtKind::Try { body, catch_name, handler, fin, .. } => { + self.stmts([], body); + if let Some(h) = handler { + self.stmts(catch_name.iter().map(|n| param(n)), h); + } + if let Some(h) = fin { + self.stmts([], h); + } + } + } + } + pub fn decls(&mut self, ds: &'a [Decl]) { + for d in ds { + match d { + Decl::Source { init: e, .. } | Decl::Eq { e, .. } | Decl::Provide { e, .. } => self.expr(e), + Decl::Import { .. } | Decl::TypeDecl { .. } => {} + Decl::Error { params, msg, .. } => { + if let Some(m) = msg { + self.with(params.iter().map(|p| param(p)), |w| w.expr(m)); + } + } + Decl::Effect { inputs, body, .. } => { + inputs.iter().for_each(|i| self.expr(i)); + self.stmts([], body); + } + Decl::Fn { params, decls, tail, .. } => self.block(params.iter().map(|p| param(&p.name)), decls, |w| w.expr(tail)), + Decl::Component { props, decls, view, .. } => self.block([param(props)], decls, |w| w.markups(view)), + Decl::Action { params, body, .. } | Decl::Server { params, body, .. } => self.stmts(params.iter().map(|p| param(p)), body), + Decl::Context { dflt, .. } => { + if let Some(e) = dflt { + self.expr(e); + } + } + } + } + } + pub fn markups(&mut self, ms: &'a [Markup]) { + for m in ms { + match &m.kind { + MarkupKind::El { attrs, children, .. } => { + attrs.iter().for_each(|a| self.expr(&a.e)); + self.markups(children); + } + MarkupKind::Read(e) => self.expr(e), + MarkupKind::Text(_) | MarkupKind::Style(_) => {} + MarkupKind::Mif { c, t, t_decls, f, f_decls } => { + self.expr(c); + self.block([], t_decls, |w| w.markups(t)); + self.block([], f_decls, |w| w.markups(f)); + } + MarkupKind::Mfor { name, index, xs, decls, body } => { + self.expr(xs); + self.block(std::iter::once(param(name)).chain(index.iter().map(|i| param(i))), decls, |w| w.markups(body)); + } + MarkupKind::Mview { params, decls, body, .. } => self.block(params.iter().map(|p| param(p)), decls, |w| w.markups(body)), + MarkupKind::Loading { on, fallback, decls, body } => { + if let Some(e) = on { + self.expr(e); + } + self.markups(fallback); + self.block([], decls, |w| w.markups(body)); + } + MarkupKind::Errored { fallback, decls, body, err_name, .. } => { + self.with(err_name.iter().map(|n| param(n)), |w| w.markups(fallback)); + self.block([], decls, |w| w.markups(body)); + } + MarkupKind::Portal { to, decls, body } => { + if let Some(e) = to { + self.expr(e); + } + self.block([], decls, |w| w.markups(body)); + } + } + } + } +} +/// Visits every expression of a module's tree with its scope. +pub fn visit<'a>(decls: &'a [Decl], view: &'a [Markup], v: &mut impl Visit<'a>) { + Walk::new(v).block([], decls, |w| w.markups(view)); +} +impl<'a, F: FnMut(&'a Expr, &Scope<'a>)> Visit<'a> for F { + fn expr(&mut self, e: &'a Expr, scope: &Scope<'a>) { + self(e, scope) + } +} + +// ---------------------------------------------------------------- the tree changed in place +/// What a pass changes in every node of a tree that holds it, where the scope does not matter: an expression (before +/// those inside it), a fn's declaration (after its body), a type's text and a tag (`tag`). +pub trait VisitMut { + fn expr(&mut self, _e: &mut Expr) {} + fn fn_decl(&mut self, _d: &mut Decl) {} + fn text(&mut self, _t: &mut String, _tag: bool) {} +} +/// Changes every node of a module's tree, in the order of the text. +pub fn visit_mut(p: &mut Program, v: &mut impl VisitMut) { + WalkMut(v).decls(&mut p.decls); + WalkMut(v).markups(&mut p.view); +} +struct WalkMut<'v, V: VisitMut>(&'v mut V); +impl WalkMut<'_, V> { + fn ty<'t>(&mut self, ts: impl IntoIterator) { + ts.into_iter().for_each(|t| self.0.text(t, false)); + } + fn opt(&mut self, e: &mut Option>) { + if let Some(e) = e { + self.expr(e); + } + } + fn expr(&mut self, e: &mut Expr) { + self.0.expr(e); + match &mut e.k { + ExprKind::Lit(_) | ExprKind::Id(_) | ExprKind::Use(_) | ExprKind::StyleMap { .. } => {} + ExprKind::Bin { l, r, .. } => { + self.expr(l); + self.expr(r); + } + ExprKind::Un { e, .. } | ExprKind::Peek(e) | ExprKind::Latest(e) | ExprKind::Pending(e) | ExprKind::Spread(e) | ExprKind::Omit { e, .. } | ExprKind::Throw(e) | ExprKind::Member { o: e, .. } => self.expr(e), + ExprKind::Pre { init, .. } => self.opt(init), + ExprKind::Await { e, init, .. } => { + self.expr(e); + self.opt(init); + } + ExprKind::If { c, t, f } => { + self.expr(c); + self.expr(t); + self.expr(f); + } + ExprKind::Tpl(parts) => parts.iter_mut().for_each(|p| { + if let TplPart::Expr(e) = p { + self.expr(e); + } + }), + ExprKind::Index { o, i, .. } => { + self.expr(o); + self.expr(i); + } + ExprKind::Call { f, args, .. } => { + self.expr(f); + args.iter_mut().for_each(|a| self.expr(a)); + } + ExprKind::Arr(items) => items.iter_mut().for_each(|x| self.expr(x)), + ExprKind::Rec(fields) => fields.iter_mut().for_each(|x| match x { + Field::Kv { v, .. } => self.expr(v), + Field::Spread(e) => self.expr(e), + }), + ExprKind::Fn { body, stmts, .. } => { + self.expr(body); + if let Some(ss) = stmts { + self.stmts(ss); + } + } + ExprKind::Draft { seed, body } => { + self.expr(seed); + self.stmts(body); + } + ExprKind::Catch { e, alt, .. } => { + self.expr(e); + self.expr(alt); + } + ExprKind::ServerFn { body, .. } => self.stmts(body), + } + } + fn stmts(&mut self, ss: &mut [Stmt]) { + for s in ss { + match &mut s.k { + StmtKind::Write { target, e } | StmtKind::Optimistic { target, e } => { + for p in &mut target.path { + if let PathSeg::Expr(x) = p { + self.expr(x); + } + } + self.expr(e); + } + StmtKind::Let { e, ty, .. } => { + self.ty(ty.iter_mut()); + self.expr(e) + } + StmtKind::Expr(e) | StmtKind::Throw(e) => self.expr(e), + StmtKind::Refresh(_) | StmtKind::Affects(_) => {} + StmtKind::Action(body) => self.stmts(body), + StmtKind::Sif { c, t, f } => { + self.expr(c); + self.stmts(t); + self.stmts(f); + } + StmtKind::For { e, body, .. } => { + self.expr(e); + self.stmts(body); + } + StmtKind::Return(e) => { + if let Some(e) = e { + self.expr(e); + } + } + StmtKind::Try { body, handler, fin, .. } => { + self.stmts(body); + if let Some(h) = handler { + self.stmts(h); + } + if let Some(h) = fin { + self.stmts(h); + } + } + } + } + } + fn decls(&mut self, ds: &mut [Decl]) { + for d in ds { + match d { + Decl::Source { ty, .. } | Decl::Eq { ty, .. } | Decl::Context { ty, .. } => self.ty(ty.iter_mut()), + Decl::TypeDecl { text, .. } => self.ty([text]), + Decl::Error { ptypes, .. } => self.ty(ptypes.iter_mut().flatten()), + Decl::Action { ptypes, ret, .. } => self.ty(ptypes.iter_mut().flatten().chain(ret.iter_mut())), + Decl::Server { ptypes, ret, .. } => self.ty(ptypes.iter_mut().flatten().chain(ret.iter_mut())), + Decl::Fn { params, ret, tparams, .. } => self.ty(params.iter_mut().filter_map(|p| p.ty.as_mut()).chain(ret.iter_mut()).chain(tparams.iter_mut())), + Decl::Component { props_type, tparams, .. } => self.ty(props_type.iter_mut().chain(tparams.iter_mut())), + Decl::Import { .. } | Decl::Effect { .. } | Decl::Provide { .. } => {} + } + match d { + Decl::Source { init: e, .. } | Decl::Eq { e, .. } | Decl::Provide { e, .. } => self.expr(e), + Decl::Import { .. } | Decl::TypeDecl { .. } => {} + Decl::Error { msg, .. } => { + if let Some(m) = msg { + self.expr(m); + } + } + Decl::Effect { inputs, body, .. } => { + inputs.iter_mut().for_each(|i| self.expr(i)); + self.stmts(body); + } + Decl::Fn { decls, tail, .. } => { + self.decls(decls); + self.expr(tail); + self.0.fn_decl(d); + } + Decl::Component { decls, view, .. } => { + self.decls(decls); + self.markups(view); + } + Decl::Action { body, .. } | Decl::Server { body, .. } => self.stmts(body), + Decl::Context { dflt, .. } => { + if let Some(e) = dflt { + self.expr(e); + } + } + } + } + } + fn markups(&mut self, ms: &mut [Markup]) { + for m in ms { + match &mut m.kind { + MarkupKind::El { tag, attrs, children } => { + self.0.text(tag, true); + attrs.iter_mut().for_each(|a| self.expr(&mut a.e)); + self.markups(children); + } + MarkupKind::Read(e) => self.expr(e), + MarkupKind::Text(_) | MarkupKind::Style(_) => {} + MarkupKind::Mif { c, t, t_decls, f, f_decls } => { + self.expr(c); + self.decls(t_decls); + self.markups(t); + self.decls(f_decls); + self.markups(f); + } + MarkupKind::Mfor { xs, decls, body, .. } => { + self.expr(xs); + self.decls(decls); + self.markups(body); + } + MarkupKind::Mview { decls, body, .. } => { + self.decls(decls); + self.markups(body); + } + MarkupKind::Loading { on, fallback, decls, body } => { + if let Some(e) = on { + self.expr(e); + } + self.markups(fallback); + self.decls(decls); + self.markups(body); + } + MarkupKind::Errored { fallback, decls, body, .. } => { + self.markups(fallback); + self.decls(decls); + self.markups(body); + } + MarkupKind::Portal { to, decls, body } => { + if let Some(e) = to { + self.expr(e); + } + self.decls(decls); + self.markups(body); + } + } + } + } +} + +/// MO-6d: a namespace import, `import * as Select from "m"`, is the named imports of the members the module names: each +/// `Select.Item` — a tag's first part, or a type's in a type's text — is the name `Select$Item`, imported as `Item`. The +/// namespace itself is no value. `ref/src/parse.ts` `namespaces`. +pub fn namespaces(p: &mut Program) { + let nss: Vec = p.decls.iter().filter_map(|d| if let Decl::Import { ns: Some(n), .. } = d { Some(n.clone()) } else { None }).collect(); + if nss.is_empty() { + return; + } + // (`\w` is ASCII in ref's JavaScript pattern and every letter in Rust's: written out, so a combining mark after a + // member's first letter ends its name on both sides — found by ref/crate.ts --text, `Select.e\u{301}Opt`) + let res: Vec<(String, regex::Regex)> = nss.iter().map(|n| (n.clone(), regex::Regex::new(&format!(r"(^|[^A-Za-z0-9_$.]){}\.([A-Za-z_$][A-Za-z0-9_$]*)", regex::escape(n))).unwrap())).collect(); + let found = std::cell::RefCell::new(std::collections::BTreeSet::<(String, String)>::new()); + let ty = |t: &mut String| { + for (ns, re) in &res { + if t.contains(&format!("{ns}.")) { + *t = re.replace_all(t, |c: ®ex::Captures| { + found.borrow_mut().insert((ns.clone(), c[2].to_string())); + format!("{}{ns}${}", &c[1], &c[2]) + }).into_owned(); + } + } + }; + let mut text = |t: &mut String, tag: bool| { + if !tag { + return ty(t); + } + let Some(i) = t.find('.') else { return }; + if !nss.iter().any(|n| *n == t[..i]) { + return; + } + let rest = t[i + 1..].to_string(); + found.borrow_mut().insert((t[..i].to_string(), rest.split('.').next().unwrap_or("").to_string())); + *t = format!("{}${rest}", &t[..i]); + }; + struct Ns<'t, T: FnMut(&mut String, bool), Y: Fn(&mut String)>(&'t mut T, &'t Y); + impl VisitMut for Ns<'_, T, Y> { + fn expr(&mut self, e: &mut Expr) { + match &mut e.k { + ExprKind::Call { targs: Some(t), .. } => (self.1)(t), + ExprKind::Fn { ptypes, .. } => ptypes.iter_mut().flatten().for_each(self.1), + ExprKind::ServerFn { ptypes, ret, .. } => ptypes.iter_mut().flatten().chain(ret.iter_mut()).for_each(self.1), + _ => {} + } + } + fn text(&mut self, t: &mut String, tag: bool) { + (self.0)(t, tag) + } + } + visit_mut(p, &mut Ns(&mut text, &ty)); + let found = found.into_inner(); + for d in &mut p.decls { + if let Decl::Import { ns: Some(ns), names, .. } = d { + *names = found.iter().filter(|(n, _)| n == ns).map(|(_, m)| ImportName { name: m.clone(), alias: format!("{ns}${m}") }).collect(); + } + } +} +/// Every fn the program declares, in whatever block. +pub fn fns_mut(p: &mut Program, d: &mut dyn FnMut(&mut Decl)) { + struct Fns<'d>(&'d mut dyn FnMut(&mut Decl)); + impl VisitMut for Fns<'_> { + fn fn_decl(&mut self, d: &mut Decl) { + (self.0)(d) + } + } + visit_mut(p, &mut Fns(d)); +} +/// E-9b: a body that only names values — plain equations, and nothing in it that waits, remembers, reads a context or +/// makes anything. Whether one of them is a call that instantiates is the loader's to see (`modules::name_locals`). +pub fn names_only(d: &Decl) -> bool { + let Decl::Fn { params, decls, tail, .. } = d else { return false }; + if decls.is_empty() || params.iter().any(|p| p.r#ref) || !decls.iter().all(|d| matches!(d, Decl::Eq { deferred: false, key: None, .. } | Decl::TypeDecl { .. })) || std::iter::once(tail).chain(decls.iter().filter_map(|d| if let Decl::Eq { e, .. } = d { Some(e) } else { None })).any(|e| crate::ast::reads_context(Node::E(e))) { + return false; + } + let mut ok = true; + let mut f = |e: &Expr, _: &Scope| ok &= !matches!(e.k, ExprKind::Await { .. } | ExprKind::Pre { .. } | ExprKind::Use(_) | ExprKind::Draft { .. } | ExprKind::ServerFn { .. } | ExprKind::StyleMap { .. }); + Walk::new(&mut f).decls(std::slice::from_ref(d)); + ok +} +/// The names a body calls that nothing in it binds, its parameters included. +pub fn free_calls(params: &[String], body: &[Stmt]) -> Vec { + let mut out = vec![]; + let mut f = |e: &Expr, scope: &Scope| { + if let ExprKind::Call { f, .. } = &e.k { + if let ExprKind::Id(n) = &f.k { + if !scope.binds(n) { + out.push(n.clone()); + } + } + } + }; + Walk::new(&mut f).stmts(params.iter().map(|p| param(p)), body); + out +} diff --git a/compiler/src/serve.rs b/compiler/src/serve.rs index 780356892..1040f1d4a 100644 --- a/compiler/src/serve.rs +++ b/compiler/src/serve.rs @@ -1,29 +1,131 @@ //! `rxc serve`'s requests (spec/11 CP-8e), for a language server: the native binary answers them a line at a time, the //! WebAssembly build (`wasm.rs`) a call at a time, the same way. `disk` reads a file the editor does not have open. +use crate::json::Json; use serde_json::{json, Value}; use std::collections::HashMap; -/// One request: `analyze` (`{file, overlays, prelude}`) or `prelude`. -pub fn request(method: &str, params: &Value, disk: &dyn Fn(&str) -> Option) -> Value { +/// One request: `analyze` (`{file, overlays, prelude}`) or `prelude`; its answer's JSON text. +pub fn request(method: &str, params: &Value, disk: &dyn Fn(&str) -> Option) -> String { match method { "analyze" => analyze(params, disk), - "prelude" => json!(crate::project::PRELUDE), - _ => json!({ "error": "unknown method" }), + "prelude" => crate::json::quote(crate::project::PRELUDE), + // which build answers (lib.rs `BUILD`) + "build" => crate::json::quote(crate::BUILD), + "boundary" => boundary(params, disk).to_string(), + "declaration" => declaration(params, disk).to_string(), + // MO-8k: where a package import's declaration is found from `file` (null: none of the four places has one) + "rows" => rows(params, disk).to_string(), + "lookup" if params["below"].as_bool() == Some(true) => crate::modules::declaration_below(params["file"].as_str().unwrap_or(""), params["spec"].as_str().unwrap_or(""), disk).map_or("null".into(), |f| crate::json::quote(&f)), + "lookup" => crate::modules::declaration_for(params["file"].as_str().unwrap_or(""), params["spec"].as_str().unwrap_or(""), disk).map_or("null".into(), |f| crate::json::quote(&f)), + _ => "{\"error\":\"unknown method\"}".into(), + } +} + +/// `request`, its parameters as JSON text (the Node-API build's `serve`: node.rs). +pub fn request_text(method: &str, params: &str, disk: &dyn Fn(&str) -> Option) -> String { + request(method, &serde_json::from_str(params).unwrap_or(Value::Null), disk) +} + +/// A diagnostic as an editor is given one: `{file, line, code, rule, message, range}` (a parse error's `line` after its +/// `message`); `msg`, a message under that name as well, last. +pub struct Diag { + pub file: String, + pub line: Option, + /// the anchor's 1-based UTF-16 column on `line` (`rxc check`'s `file:line:col`); none where the diagnostic is placed on + /// its line alone (its `range` is then the line's nodes) + pub col: Option, + pub code: String, + pub rule: String, + pub message: Option, + pub range: Option, + pub msg: Option, + line_after: bool, +} +/// Where a diagnostic is: 1-based lines, 0-based columns in UTF-16 code units, and byte offsets. +pub struct Range { + pub start: (usize, usize), + pub end: (usize, usize), + pub offsets: (usize, usize), +} +impl Diag { + /// `rxc check --json`'s for a file that is not there. + pub fn not_found(file: String, code: &str, rule: &str, msg: String) -> Self { + Diag { file, line: Some(0), col: None, code: code.into(), rule: rule.into(), message: None, range: None, msg: Some(msg), line_after: false } + } + pub fn write(&self, j: &mut Json) { + j.obj(); + j.f_str("file", &self.file); + if !self.line_after { + if let Some(l) = self.line { + j.f_int("line", l); + } + if let Some(c) = self.col { + j.f_int("col", c); + } + } + j.f_str("code", &self.code); + j.f_str("rule", &self.rule); + j.f_ostr("message", self.message.as_deref()); + if self.line_after { + if let Some(l) = self.line { + j.f_int("line", l); + } + if let Some(c) = self.col { + j.f_int("col", c); + } + } + if let Some(r) = &self.range { + j.key("range"); + j.obj(); + for (k, (l, c)) in [("start", r.start), ("end", r.end)] { + j.key(k); + j.obj(); + j.f_int("line", l); + j.f_int("column", c); + j.end(); + } + j.key("offsets"); + j.arr(); + j.int(r.offsets.0); + j.int(r.offsets.1); + j.end(); + j.end(); + } + j.f_ostr("msg", self.msg.as_deref()); + j.end(); } } /// `rxc check --json`: a diagnostic with its range (CP-8), for an editor or an agent. Lines are 1-based, columns 0-based in /// UTF-16 code units, as LSP counts; `start`/`end` are byte offsets; `rule` names the spec rule (spec/99). -pub fn diagnostic_json(set: &crate::modules::ModuleSet, d: &crate::check::Diagnostic) -> Value { - let file = d.file.clone().unwrap_or_else(|| set.entry.clone()); - let mut v = json!({ "file": file, "line": d.line, "code": d.code, "rule": d.rule, "message": d.msg }); - if let (Some(src), Some(p)) = (set.sources.get(&file), set.programs.get(&file)) { - if let Some(r) = crate::spans::line_range(src, p, d.line.max(1) as usize) { - let ((l0, c0), (l1, c1)) = (crate::spans::line_col(src, r.start), crate::spans::line_col(src, r.end)); - v["range"] = json!({ "start": { "line": l0, "column": c0 }, "end": { "line": l1, "column": c1 }, "offsets": [r.start, r.end] }); +pub struct Diagnostics<'a> { + set: &'a crate::modules::ModuleSet, + ranges: HashMap>, +} +impl<'a> Diagnostics<'a> { + pub fn new(set: &'a crate::modules::ModuleSet) -> Self { + Diagnostics { set, ranges: HashMap::new() } + } + pub fn json(&mut self, d: &crate::check::Diagnostic) -> Diag { + let set = self.set; + let file = d.file.clone().unwrap_or_else(|| set.entry.clone()); + let mut range = None; + if let (Some(src), Some(p)) = (set.sources.get(&file), set.programs.get(&file)) { + let ranges = self.ranges.entry(file.clone()).or_insert_with(|| crate::spans::Ranges::new(src, p)); + // spec/99 *Where a diagnostic is*: on its anchor — the name, the call, the write it is about; else its line's nodes + let r = d.at.map(|a| a.span).or_else(|| ranges.of(d.line.max(1) as usize)); + if let Some(r) = r { + range = Some(range_of(&ranges.lines, r.start as usize, r.end as usize)); + } + } else if let Some(a) = d.at { + // a file that is no program (a host declaration, MO-14c): its anchor alone, as the checker placed it + range = Some(Range { start: (d.line as usize, a.col as usize - 1), end: (a.end_line as usize, a.end_col as usize - 1), offsets: (a.span.start as usize, a.span.end as usize) }); } + Diag { file, line: Some(d.line), col: d.at.map(|a| a.col as i64), code: d.code.clone(), rule: d.rule.clone(), message: Some(d.msg.clone()), range, msg: None, line_after: false } } - v +} +fn range_of(lines: &crate::spans::Lines, start: usize, end: usize) -> Range { + Range { start: lines.line_col(start), end: lines.line_col(end), offsets: (start, end) } } /// A parse error's message without the `file: line n:` it carries (the diagnostic's own fields say where). @@ -31,19 +133,21 @@ pub fn parse_message(e: &crate::parse::ParseError) -> &str { e.0.split_once("line ").filter(|(pre, _)| pre.is_empty() || pre.ends_with(": ")).and_then(|(_, r)| r.split_once(": ")).map(|(_, m)| m).unwrap_or(&e.0) } -pub fn parse_error_in(file: &str, e: &crate::parse::ParseError, src: Option<&str>) -> Value { +pub fn parse_error_in(file: &str, e: &crate::parse::ParseError, src: Option<&str>) -> Diag { + parse_error_at(file, e, src.map(crate::spans::Lines::new).as_ref()) +} +fn parse_error_at(file: &str, e: &crate::parse::ParseError, lines: Option<&crate::spans::Lines>) -> Diag { static RULE: std::sync::LazyLock = std::sync::LazyLock::new(|| regex::Regex::new(r"\b([A-Z]+-\d+[a-z]?)\b").unwrap()); let rule = RULE.captures(&e.0).map(|c| c[1].to_string()).unwrap_or_else(|| "07".into()); - let mut v = json!({ "file": file, "code": e.3, "rule": rule, "message": parse_message(e) }); - if let (Some(at), Some(src)) = (e.1, src) { - let at = at.min(src.len()); - let end = src[at..].find('\n').map(|j| at + j).unwrap_or(src.len()); - let end = at + src[at..end].trim_end().len(); - let ((l0, c0), (l1, c1)) = (crate::spans::line_col(src, at as u32), crate::spans::line_col(src, end as u32)); - v["line"] = json!(l0); - v["range"] = json!({ "start": { "line": l0, "column": c0 }, "end": { "line": l1, "column": c1 }, "offsets": [at, end] }); + let mut d = Diag { file: file.into(), line: None, col: None, code: e.3.to_string(), rule, message: Some(parse_message(e).to_string()), range: None, msg: None, line_after: true }; + if let (Some(at), Some(lines)) = (e.1, lines) { + let (at, end) = lines.rest(at); + d.line = Some(lines.line(at) as i64); + let r = range_of(lines, at, end); + d.col = Some(r.start.1 as i64 + 1); // where the parse stopped + d.range = Some(r); } - v + d } /// UTF-16 offsets of a text's byte offsets (what JavaScript strings, Volar and LSP index by). @@ -63,33 +167,434 @@ pub fn utf16_index(s: &str) -> Vec { /// `rxc serve`, one request: `{file, overlays: {path: text}, prelude}` — the file loaded (and its imports) as an editor /// has them, recovering (CP-8e); its projection with mappings in UTF-16 offsets, and its diagnostics: the parse's, else /// the checker's. -pub fn analyze(params: &Value, disk: &dyn Fn(&str) -> Option) -> Value { +pub fn analyze(params: &Value, disk: &dyn Fn(&str) -> Option) -> String { let file = params["file"].as_str().unwrap_or_default().to_string(); let overlays: HashMap = params["overlays"].as_object().map(|o| o.iter().filter_map(|(k, v)| Some((k.clone(), v.as_str()?.to_string()))).collect()).unwrap_or_default(); let read = |p: &str| overlays.get(p).cloned().or_else(|| disk(p)); + let mut j = Json::new(); + j.obj(); let set = match crate::modules::load_modules_recovering(&file, &read) { Ok(s) => s, Err(e) => { let src = e.2.as_deref().and_then(|f| read(f)); - return json!({ "diagnostics": [parse_error_in(e.2.as_deref().unwrap_or(&file), &e, src.as_deref())] }); + j.key("diagnostics"); + j.arr(); + parse_error_in(e.2.as_deref().unwrap_or(&file), &e, src.as_deref()).write(&mut j); + j.end(); + j.end(); + return j.finish(); } }; let src = set.sources.get(&file).cloned().unwrap_or_default(); let prelude = params["prelude"].as_str(); - let mut out = json!({ "code": null, "mappings": [] }); - if let Some(p) = crate::project::project_modules_with(&set, prelude).into_iter().find(|p| p.rx == file) { - let (gi, si) = (utf16_index(&p.code), utf16_index(&src)); - let maps: Vec<[u32; 3]> = p.mappings.iter().map(|m| [gi[m.gen as usize], si[m.src as usize], si[(m.src + m.len) as usize] - si[m.src as usize]]).collect(); - let u = |i: &[u32], a: u32, n: u32| [i[a as usize], i[(a + n) as usize] - i[a as usize]]; - let ranges: Vec<[u32; 4]> = p.ranges.iter().map(|r| { let (g, s) = (u(&gi, r.gen, r.glen), u(&si, r.src, r.len)); [g[0], g[1], s[0], s[1]] }).collect(); - out = json!({ "code": p.code, "mappings": maps, "ranges": ranges }); - } - let own: Vec = if set.parse_errors.iter().any(|e| e.2.as_deref() == Some(file.as_str())) { - set.parse_errors.iter().filter(|e| e.2.as_deref() == Some(file.as_str())).map(|e| parse_error_in(&file, e, Some(&src))).collect() + match crate::project::project_module_with(&set, prelude, &file) { + Some(p) => { + let (gi, si) = (utf16_index(&p.code), utf16_index(&src)); + let u = |i: &[u32], a: u32, n: u32| [i[a as usize], i[(a + n) as usize] - i[a as usize]]; + j.f_str("code", &p.code); + j.key("mappings"); + j.arr(); + for m in &p.mappings { + j.arr(); + [gi[m.gen as usize], si[m.src as usize], si[(m.src + m.len) as usize] - si[m.src as usize]].iter().for_each(|n| j.int(n)); + j.end(); + } + j.end(); + j.key("ranges"); + j.arr(); + for r in &p.ranges { + let (g, s) = (u(&gi, r.gen, r.glen), u(&si, r.src, r.len)); + j.arr(); + [g[0], g[1], s[0], s[1]].iter().for_each(|n| j.int(n)); + j.end(); + } + j.end(); + } + None => { + j.key("code"); + j.null(); + j.key("mappings"); + j.arr(); + j.end(); + } + } + // `whole` (E-5a): the loaded modules checked as the whole program, `hosts` the modules a JS host imports with ?rx-lib + // (as a build is checked, `app.rs`); `all`: every loaded module's diagnostics, not only the file's (`rx-tsc + // --rx-whole-program`, which checks from each program's entry) + let all = params["all"].as_bool().unwrap_or(false); + let hosts: Vec = params["hosts"].as_array().map(|a| a.iter().filter_map(|h| h.as_str().map(|h| h.replace('\\', "/"))).collect()).unwrap_or_default(); + let hosts = crate::modules::hosts_as_keys(&set, &hosts); + let mut ranges = Diagnostics::new(&set); + // 99, the advisory rows (ASYNC_WATERFALL, SNAPSHOT_IN_EFFECT, GUESS_AFTER_AWAIT, …): about a correct program, given beside + // the diagnostics for the editor to show as information — never an error, never counted by rx-tsc + let mut advice: Vec = vec![]; + let mut own: Vec = if set.parse_errors.iter().any(|e| all || e.2.as_deref() == Some(file.as_str())) { + let mut lines: HashMap<&str, crate::spans::Lines> = HashMap::new(); + set.parse_errors + .iter() + .filter(|e| all || e.2.as_deref() == Some(file.as_str())) + .map(|e| { + let f = e.2.as_deref().unwrap_or(&file); + let lines = set.sources.get(f).map(|src| &*lines.entry(f).or_insert_with(|| crate::spans::Lines::new(src))); + parse_error_at(f, e, lines) + }) + .collect() } else { - crate::check::check_modules(&set, params["spa"].as_bool().unwrap_or(false)).diags.iter().map(|d| diagnostic_json(&set, d)).filter(|d| d["file"] == json!(file)).collect() + let checked = crate::check::check_modules_hosts(&set, params["spa"].as_bool().unwrap_or(false), params["whole"].as_bool().unwrap_or(false), &hosts); + advice = checked.advice.iter().map(|d| ranges.json(d)).filter(|d| all || d.file == file).collect(); + checked.diags.iter().map(|d| ranges.json(d)).filter(|d| all || d.file == file).collect() + }; + // MO-5, per module: a cycle is found where it closes, so its diagnostic sits on the import that closes it — in another + // module than the one an editor (or per-module rx-tsc) analyses, which then passed in silence. Each module on the + // cycle has it, at its own import that goes on around it. + if !all && !own.iter().any(|d| d.code == "MODULE_CYCLE") { + for d in set.diags.iter().filter(|d| d.code == "MODULE_CYCLE" && d.file.as_deref() != Some(file.as_str())) { + let chain: Vec<&str> = d.msg.split(": modules may not").next().unwrap_or_default().split(" → ").collect(); + let Some(i) = chain.iter().position(|m| *m == file) else { continue }; + let Some(next) = chain.get(i + 1) else { continue }; + let line = set.programs.get(&file).and_then(|p| p.decls.iter().find_map(|x| match x { + crate::ast::Decl::Import { resolved: Some(r), span, .. } if r == next => Some(p.line(*span) as i64), + _ => None, + })); + let Some(line) = line else { continue }; + let mine = crate::check::Diagnostic { code: d.code.clone(), rule: d.rule.clone(), line, msg: d.msg.clone(), file: Some(file.clone()), at: None }; + own.push(ranges.json(&mine)); + break; + } + } + j.key("diagnostics"); + j.arr(); + own.iter().for_each(|d| d.write(&mut j)); + j.end(); + j.key("advice"); + j.arr(); + advice.iter().for_each(|d| d.write(&mut j)); + j.end(); + j.f_strs("modules", &set.order); + // MO-8f, MO-8j, TY-6: the declarations this load consumed, each with its importer and the import's text + let mut uses: Vec<(&str, &str, &str)> = set.declaration_uses.iter().map(|u| (u.declaration.as_str(), u.importer.as_str(), u.spec.as_str())).collect(); + // MO-14e: the host declaration this program is under is a declaration it is checked by — and what that declaration + // imports from JavaScript (MO-14f) is consumed through it, by the declaration's own place + let own_decl = set.host.as_ref().map(|h| format!("{}.host.d.rx", h.file)); + if let (Some(h), Some(own)) = (&set.host, &own_decl) { + j.f_str("host", &h.file); + for u in h.set.declaration_uses.iter().filter(|u| u.importer == h.entry && u.declaration != *own) { + let v = (u.declaration.as_str(), h.file.as_str(), u.spec.as_str()); + if !uses.contains(&v) { + uses.push(v); + } + } + } + j.key("declarations"); + j.arr(); + for (file, importer, spec) in uses { + j.obj(); + j.f_str("file", file); + j.f_str("importer", importer); + j.f_str("spec", spec); + j.end(); + } + j.end(); + j.end(); + j.finish() +} + + +/// `boundary` (`{file, text?, module}`): a TypeScript file that checks a `.d.rx` against the JS module it declares +/// (TY-6): each export's declared row as a type, then the module's real export assigned to it. `checks` maps each +/// assignment's line in `code` (1-based) to the declaration's line and name, so a type error lands on the `.d.rx`. +pub fn boundary(params: &Value, disk: &dyn Fn(&str) -> Option) -> Value { + let file = params["file"].as_str().unwrap_or_default(); + let module = params["module"].as_str().unwrap_or_default(); + let Some(text) = params["text"].as_str().map(str::to_string).or_else(|| disk(file)) else { return json!({ "error": format!("cannot read {}", file) }) }; + // MO-13a: a printed signature declares no JS module: its rows are the compiler's, and nothing is held against types here + if crate::modules::is_printed_signature(&text) { + return json!({ "signature": true, "code": "export {};\n", "checks": [] }); + } + // MO-8y: a project's declaration is held by its own `export` rows; the rows it leaves to the declaration below, and + // the types of the rows it extends, are held where that file is + let extended = |r: &crate::parse::JsDecl| text.get(row_span(r).start as usize..).is_some_and(|t| t.starts_with("extend")); + let held = crate::modules::read_over(file, &text, disk).map(|mut d| { + // MO-8y, TY-6g: the names an `extend` row puts its words on, held against the type the row below names (extends.rs) + let below: Vec = d.rows[d.own..].iter().filter(|r| matches!(r, crate::parse::JsDecl::Type { .. })).cloned().collect(); + let names = crate::extends::names(&text, &d.rows[..d.own]); + d.rows.truncate(d.own); + // (an `extend` row's types are the row's below, held where that declaration is: here it states none) + d.rows.retain(|r| !extended(r)); + (d.rows, names, below) + }); + match held { + Ok((decls, names, below)) => { + let (mut code, checks, mut overlay) = crate::dts::boundary_checks(&decls, module, &below); + crate::extends::append(&mut code, &mut overlay, &names); + let lines = crate::ast::LineIndex::new(&text); + let mut all: Vec = checks.iter().map(|(at, row, name)| json!({ "at": at, "line": lines.of(*row), "name": name })).collect(); + // MO-8o: a field of a props' record against the library's type for that prop; `says` is the finding + all.extend(overlay.iter().map(|o| json!({ "at": o.at, "line": lines.of(o.row), "name": o.name, "prop": o.prop, "overlay": if o.suggest { "suggest" } else if o.has { "has" } else { "type" }, "says": o.says, "extend": o.extend }))); + json!({ "code": code, "checks": all }) + } + Err(e) => json!({ "error": e.0 }), + } +} + +/// `declaration` (`{file, text?}`): the `.d.ts` a `.d.rx` stands for (TY-4b), for a JS module that has no TypeScript types +/// of its own: what `rx-tsc` gives TypeScript in its place. +/// MO-8j, TY-7: a declaration file's rows as the parser reads them: each row's name and kind, the lines it spans (to +/// the next row), what running must show for it to be verified (`obligations`, `parse::obligations`), and what the row +/// says (`facts`). Every tool that asks what a row means — rx-verify, the strict record, the audit, the benchmark — +/// reads these, so none reads the row's text for itself. +pub fn rows(params: &Value, disk: &dyn Fn(&str) -> Option) -> Value { + use crate::parse::JsDecl; + let file = params["file"].as_str().unwrap_or_default(); + let Some(text) = params["text"].as_str().map(str::to_string).or_else(|| disk(file)) else { return json!({ "error": format!("cannot read {}", file) }) }; + // MO-13a: a printed signature's rows are what the compiler inferred, not assertions: none to verify (MO-8j) + if crate::modules::is_printed_signature(&text) { + return json!({ "signature": true, "rows": [] }); + } + // MO-8y: a project's declaration over the one below it — its own rows (an `extend` row as the row it makes, `extend`: + // true), each on its lines; the rows it leaves to the declaration below are that file's + let over = match crate::modules::read_over(file, &text, disk) { + Ok(d) if d.below.is_some() => Some(d), + // (MO-15c, 2026-12-02: a shared declaration's `extend` rows over its own draft, below `//@ drafted below`) + Ok(d) if text.lines().any(|l| l.trim_start().starts_with("extend ")) => Some(d), + Ok(_) => None, + Err(e) => return json!({ "error": e.0 }), }; - out["diagnostics"] = json!(own); + let parsed = match over { + Some(mut d) => { + d.rows.truncate(d.own); + let lines = crate::ast::LineIndex::new(&text); + let starts: Vec = d.rows.iter().map(|r| lines.of(row_span(r))).collect(); + Ok((d.rows, starts, d.below.map(|b| b.0))) + } + None => crate::parse::parse_declaration_rows(&text).map(|(d, s)| (d, s, None)), + }; + match parsed { + Ok((decls, starts, below)) => { + let last = text.lines().count().max(1); + let rows: Vec = decls + .iter() + .enumerate() + .map(|(i, d)| { + let line = starts[i]; + let end = starts.get(i + 1).map(|n| n - 1).unwrap_or(last); + let kind = match d { + JsDecl::Fn { .. } => "fn", + JsDecl::Comp { .. } => "component", + JsDecl::Error { .. } => "error", + JsDecl::Value { .. } => "const", + JsDecl::Type { .. } => "type", + JsDecl::Context { .. } => "context", + JsDecl::Import { .. } => "import", + JsDecl::Host { .. } => "host", + }; + let mut facts = facts(d); + facts["types"] = json!(type_places(d)); + if let JsDecl::Host { tree, .. } = d { + facts["tree"] = json!(text.get(tree.start as usize..tree.end as usize).unwrap_or_default().trim()); // MO-14b: the view, as written + } + let extend = text.get(row_span(d).start as usize..).is_some_and(|t| t.starts_with("extend")); + let mut row = json!({ "name": d.name(), "kind": kind, "line": line, "end": end, "obligations": crate::parse::obligations(d), "facts": facts }); + if extend { + row["extend"] = json!(true); + } + row + }) + .collect(); + match below { + Some(b) => json!({ "rows": rows, "below": b }), + None => json!({ "rows": rows }), + } + } + Err(e) => json!({ "error": e.0 }), + } +} + +fn row_span(d: &crate::parse::JsDecl) -> crate::ast::Span { + use crate::parse::JsDecl; + match d { + JsDecl::Fn { span, .. } | JsDecl::Error { span, .. } | JsDecl::Type { span, .. } | JsDecl::Comp { span, .. } | JsDecl::Context { span, .. } | JsDecl::Value { span, .. } | JsDecl::Import { span, .. } | JsDecl::Host { span, .. } => *span, + } +} + +/// Every place of a row a type is written at, in the order the row writes them, each under a name: `tparams`, +/// `param:0`, `param:1.onDone` (a field of a record written there), `result`, `result.0` (an item of a tuple), `param:0.()0` and `param:0.=>` (a function type's +/// parameter and result), `.<0>` (a type argument), `.|0` (a member of a union), `.[]` (an array's element), `props` +/// (a component's props where they are a type the library names), `prop:label`, `type` (a value's, an alias's). What a +/// tool compares two rows of one export by: an `any` at one place says nothing of another (09 MO-8q). +fn type_places(d: &crate::parse::JsDecl) -> Vec<(String, String)> { + use crate::parse::{closes, split_top, JsDecl}; + fn walk(id: String, t: &str, out: &mut Vec<(String, String)>) { + let t = t.trim(); + if t.is_empty() { + return; + } + let end = closes(t, 0); + let whole = end == Some(t.len()); + // `(a: A) => R`: each parameter and the result are places of their own + if t.starts_with('(') { + if let Some((e, r)) = end.and_then(|e| t[e..].trim_start().strip_prefix("=>").map(|r| (e, r))) { + for (k, p) in split_top(&t[1..e - 1], ",").iter().enumerate() { + walk(format!("{id}.(){k}"), p.split_once(':').map_or(p.as_str(), |(_, ty)| ty), out); + } + return walk(format!("{id}.=>"), r, out); + } + if whole { + return walk(id, &t[1..t.len() - 1], out); + } + } + let members = split_top(t, "|&"); + if members.iter().filter(|m| !m.trim().is_empty()).count() > 1 { + for (k, m) in members.iter().enumerate() { + walk(format!("{id}.|{k}"), m, out); + } + return; + } + if let Some(of) = t.strip_suffix("[]") { + return walk(format!("{id}.[]"), of, out); + } + let body = t.strip_prefix("readonly").map(str::trim_start).filter(|r| r.starts_with('[')).unwrap_or(t); + let shut = closes(body, 0) == Some(body.len()); + if body.starts_with('{') && shut { + for (k, f) in crate::parse::members(&body[1..body.len() - 1]).iter().enumerate() { + let name = f.find(':').map(|i| f[..i].trim().trim_start_matches("readonly ").trim().trim_end_matches('?').to_string()).filter(|n| !n.is_empty() && n.chars().all(|c| c.is_alphanumeric() || c == '_' || c == '$')); + match name { + Some(n) => walk(format!("{id}.{n}"), &f[f.find(':').unwrap() + 1..], out), + None => out.push((format!("{id}.#{k}"), f.clone())), // a method, an index signature: a place of its own + } + } + } else if body.starts_with('[') && shut { + for (k, x) in split_top(&body[1..body.len() - 1], ",").iter().enumerate() { + walk(format!("{id}.{k}"), x, out); + } + } else if let Some(lt) = body.find('<').filter(|&i| i > 0 && body[..i].chars().all(|c| c.is_alphanumeric() || "_$.".contains(c)) && closes(body, i) == Some(body.len())) { + for (k, x) in split_top(&body[lt + 1..body.len() - 1], ",").iter().enumerate() { + walk(format!("{id}.<{k}>"), x, out); + } + } else { + out.push((id, t.to_string())); + } + } + let mut out = vec![]; + match d { + JsDecl::Fn { ptypes, ret, tparams, .. } => { + if let Some(t) = tparams { + out.push(("tparams".to_string(), t.clone())); + } + for (i, t) in ptypes.iter().enumerate() { + walk(format!("param:{i}"), t.as_deref().unwrap_or(""), &mut out); + } + walk("result".to_string(), ret.as_deref().unwrap_or(""), &mut out); + } + JsDecl::Comp { props, tparams, props_type, .. } => { + if let Some(t) = tparams { + out.push(("tparams".to_string(), t.clone())); + } + if let Some(t) = props_type { + out.push(("props".to_string(), t.clone())); + } + for p in props { + walk(format!("prop:{}", p.name), p.ty.as_deref().unwrap_or(""), &mut out); + } + } + JsDecl::Value { ty, .. } => walk("type".to_string(), ty.as_deref().unwrap_or(""), &mut out), + JsDecl::Type { text, .. } => walk("type".to_string(), text, &mut out), + JsDecl::Error { .. } | JsDecl::Context { .. } | JsDecl::Import { .. } | JsDecl::Host { .. } => {} + } out } +/// What a row says, as the parser read it. A fn: its words (`pure`, `side`, `instantiates`, `rejects`, `uses`, +/// `provides`, `nests`, `renders`), its parameters (`name`, `type`, `ref`, `draft`, `optional`, `rest`), its callback +/// positions (`callbacks`: `index`, `name`, `field`, `handler`), its result (`result`, TypeScript's text; `shape`; and +/// `parts`, every place a read of the result may be asked about — the whole result when it is a `ref`, a tuple's items, +/// a record's fields, a plain record below a field too — each with `ref`, `pending`, `fails`, `draft`). A component: its +/// props (`name`, `type`, `optional`, `function`, `handler`, `render`, `component`, `components`, `view`) and its words. +fn facts(d: &crate::parse::JsDecl) -> Value { + use crate::parse::{JsDecl, Part, Shape}; + match d { + JsDecl::Fn { pure, reads, params, rejects, side, ptypes, ret, refs, shape, instantiates, uses, provides, nests, held, opts, waits, part_drafts, draft_args, renders, cbs, io_parts, ctor, .. } => { + let ps: Vec = params + .iter() + .enumerate() + .map(|(i, n)| json!({ "name": n.trim_start_matches("..."), "type": ptypes.get(i).cloned().flatten(), "ref": refs.get(i).copied().unwrap_or(false), "draft": draft_args.contains(&i), "optional": opts.get(i).copied().unwrap_or(false), "rest": n.starts_with("...") })) + .collect(); + let cbs: Vec = crate::parse::callbacks_of(params, ptypes, cbs).into_iter().map(|c| json!({ "index": c.index, "name": c.name, "field": c.field, "handler": c.handler })).collect(); + let rows = |key: &str| held.iter().find(|h| h.0 == key).map(|h| (h.1, h.2.clone())).unwrap_or_default(); + let part = |path: Vec, kind: Part, rows: (bool, Vec)| json!({ "path": path, "ref": kind == Part::Ref, "fn": kind == Part::Fn, "pending": rows.0, "fails": rows.1, "draft": path.len() == 1 && part_drafts.iter().any(|p| p.0 == path[0]) }); + // a plain record below a field is read field by field as well: a read that waits or fails there has no row + fn below(t: &str, path: &[String], out: &mut Vec) -> bool { + let t = t.trim(); + if !(t.len() >= 2 && t.starts_with('{') && t.ends_with('}')) { + return false; + } + for f in crate::parse::members(&t[1..t.len() - 1]) { + let Some(i) = f.find(':') else { continue }; + let k = f[..i].trim().trim_start_matches("readonly ").trim().trim_end_matches('?').to_string(); + if k.is_empty() || !k.chars().all(|c| c.is_alphanumeric() || c == '_' || c == '$') { + continue; + } + let p: Vec = path.iter().cloned().chain([k]).collect(); + if !below(&f[i + 1..], &p, out) { + out.push(json!({ "path": p, "ref": false, "fn": false, "pending": false, "fails": [], "draft": false })); + } + } + true + } + let ret_text = ret.as_deref().unwrap_or(""); + let body = ret_text.trim().strip_prefix("readonly").map(str::trim).filter(|r| r.starts_with('[')).unwrap_or(ret_text.trim()); + let mut parts: Vec = vec![]; + let kind = match shape { + Shape::Comp => "comp", + Shape::Part(Part::Ref) => { + parts.push(part(vec![], Part::Ref, waits.clone().unwrap_or_default())); + "ref" + } + Shape::Part(Part::Fn) => "fn", + Shape::Part(Part::Value) => { + // MO-8y: a result whose type is named, with the fields an `extend` row says wait or fail + parts.extend(held.iter().filter(|h| !h.0.contains('.')).map(|h| part(vec![h.0.clone()], Part::Value, (h.1, h.2.clone())))); + parts.extend(io_parts.iter().map(|f| part(vec![f.clone()], Part::Fn, Default::default()))); + "value" + } + Shape::Items(items) => { + parts.extend(items.iter().enumerate().map(|(i, k)| part(vec![i.to_string()], *k, rows(&i.to_string())))); + "items" + } + Shape::Fields(fields) => { + let texts = if body.len() >= 2 { crate::parse::members(&body[1..body.len() - 1]) } else { vec![] }; + for (i, (name, k)) in fields.iter().enumerate() { + let ty = texts.get(i).and_then(|f| f.find(':').map(|at| f[at + 1..].to_string())).unwrap_or_default(); + if *k != Part::Value || !below(&ty, std::slice::from_ref(name), &mut parts) { + parts.push(part(vec![name.clone()], *k, rows(name))); + } + } + "fields" + } + }; + json!({ "pure": pure, "reads": reads, "side": side.map(|s| s.as_str()), "instantiates": instantiates, "rejects": rejects, "uses": uses, "provides": provides, "nests": nests.as_ref().map(|(kids, inside)| json!({ "kids": kids, "inside": inside })), "renders": renders, "params": ps, "callbacks": cbs, "result": ret, "shape": kind, "parts": parts, "ctor": ctor }) + } + JsDecl::Comp { props, fails, uses, provides, props_type, .. } => { + let ps: Vec = props.iter().map(|p| json!({ "name": p.name, "type": p.ty, "optional": p.optional, "function": p.callback || p.pure, "handler": p.callback, "render": p.render, "component": p.component, "components": p.components, "view": p.view })).collect(); + json!({ "props": ps, "propsType": props_type, "fails": fails, "uses": uses, "provides": provides }) + } + JsDecl::Error { fields, .. } => json!({ "fields": fields }), + JsDecl::Type { text, .. } => json!({ "type": text }), + JsDecl::Value { ty, client, .. } => json!({ "type": ty, "client": client }), + JsDecl::Context { from, .. } => json!({ "from": from }), + JsDecl::Import { names, from, .. } => json!({ "names": names.iter().map(|(n, a)| json!([n, a])).collect::>(), "from": from }), + JsDecl::Host { provides, nests, .. } => json!({ "provides": provides, "nests": nests.as_ref().map(|(kids, inside)| json!({ "kids": kids, "inside": inside })) }), + } +} +pub fn declaration(params: &Value, disk: &dyn Fn(&str) -> Option) -> Value { + let file = params["file"].as_str().unwrap_or_default(); + let Some(text) = params["text"].as_str().map(str::to_string).or_else(|| disk(file)) else { return json!({ "error": format!("cannot read {}", file) }) }; + // MO-13a: a printed signature carries rows, not types: its module's types are the `.d.ts` shipped beside it (TY-4c) + if crate::modules::is_printed_signature(&text) { + return json!({ "signature": true }); + } + match crate::modules::read_over(file, &text, disk).map(|d| d.rows) { + Ok(decls) => json!({ "code": crate::dts::declaration_file(&decls) }), + Err(e) => json!({ "error": e.0 }), + } +} diff --git a/compiler/src/signature.rs b/compiler/src/signature.rs index 36103a4ed..5ca3715d8 100644 --- a/compiler/src/signature.rs +++ b/compiler/src/signature.rs @@ -11,6 +11,7 @@ //! export context theme: source pending Theme = … rows, then the written type; `= …` a default //! export component Panel(props: { title; children: catches(Error) provides(./theme.rx#theme) }) fails(Error) uses(…) shape(…) +use crate::parse::JsTrim; use crate::content::Shape; use indexmap::{IndexMap, IndexSet}; use regex::Regex; @@ -47,9 +48,28 @@ pub struct PropSig { pub f: Catch, pub p: Catch, pub rendered: bool, + /// SC-4b: an `on…` prop typed to answer a value: a function the component calls for what it answers, no handler + pub pure: bool, pub action: Option<(Catch, String)>, /// MO-11c: a JS component's prop that takes a component value pub component: bool, + /// MO-11c (2026-11-24): a JS component's prop whose type holds a `Component` inside a record or an array + pub components: bool, + /// MO-10f: the fields of this prop its type says hold or fail where they are read (path, holds, classes): a JS + /// result with such fields may be given whole + pub takes: Vec<(String, bool, Vec)>, + /// RG-4c + pub view: Option, +} +/// RG-4c: a view the component shows: whether it is optional, what its parameter's type says, and the fields it is shown with +/// that hold no closure of the component's (O-3). +#[derive(Debug, Clone, PartialEq)] +pub struct ViewSig { + pub optional: bool, + /// plain content is taken as well + pub mixed: bool, + pub ty: Option, + pub values: Vec, } #[derive(Debug, Clone)] pub struct Own { @@ -60,35 +80,143 @@ pub struct Own { /// MO-3: an exported component as an importer sees it. #[derive(Debug, Clone)] pub struct CompSig { + /// 07 §2: ``, as text + pub tparams: Option, + /// MO-11j: a JS factory's component, exported from the module that made it (applied as JSX's ``) + pub made: bool, pub own: Vec, pub requires: Vec, pub props: IndexMap, pub shape: Option, /// O-3: the props it stores where they outlive it — "module", or a provision's key. pub stored: IndexMap>, + /// MO-11u: each place the component applies a component a declared fn `renders(…)` beneath, by that component's key + /// (`declaration#Name`): what is discharged and provided between its children there and this component's root + pub hosts: IndexMap>, + /// MO-14f (2026-11-25), in a host's view: the component's view applies a component the host renders through, so it + /// renders its applier's children there. Not printed: a host's view is checked from source + pub through: bool, +} +/// MO-11u: one application of a component a declared fn `renders(…)` beneath, as the components that fn is given see it. +#[derive(Debug, Clone, PartialEq)] +pub struct HostSite { + pub f: Catch, + pub p: Catch, +} +/// MO-11u: a call of a fn declared `renders(H)` that was given components — what they let out of H's children, H's own +/// `uses(…)` and `provides(…)` taken off: judged at each application of H in the program (`check::judge_hosted`). +#[derive(Debug, Clone)] +pub struct Hosted { + pub host: String, + pub name: String, + pub r#fn: String, + pub line: usize, + pub fails: Vec, + pub requires: Vec, + /// the places those components themselves apply a host (a routed layout's ``), from their own root, with + /// what H uses and provides above them + pub inner: IndexMap>, + /// spec/99 *Where a diagnostic is*: the call's anchor on `line`, in this run (a printed signature has none) + pub at: Option, } #[derive(Debug, Clone)] pub struct SigParam { pub name: String, pub r#ref: bool, pub ty: Option, + pub opt: bool, } #[derive(Debug, Clone)] pub enum ExportSig { - Source { question: bool, rows: Vec, fails: Vec }, - Eq { rows: Vec, fails: Vec, io: bool }, - Fn { params: Vec, instantiating: bool, rows: Vec, fails: Vec, rejects: Vec }, + Source { question: bool, rows: Vec, fails: Vec, actions: Vec }, + /// `actions`: R-io-3, the parts of its value (a fn's: of its result) that are actions, as paths ("": the value) + Eq { rows: Vec, fails: Vec, io: bool, actions: Vec }, + /// `uses`: RG-7b, the contexts a call of it reads above the place it is written (keys) + Fn { /// 07 §2: ``, as text + tparams: Option, params: Vec, instantiating: bool, rows: Vec, fails: Vec, rejects: Vec, uses: Vec, actions: Vec, /// MO-9b, W2: the paths of its parameters it calls while it runs, `p` or `p.path` (`calls(f, xs.*)`) + calls: Vec, /// MO-13i: the parts of its result, where they are known + result: Option }, Action, Server { io: bool, params: Vec, rejects: Vec }, ErrClass { params: Vec }, Comp { sig: CompSig }, Context { key: String, source: bool, dflt: bool, rows: Vec, fails: Vec, ty: Option }, - Type, + /// what it stands for (RG-4c), where a signature can hold it + /// what it stands for, and its type parameters (07 §2) + Type(Option, Option), +} +/// MO-13i: what a fn's result is made of. An action; one value, read (`reader`: it changes, with the rows it is read with) +/// or plain (made once), and the parts of it that are actions; a record or a tuple of such. +#[derive(Debug, Clone, PartialEq)] +pub enum Res { + Io, + Leaf { reader: bool, rows: Vec, fails: Vec, actions: Vec }, + Rec(Vec<(String, Res)>), + Arr(Vec), +} +impl Res { + pub fn is_reader(&self) -> bool { + matches!(self, Res::Leaf { reader: true, .. }) + } + pub fn at(&self, key: &str) -> Option<&Res> { + match self { + Res::Rec(fs) => fs.iter().find(|f| f.0 == key).map(|f| &f.1), + Res::Arr(xs) => key.parse::().ok().and_then(|i| xs.get(i)), + _ => None, + } + } + /// R-io-3: its parts that are actions, as paths + pub fn actions(&self) -> Vec { + let part = |k: &str, r: &Res| r.actions().into_iter().map(|p| if p.is_empty() { k.to_string() } else { format!("{k}.{p}") }).collect::>(); + sorted(match self { + Res::Io => vec![String::new()], + Res::Leaf { actions, .. } => actions.clone(), + Res::Rec(fs) => fs.iter().flat_map(|(k, r)| part(k, r)).collect(), + Res::Arr(xs) => xs.iter().enumerate().flat_map(|(i, r)| part(&i.to_string(), r)).collect(), + }) + } + /// What `rx-lib` writes the module's JavaScript and its types from: `"io"`, `"ref"`, `"value"`, a record or a list of such. + pub fn write(&self, j: &mut crate::json::Json) { + match self { + Res::Io => j.str("io"), + Res::Leaf { reader, .. } => j.str(if *reader { "ref" } else { "value" }), + Res::Rec(fs) => { + // as a map collected from its fields: a key given twice keeps its first place and its last value + let mut m: IndexMap<&str, &Res> = IndexMap::new(); + for (k, r) in fs { + m.insert(k, r); + } + j.obj(); + for (k, r) in m { + j.key(k); + r.write(j); + } + j.end(); + } + Res::Arr(xs) => { + j.arr(); + xs.iter().for_each(|x| x.write(j)); + j.end(); + } + } + } } #[derive(Debug, Clone)] pub struct ModSig { pub file: String, pub exports: IndexMap, + /// MO-11u: the calls of `renders(H)` fns that were given components + pub hosted: Vec, + /// MO-11u: the applications of such an H the module itself roots (its mounted view, a root of a library's own) + pub hosts: IndexMap>, + /// MO-6e: the names the module re-exports, by the module that declares them + pub reexports: Vec, +} +/// MO-6e: `export { A, B as C } from "./m.rx"` — the spec, and each (name there, alias here). +#[derive(Debug, Clone)] +pub struct Reexport { + pub from: String, + pub names: Vec<(String, String)>, } fn sorted(xs: impl IntoIterator) -> Vec { @@ -126,11 +254,30 @@ fn split_hash(key: &str) -> (String, String) { } } /// A context key relative to the module whose signature names it (`./theme.rx#theme`). +/// A prop's name in a row: `...props` for the spread, a key that is no identifier quoted (`"tc-button"`, X5). +fn field_text(f: &str) -> String { + let ident = f.chars().next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_' || c == '$') && f.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$'); + if f == "*" { "...props".into() } else if ident { f.into() } else { serde_json::to_string(f).unwrap_or_else(|_| f.into()) } +} +/// A row's prop name and what follows its `:`, read back (a quoted name may hold a `:`). +fn field_of(s: &str) -> (String, String) { + let t = crate::parse::js_trim(s); + if t.starts_with('"') { + let mut esc = false; + let end = t.char_indices().skip(1).find(|&(_, c)| { let close = c == '"' && !esc; esc = c == '\\' && !esc; close }).map(|(i, _)| i + 1); + if let Some(name) = end.and_then(|e| serde_json::from_str::(&t[..e]).ok().map(|n| (n, e))) { + let rest = crate::parse::js_trim(&t[name.1..]); + return (name.0, crate::parse::js_trim(rest.strip_prefix(':').unwrap_or(rest)).to_string()); + } + } + let (f, rest) = match t.find(':') { Some(i) => (crate::parse::js_trim(&t[..i]), crate::parse::js_trim(&t[i + 1..])), None => (t, "") }; + (if f == "...props" { "*".into() } else { f.into() }, rest.into()) +} /// O-3: the props a component stores where they outlive it, and where. fn retains_text(file: &str, st: &IndexMap>) -> String { let mut fs: Vec<&String> = st.keys().collect(); fs.sort(); - let xs: Vec = fs.into_iter().flat_map(|f| st[f].iter().map(move |t| format!("{}: {}", if f == "*" { "...props" } else { f }, if t == "module" { t.clone() } else { rel_key(file, t) }))).collect(); + let xs: Vec = fs.into_iter().flat_map(|f| st[f].iter().map(move |t| format!("{}: {}", field_text(f), if t == "module" { t.clone() } else { rel_key(file, t) }))).collect(); if xs.is_empty() { String::new() } else { format!(" retains({})", xs.join(", ")) } } fn rel_key(from: &str, key: &str) -> String { @@ -190,29 +337,175 @@ fn shape_text(s: &Option) -> String { for c in &s.children_at { parts.push(format!("children-at {}", c.join(" "))); } + for (f, at) in &s.views_at { + for c in at { + parts.push(format!("{f}-at {}", c.join(" ")).trim_end().to_string()); + } + } if parts.is_empty() { String::new() } else { format!(" shape({})", parts.join("; ")) } } +/// MO-11u: `hosts( catches(…) provides(…); …)`, one entry an application. +fn hosts_text(file: &str, hs: &IndexMap>) -> String { + let xs: Vec = hs + .iter() + .flat_map(|(k, sites)| { + sites.iter().map(move |x| { + format!( + "{}{}{}", + rel_key(file, k), + if x.f.is_empty_set() { String::new() } else { format!(" catches({})", cls(&x.f)) }, + match &x.p { + Catch::Set(ks) if ks.is_empty() => String::new(), + Catch::All => " provides(*)".to_string(), + Catch::Set(ks) => format!(" provides({})", sorted(ks.iter().cloned()).iter().map(|q| rel_key(file, q)).collect::>().join(", ")), + } + ) + }) + }) + .collect(); + if xs.is_empty() { String::new() } else { format!("hosts({})", xs.join("; ")) } +} +fn hosted_text(file: &str, h: &Hosted) -> String { + format!( + "export renders {} from {}:{}{}{}", + rel_key(file, &h.host), + h.r#fn, + h.line, + if h.fails.is_empty() { String::new() } else { format!(" fails({})", sorted(h.fails.iter().cloned()).join(" | ")) }, + if h.requires.is_empty() { String::new() } else { format!(" uses({})", h.requires.iter().map(|k| rel_key(file, k)).collect::>().join(", ")) } + ) + &(if h.inner.is_empty() { String::new() } else { format!(" {}", hosts_text(file, &h.inner)) }) +} +/// The text inside the balanced parentheses that open at byte `at` (the index of `(`). +fn balanced(s: &str, at: usize) -> Option<&str> { + let mut depth = 0i64; + for (i, ch) in s[at..].char_indices() { + if ch == '(' { + depth += 1; + } else if ch == ')' { + depth -= 1; + if depth == 0 { + return Some(&s[at + 1..at + i]); + } + } + } + None +} +/// 07 §2: a fn's row without its type parameters, `pure fn f(…)`, and those, as text. +fn type_params_of(s: &str) -> (String, Option) { + let Some(at) = T_FN_TPARAMS.find(s).map(|m| m.end()) else { return (s.to_string(), None) }; + let (mut depth, mut prev) = (1, '<'); + let mut end = s.len(); + for (i, ch) in s[at..].char_indices() { + if ch == '<' { + depth += 1; + } else if ch == '>' && prev != '=' { + depth -= 1; + } + prev = ch; + if depth == 0 { + end = at + i + 1; + break; + } + } + (format!("{}{}", &s[..at - 1], &s[end..]), Some(s[at - 1..end].to_string())) +} +fn hosts_of(file: &str, text: &str) -> IndexMap> { + let mut out: IndexMap> = IndexMap::new(); + for part in split(text, ';') { + let key = part.split(crate::parse::js_ws).filter(|w| !w.is_empty()).next().unwrap_or("").to_string(); + let rest = &part[key.len()..]; + let f = P_CATCHES.captures(rest).map(|c| catch_of(&c[2])).unwrap_or_else(|| Catch::Set(IndexSet::new())); + let p = match P_PROVIDES.captures(rest) { + Some(p) if crate::parse::js_trim(&p[2]) == "*" => Catch::All, + Some(p) => Catch::Set(p[2].split(',').map(|k| abs_key(file, crate::parse::js_trim(k))).filter(|x| !x.is_empty()).collect()), + None => Catch::Set(IndexSet::new()), + }; + out.entry(abs_key(file, &key)).or_default().push(HostSite { f, p }); + } + out +} +/// R-io-3: the parts of a value that are actions, among others: `{ set: io; pair.1: io; … }`; `io`: the value itself. +fn is_caller(p: &str) -> bool { + p.split('.').any(|x| x == "!") +} +fn actions_text(ps: &[String]) -> String { + if ps.is_empty() { + String::new() + } else if ps.iter().any(|p| p.is_empty()) { + "io".to_string() + } else { + // R-io-3e: a caller — where, `!`, what it calls of what it is given + format!("{{ {}; … }}", ps.iter().map(|p| format!("{p}: {}", if is_caller(p) { "calls" } else { "io" })).collect::>().join("; ")) + } +} +fn actions_of(text: &str) -> Option> { + if text == "io" { + return Some(vec![String::new()]); + } + let inner = crate::parse::js_trim(crate::parse::js_trim(text.strip_prefix('{')?.strip_suffix('}')?).strip_suffix('…')?).strip_suffix(';')?; + let ps = split(inner, ';').iter().map(|p| P_PART.captures(p).filter(|m| is_caller(&m[1]) == (&m[2] == "calls")).map(|m| m[1].to_string())).collect::>>()?; + (!ps.is_empty()).then_some(ps) +} +fn words(parts: [String; 3]) -> String { + parts.into_iter().filter(|x| !x.is_empty()).collect::>().join(" ") +} +/// MO-13i: the parts of a fn's result. +fn result_text(r: &Res) -> String { + match r { + Res::Io => "io".into(), + Res::Rec(fs) => format!("{{ {} }}", fs.iter().map(|(k, r)| format!("{k}: {}", result_text(r))).collect::>().join("; ")), + Res::Arr(xs) => format!("[{}]", xs.iter().map(result_text).collect::>().join(", ")), + Res::Leaf { reader: true, rows: r, fails, actions } => words(["ref".into(), rows(r, fails), actions_text(actions)]), + Res::Leaf { actions, .. } => words(["value".into(), String::new(), actions_text(actions)]), + } +} +fn result_of(t: &str) -> Option { + if t == "io" { + return Some(Res::Io); + } + if let Some(inner) = t.strip_prefix('{').and_then(|t| t.strip_suffix('}')) { + let fs = split(inner, ';').iter().map(|f| P_FIELD.captures(f).and_then(|m| Some((m[1].to_string(), result_of(&m[2])?)))).collect::>>()?; + return (!fs.is_empty()).then_some(Res::Rec(fs)); + } + if let Some(inner) = t.strip_prefix('[').and_then(|t| t.strip_suffix(']')) { + let xs = split(inner, ',').iter().map(|x| result_of(x)).collect::>>()?; + return (!xs.is_empty()).then_some(Res::Arr(xs)); + } + let m = P_LEAF.captures(t)?; + let rest = m.get(2).map(|x| x.as_str()).unwrap_or(""); + let r = if &m[1] == "ref" { row_words(rest) } else { RowWords { rows: vec![], fails: vec![], rest: rest.to_string() } }; + let text = if r.rows.iter().any(|x| x == "io") { "io" } else { r.rest.as_str() }; + let actions = if text.is_empty() { vec![] } else { actions_of(text)? }; + Some(Res::Leaf { reader: &m[1] == "ref", rows: r.rows.into_iter().filter(|x| x != "io").collect(), fails: r.fails, actions }) +} fn with_rows(head: String, r: String) -> String { if r.is_empty() { head } else { format!("{}: {}", head, r) } } fn line(file: &str, name: &str, x: &ExportSig) -> String { match x { - ExportSig::Source { question, rows: r, fails } => format!("{} {} …", with_rows(format!("export source {}", name), rows(r, fails)), if *question { "=" } else { ":=" }), - ExportSig::Eq { rows: r, fails, io } => { + ExportSig::Source { question, rows: r, fails, actions } => format!("{} {} …", with_rows(format!("export source {}", name), [rows(r, fails), actions_text(actions)].into_iter().filter(|x| !x.is_empty()).collect::>().join(" ")), if *question { "=" } else { ":=" }), + ExportSig::Eq { rows: r, fails, io, actions } => { let mut rr = r.clone(); if *io { rr.insert(0, "io".into()); } - with_rows(format!("export {}", name), rows(&rr, fails)) + with_rows(format!("export {}", name), words([rows(&rr, fails), if *io { String::new() } else { actions_text(actions) }, String::new()])) } - ExportSig::Fn { params, instantiating, rows: r, fails, rejects } => { - let ps: Vec = params.iter().map(|p| format!("{}{}{}", if p.r#ref { "ref " } else { "" }, p.name, p.ty.as_ref().map(|t| format!(": {}", t)).unwrap_or_default())).collect(); + ExportSig::Fn { tparams, params, instantiating, rows: r, fails, rejects, uses, actions, result, calls } => { + let parts = match result { + Some(x) => result_text(x), + None if actions.iter().any(|p| p.is_empty()) => "ref io".to_string(), + None => actions_text(actions), + }; + let ps: Vec = params.iter().map(|p| format!("{}{}{}{}", if p.r#ref { "ref " } else { "" }, p.name, if p.opt { "?" } else { "" }, p.ty.as_ref().map(|t| format!(": {}", t)).unwrap_or_default())).collect(); format!( - "{}{}{}", - with_rows(format!("export pure fn {}({})", name, ps.join(", ")), rows(r, fails)), + "{}{}{}{}{}", + with_rows(format!("export pure fn {}{}({})", name, tparams.as_deref().unwrap_or(""), ps.join(", ")), words([rows(r, fails), parts, String::new()])), if rejects.is_empty() { String::new() } else { format!(" rejects({})", rejects.join(" | ")) }, - if *instantiating { " instantiates" } else { "" } + if *instantiating { " instantiates" } else { "" }, + if uses.is_empty() { String::new() } else { format!(" uses({})", uses.iter().map(|k| rel_key(file, k)).collect::>().join(", ")) }, + if calls.is_empty() { String::new() } else { format!(" calls({})", calls.join(", ")) } ) } ExportSig::Server { io, params, rejects } => format!( @@ -224,7 +517,7 @@ fn line(file: &str, name: &str, x: &ExportSig) -> String { ), ExportSig::Action => format!("export action {}", name), ExportSig::ErrClass { params } => format!("export error {}({})", name, params.join(", ")), - ExportSig::Type => format!("export type {}", name), + ExportSig::Type(t, tp) => format!("export type {}{}", name, t.as_ref().map(|t| format!("{} = {t}", tp.as_deref().unwrap_or(""))).unwrap_or_default()), ExportSig::Context { source, dflt, rows: r, fails, ty, .. } => { let t: Vec = [if *source { "source".to_string() } else { String::new() }, rows(r, fails), ty.clone().unwrap_or_default()].into_iter().filter(|x| !x.is_empty()).collect(); let t = t.join(" "); @@ -236,6 +529,15 @@ fn line(file: &str, name: &str, x: &ExportSig) -> String { .iter() .map(|(f, v)| { let mut parts = vec![]; + if !v.takes.is_empty() { + // MO-10f: the fields it reads as ones that hold or fail + let ts: Vec = v.takes.iter().map(|(p, holds, fails)| format!("{p}{}{}", if *holds { " pending" } else { "" }, if fails.is_empty() { String::new() } else { format!(" fails({})", fails.join(" | ")) })).collect(); + parts.push(format!("takes({})", ts.join(", "))); + } + if let Some(ViewSig { optional, mixed, ty, values }) = &v.view { + // RG-4c: a view it shows; `value(…)`: what it shows it with that holds no closure of its own (O-3) + parts.push(format!("view{}{}{}{}", if *optional { "?" } else { "" }, if *mixed { " | View" } else { "" }, ty.as_ref().map(|t| format!(" {t}")).unwrap_or_default(), if values.is_empty() { String::new() } else { format!(" value({})", values.join(", ")) })); + } if !v.rendered { parts.push("unrendered".to_string()); } else { @@ -255,17 +557,23 @@ fn line(file: &str, name: &str, x: &ExportSig) -> String { if let Some((af, an)) = &v.action { parts.push(format!("action {} catches({})", an, cls(af))); } - format!("{}{}", if f == "*" { "...props" } else { f }, if parts.is_empty() { String::new() } else { format!(": {}", parts.join(" ")) }) + if v.pure { + parts.push("pure".to_string()); + } + format!("{}{}", field_text(f), if parts.is_empty() { String::new() } else { format!(": {}", parts.join(" ")) }) }) .collect(); let own: IndexSet = s.own.iter().map(|o| o.cls.clone()).collect(); format!( - "export component {}(props: {}){}{}{}{}", + "export component {}{}(props: {}){}{}{}{}{}{}", name, + s.tparams.as_deref().unwrap_or(""), if props.is_empty() { "{}".to_string() } else { format!("{{ {} }}", props.join("; ")) }, + if s.made { " made" } else { "" }, if own.is_empty() { String::new() } else { format!(" fails({})", sorted(own).join(" | ")) }, if s.requires.is_empty() { String::new() } else { format!(" uses({})", s.requires.iter().map(|k| rel_key(file, k)).collect::>().join(", ")) }, retains_text(file, &s.stored), + if s.hosts.is_empty() { String::new() } else { format!(" {}", hosts_text(file, &s.hosts)) }, shape_text(&s.shape) ) } @@ -273,10 +581,22 @@ fn line(file: &str, name: &str, x: &ExportSig) -> String { } pub fn print_signature(sig: &ModSig) -> String { - let mut out = vec![format!("// {} — signature (09-modules MO-3). Sources are read-only to importers (MO-2).", sig.file.split('/').last().unwrap_or(""))]; + let mut out = vec![format!("//@ signature {} (09-modules MO-3, MO-13a). Sources are read-only to importers (MO-2).", sig.file.split('/').last().unwrap_or(""))]; for (n, x) in &sig.exports { out.push(line(&sig.file, n, x)); } + // MO-11u + if !sig.hosts.is_empty() { + out.push(format!("export {}", hosts_text(&sig.file, &sig.hosts))); + } + for h in &sig.hosted { + out.push(hosted_text(&sig.file, h)); + } + // MO-6e: where the names are declared + for r in &sig.reexports { + let names: Vec = r.names.iter().map(|(n, a)| if n == a { n.clone() } else { format!("{n} as {a}") }).collect(); + out.push(format!("export {{ {} }} from \"{}\"", names.join(", "), r.from)); + } out.join("\n") + "\n" } @@ -286,27 +606,45 @@ pub struct SignatureError(pub String); macro_rules! re { ($name:ident, $pat:expr) => { - static $name: LazyLock = LazyLock::new(|| Regex::new($pat).unwrap()); + static $name: LazyLock = LazyLock::new(|| crate::parse::js_regex($pat)); }; } re!(ROW, r"^(io|pending|lane|fails\(([^)]*)\))$"); re!(TRAIL_COMMENT, r"\s//.*$"); re!(LEAD_COMMENT, r"^//.*$"); -re!(T_TYPE, r"^type\s+([A-Za-z_$][A-Za-z0-9_$]*)"); +re!(T_RENDERS, r"^renders\s+(\S+)\s+from\s+([A-Za-z_$][A-Za-z0-9_$.]*):(\d+)\s*(?:fails\(([^)]*)\))?\s*(?:uses\(([^)]*)\))?$"); +re!(C_HOSTS, r"(^|\s)hosts\("); +re!(R_HOSTS, r"\shosts\("); +re!(T_TYPE, r"^type\s+([A-Za-z_$][A-Za-z0-9_$]*)(?:\s*=\s*(.+))?"); +re!(T_REEXPORT, r#"^\{([^}]*)\}\s*from\s*"([^"]+)"$"#); +re!(T_REEXPORT_NAME, r"^([A-Za-z_$][A-Za-z0-9_$]*)(?:\s+as\s+([A-Za-z_$][A-Za-z0-9_$]*))?$"); re!(T_ACTION, r"^action\s+([A-Za-z_$][A-Za-z0-9_$]*)$"); re!(T_ERROR, r"^error\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*(?:\(([^)]*)\))?$"); re!(T_SOURCE, r"^source\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*(?::([^=].*?)?)??\s*(:?=)\s*…$"); re!(T_SERVER, r"^server\s+(pure\s+)?fn\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*\(([^)]*)\)\s*(?:rejects\(([^)]*)\))?$"); -re!(T_FN, r"^pure\s+fn\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*\((.*?)\)\s*(?::\s*((?:(?:io|pending|lane|fails\([^)]*\))\s*)*))?\s*(?:rejects\(([^)]*)\))?\s*(instantiates)?$"); +re!(T_FN, r"^pure\s+fn\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*\("); +re!(T_FN_TPARAMS, r"^(?:pure\s+fn|component)\s+[A-Za-z_$][A-Za-z0-9_$]*\s*<"); +re!(T_FN_ROWS, r"^\s*(?::\s*(.*?))?\s*(?:\brejects\(([^)]*)\))?\s*(\binstantiates)?\s*(?:\buses\(([^)]*)\))?\s*(?:\bcalls\(([^)]*)\))?$"); +re!(P_FIELD, r"^([A-Za-z0-9_$-]+)\s*:\s*(.+)$"); +re!(P_LEAF, r"^(ref|value)(?:\s+(.*))?$"); re!(T_CONTEXT, r"^context\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*(?::\s*(.*?))?\s*(=\s*…)?$"); -re!(T_COMP, r"^component\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*\(props:\s*(\{.*?\}|\{\})\)(.*)$"); +re!(T_COMP, r"^component\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*\("); +re!(T_PROPS, r"^props:\s*(\{.*\})$"); +re!(P_PART, r"^([A-Za-z0-9_$.*?()!-]+)\s*:\s*(io|calls)$"); re!(T_EQ, r"^([A-Za-z_$][A-Za-z0-9_$]*)\s*(?::\s*(.*))?$"); re!(P_ACTION, r"(^|[^A-Za-z0-9_])action\s+([A-Za-z_$][A-Za-z0-9_$]*)\s+catches\(([^)]*)\)"); +re!(P_PURE, r"(^|\s)pure(\s|$)"); re!(P_UNRENDERED, r"(^|[^A-Za-z0-9_])unrendered([^A-Za-z0-9_]|$)"); +re!(P_TAKES, r"(^|[^A-Za-z0-9_])takes\(((?:[^()]|\([^()]*\))*)\)"); +re!(P_VIEW, r"^view(\??)(\s*\|\s*View)?(?:\s|$)"); +re!(P_VALUE, r"^value\(([^)]*)\)"); +re!(P_PENDING, r"(^|\s)pending(\s|$)"); +re!(P_FAILS, r"fails\(([^)]*)\)"); re!(P_CATCHES, r"(^|[^A-Za-z0-9_])catches\(([^)]*)\)"); re!(P_PROVIDES, r"(^|[^A-Za-z0-9_])provides\(([^)]*)\)"); re!(C_FAILS, r"(^|[^A-Za-z0-9_])fails\(([^)]*)\)"); re!(C_USES, r"(^|[^A-Za-z0-9_])uses\(([^)]*)\)"); +re!(C_MADE, r"^\s*made\b"); re!(C_RETAINS, r"(^|[^A-Za-z0-9_])retains\(([^)]*)\)"); re!(C_SHAPE, r"(^|[^A-Za-z0-9_])shape\(([^)]*)\)"); re!(SOURCE_WORD, r"^source([^A-Za-z0-9_]|$)"); @@ -327,7 +665,7 @@ fn split(s: &str, sep: char) -> Vec { if "({[<".contains(ch) { depth += 1; } - if ")}]>".contains(ch) { + if ")}]>".contains(ch) && !(ch == '>' && cur.ends_with('=')) { depth -= 1; } if ch == sep && depth == 0 { @@ -363,11 +701,11 @@ fn row_words(s: &str) -> RowWords { RowWords { rows, fails, rest: words[i..].join(" ") } } /// SV-7d's words (MO-9b; a JS component's, MO-11a). -pub fn content_shape_of(s: Option<&str>) -> Result { +pub fn content_shape_of(s: Option<&str>, printed: bool) -> Result { let mut sh = Shape::default(); let Some(s) = s else { return Ok(sh) }; for p in s.split(';').map(crate::parse::js_trim).filter(|x| !x.is_empty()) { - let ws: Vec = p.split(char::is_whitespace).filter(|x| !x.is_empty()).map(String::from).collect(); + let ws: Vec = p.split(crate::parse::js_ws).filter(|x| !x.is_empty()).map(String::from).collect(); let (w, rest) = (ws[0].as_str(), ws[1..].to_vec()); match w { "roots" => sh.roots = rest, @@ -375,6 +713,7 @@ pub fn content_shape_of(s: Option<&str>) -> Result { "a" => sh.a = true, "form" => sh.form = true, "children-at" => sh.children_at.push(rest), + _ if printed && w.ends_with("-at") => sh.views_at.entry(w[..w.len() - 3].to_string()).or_default().push(rest), _ => return Err(format!("shape: {}", p)), } } @@ -385,6 +724,9 @@ pub fn content_shape_of(s: Option<&str>) -> Result { /// module's path: context keys are its, and relative keys resolve against it. pub fn parse_signature(src: &str, file: &str) -> Result { let mut exports = IndexMap::new(); + let mut hosts: IndexMap> = IndexMap::new(); + let mut hosted: Vec = vec![]; + let mut reexports: Vec = vec![]; for (i, raw) in src.split('\n').enumerate() { let t = TRAIL_COMMENT.replace(raw, ""); let t = LEAD_COMMENT.replace(&t, ""); @@ -397,8 +739,48 @@ pub fn parse_signature(src: &str, file: &str) -> Result return Err(fail("a signature declares exports")); } let s = crate::parse::js_trim(&t[7..]).to_string(); + // MO-6e: `export { A, B as C } from "./m.rx"` — names another module declares; an importer is sent there (the loaders) + if let Some(m) = T_REEXPORT.captures(&s) { + let mut names = vec![]; + for x in m[1].split(',').map(|x| crate::parse::js_trim(x)).filter(|x| !x.is_empty()) { + let Some(a) = T_REEXPORT_NAME.captures(x) else { return Err(fail("a re-exported name")) }; + names.push((a[1].to_string(), a.get(2).map_or_else(|| a[1].to_string(), |y| y.as_str().to_string()))); + } + if !m[2].ends_with(".rx") { + return Err(fail("only an .rx module's names are re-exported")); + } + reexports.push(Reexport { from: m[2].to_string(), names }); + continue; + } + // MO-11u + if s.starts_with("hosts(") { + let Some(inner) = balanced(&s, 5) else { return Err(fail("hosts(…)")) }; + hosts = hosts_of(file, inner); + continue; + } + // `export renders from : … hosts(…)`: the places taken out first (their entries write `provides(…)`) + let (s, inner) = match (s.starts_with("renders "), R_HOSTS.find(&s)) { + (true, Some(at)) => { + let open = at.end() - 1; + let Some(text) = balanced(&s, open) else { return Err(fail("hosts(…)")) }; + let inner = hosts_of(file, text); + let end = open + text.len() + 2; + (crate::parse::js_trim(&format!("{}{}", &s[..at.start()], &s[end..])).to_string(), inner) + } + _ => (s, IndexMap::new()), + }; + if let Some(m) = T_RENDERS.captures(&s) { + let host = abs_key(file, &m[1]); + let name = host.rsplit('#').next().unwrap_or("").to_string(); + let mut fails = classes_of(m.get(4).map(|x| x.as_str()).unwrap_or("")); + fails.sort(); + let requires = m.get(5).map(|x| x.as_str()).unwrap_or("").split(',').map(crate::parse::js_trim).filter(|k| !k.is_empty()).map(|k| abs_key(file, k)).collect(); + hosted.push(Hosted { host, name, r#fn: m[2].to_string(), line: m[3].parse().unwrap_or(1), fails, requires, inner, at: None }); + continue; + } if let Some(m) = T_TYPE.captures(&s) { - exports.insert(m[1].to_string(), ExportSig::Type); + let h = crate::modules::alias_head(&s); + exports.insert(m[1].to_string(), ExportSig::Type(h.as_ref().map(|h| h.1.to_string()), h.and_then(|h| h.0))); continue; } if let Some(m) = T_ACTION.captures(&s) { @@ -412,10 +794,9 @@ pub fn parse_signature(src: &str, file: &str) -> Result } if let Some(m) = T_SOURCE.captures(&s) { let r = row_words(m.get(2).map(|x| x.as_str()).unwrap_or("")); - if !r.rest.is_empty() { - return Err(fail("a source's rows")); - } - exports.insert(m[1].to_string(), ExportSig::Source { question: &m[3] == "=", rows: r.rows, fails: r.fails }); + let acts = if r.rows.iter().any(|x| x == "io") { Some(vec![String::new()]) } else if r.rest.is_empty() { Some(vec![]) } else { actions_of(&r.rest) }; + let Some(actions) = acts else { return Err(fail("a source's rows")) }; + exports.insert(m[1].to_string(), ExportSig::Source { question: &m[3] == "=", rows: r.rows.into_iter().filter(|x| x != "io").collect(), fails: r.fails, actions }); continue; } if let Some(m) = T_SERVER.captures(&s) { @@ -423,23 +804,35 @@ pub fn parse_signature(src: &str, file: &str) -> Result exports.insert(m[2].to_string(), ExportSig::Server { io: m.get(1).is_none(), params, rejects: classes_of(m.get(4).map(|x| x.as_str()).unwrap_or("")) }); continue; } - if let Some(m) = T_FN.captures(&s) { - let params = split(&m[2], ',') + let (bare, tparams) = type_params_of(&s); + if let Some(m) = T_FN.captures(&bare) { + let s = &bare; + let open = m[0].len() - 1; + let Some(ps) = balanced(s, open) else { return Err(fail("a fn's parameters")) }; + let Some(t) = T_FN_ROWS.captures(&s[open + ps.len() + 2..]) else { return Err(fail("a fn's rows")) }; + let params = split(ps, ',') .into_iter() .map(|p0| { let r = REF_PARAM.is_match(&p0); let p = if r { crate::parse::js_trim(&p0[4..]).to_string() } else { p0.clone() }; - match p.find(':') { - None => SigParam { name: crate::parse::js_trim(&p).to_string(), r#ref: r, ty: None }, - Some(c) => SigParam { name: crate::parse::js_trim(&p[..c]).to_string(), r#ref: r, ty: Some(crate::parse::js_trim(&p[c + 1..]).to_string()) }, - } + let (n, ty) = match p.find(':') { + None => (crate::parse::js_trim(&p), None), + Some(c) => (crate::parse::js_trim(&p[..c]), Some(crate::parse::js_trim(&p[c + 1..]).to_string())), + }; + let opt = n.ends_with('?'); + SigParam { name: n.trim_end_matches('?').to_string(), r#ref: r, ty, opt } }) .collect(); - let r = row_words(m.get(3).map(|x| x.as_str()).unwrap_or("")); - if !r.rest.is_empty() { - return Err(fail("a fn's rows")); - } - exports.insert(m[1].to_string(), ExportSig::Fn { params, instantiating: m.get(5).is_some(), rows: r.rows, fails: r.fails, rejects: classes_of(m.get(4).map(|x| x.as_str()).unwrap_or("")) }); + let r = row_words(t.get(1).map(|x| x.as_str()).unwrap_or("")); + let text = if r.rows.iter().any(|x| x == "io") { "io" } else { r.rest.as_str() }; + // some parts of one value are actions: what else it holds is not said + let (actions, result) = match (if text == "io" { None } else { actions_of(text) }, result_of(text)) { + (Some(a), _) => (a, None), + (None, Some(x)) => (x.actions(), (!x.is_reader()).then_some(x)), + (None, None) if text.is_empty() => (vec![], None), + (None, None) => return Err(fail("a fn's rows")), + }; + exports.insert(m[1].to_string(), ExportSig::Fn { tparams, params, instantiating: t.get(3).is_some(), actions, result, rows: r.rows.iter().filter(|x| *x != "io").cloned().collect(), fails: r.fails.clone(), rejects: classes_of(t.get(2).map(|x| x.as_str()).unwrap_or("")), uses: t.get(4).map(|u| u.as_str().split(',').map(|k| abs_key(file, crate::parse::js_trim(k))).collect()).unwrap_or_default(), calls: t.get(5).map(|c| c.as_str().split(',').map(|x| crate::parse::js_trim(x).to_string()).filter(|x| !x.is_empty()).collect()).unwrap_or_default() }); continue; } if let Some(m) = T_CONTEXT.captures(&s) { @@ -455,16 +848,31 @@ pub fn parse_signature(src: &str, file: &str) -> Result ); continue; } - if let Some(m) = T_COMP.captures(&s) { - let mut sig = CompSig { own: vec![], requires: vec![], props: IndexMap::new(), shape: None, stored: IndexMap::new() }; + if let Some((m, ps)) = T_COMP.captures(&bare).and_then(|m| balanced(&bare, m.get(0).unwrap().end() - 1).filter(|p| T_PROPS.is_match(p)).map(|p| (m, p))) { + let props = T_PROPS.captures(ps).unwrap(); + let m = [String::new(), m[1].to_string(), props[1].to_string(), bare[m.get(0).unwrap().end() + ps.len() + 1..].to_string()]; + let mut sig = CompSig { tparams: tparams.clone(), made: false, own: vec![], requires: vec![], props: IndexMap::new(), shape: None, stored: IndexMap::new(), hosts: IndexMap::new(), through: false }; let inner = &m[2][1..m[2].len() - 1]; for f in split(inner, ';') { - let (fname0, spec) = match f.find(':') { - Some(c) => (crate::parse::js_trim(&f[..c]).to_string(), crate::parse::js_trim(&f[c + 1..]).to_string()), - None => (crate::parse::js_trim(&f).to_string(), String::new()), - }; - let fname = if fname0 == "...props" { "*".to_string() } else { fname0 }; - let mut v = PropSig { f: Catch::Set(IndexSet::new()), p: Catch::Set(IndexSet::new()), rendered: true, action: None, component: false }; + let (fname, spec) = field_of(&f); + let mut v = PropSig { f: Catch::Set(IndexSet::new()), p: Catch::Set(IndexSet::new()), rendered: true, pure: false, action: None, component: false, components: false, takes: vec![], view: None }; + let mut spec = spec; + if let Some(m) = P_VIEW.captures(&spec) { + // RG-4c + let mut view = ViewSig { optional: !m[1].is_empty(), mixed: m.get(2).is_some(), ty: None, values: vec![] }; + let mut at = spec[m.get(0).unwrap().end()..].js_trim().to_string(); + if at.starts_with('{') { + let end = crate::parse::closes(&at, 0).unwrap_or(at.len()); + view.ty = Some(at[..end].to_string()); + at = at[end..].js_trim().to_string(); + } + if let Some(x) = P_VALUE.captures(&at) { + view.values = x[1].split(',').map(|x| x.js_trim().to_string()).filter(|x| !x.is_empty()).collect(); + at = at[x.get(0).unwrap().end()..].js_trim().to_string(); + } + v.view = Some(view); + spec = at; + } let a = P_ACTION.captures(&spec); let rest = match &a { Some(a) => { @@ -476,6 +884,22 @@ pub fn parse_signature(src: &str, file: &str) -> Result } None => spec.clone(), }; + if let Some(t) = P_TAKES.captures(&rest) { + // `takes(data pending fails(Error), result.more pending)` + for part in split(&t[2], ',') { + let part = crate::parse::js_trim(&part); + let path = part.split(crate::parse::js_ws).filter(|w| !w.is_empty()).next().unwrap_or("").to_string(); + let holds = P_PENDING.is_match(part); + let fails = P_FAILS.captures(part).map(|f| f[1].split('|').map(|c| c.js_trim().to_string()).filter(|c| !c.is_empty()).collect()).unwrap_or_default(); + if !path.is_empty() { + v.takes.push((path, holds, fails)); + } + } + } + let rest = P_TAKES.replace(&rest, "$1").to_string(); + if P_PURE.is_match(&rest) { + v.pure = true; + } if P_UNRENDERED.is_match(&rest) { v.rendered = false; v.f = Catch::All; @@ -493,37 +917,47 @@ pub fn parse_signature(src: &str, file: &str) -> Result } sig.props.insert(fname, v); } - let tail = &m[3]; + // MO-11u: `hosts(…)` is taken out of the tail first — its entries write `catches(…)` and `provides(…)` + let mut tail_owned = m[3].to_string(); + if let Some(at) = C_HOSTS.find(&tail_owned) { + let open = at.end() - 1; + let Some(inner) = balanced(&tail_owned, open) else { return Err(fail("hosts(…)")) }; + sig.hosts = hosts_of(file, inner); + let end = open + inner.len() + 2; + tail_owned = format!("{}{}", &tail_owned[..at.start()], &tail_owned[end..]); + } + let tail = tail_owned.as_str(); if let Some(fl) = C_FAILS.captures(tail) { let at = file.split('/').last().map(String::from); sig.own = classes_of(&fl[2]).into_iter().map(|c| Own { cls: c, what: format!("{}'s root", &m[1]), at: at.clone() }).collect(); } + if C_MADE.is_match(tail) { + sig.made = true; // MO-11j + } if let Some(us) = C_USES.captures(tail) { sig.requires = us[2].split(',').map(|k| abs_key(file, crate::parse::js_trim(k))).collect(); } if let Some(so) = C_RETAINS.captures(tail) { for x in split(&so[2], ',') { - let i = x.find(':').unwrap_or(x.len()); - let f0 = crate::parse::js_trim(&x[..i]).to_string(); - let f = if f0 == "...props" { "*".to_string() } else { f0 }; - let t = crate::parse::js_trim(x.get(i + 1..).unwrap_or("")).to_string(); + let (f, t) = field_of(&x); sig.stored.entry(f).or_default().push(if t == "module" { t } else { abs_key(file, &t) }); } } - sig.shape = Some(content_shape_of(C_SHAPE.captures(tail).map(|x| x.get(2).unwrap().as_str())).map_err(|e| fail(&e))?); + sig.shape = Some(content_shape_of(C_SHAPE.captures(tail).map(|x| x.get(2).unwrap().as_str()), true).map_err(|e| fail(&e))?); exports.insert(m[1].to_string(), ExportSig::Comp { sig }); continue; } if let Some(m) = T_EQ.captures(&s) { let r = row_words(m.get(2).map(|x| x.as_str()).unwrap_or("")); - if !r.rest.is_empty() { + let actions = actions_of(&r.rest); + if !r.rest.is_empty() && actions.is_none() { return Err(fail("an equation's rows")); } let io = r.rows.iter().any(|x| x == "io"); - exports.insert(m[1].to_string(), ExportSig::Eq { rows: r.rows.into_iter().filter(|x| x != "io").collect(), fails: r.fails, io }); + exports.insert(m[1].to_string(), ExportSig::Eq { rows: r.rows.into_iter().filter(|x| x != "io").collect(), fails: r.fails, io, actions: actions.unwrap_or_default() }); continue; } return Err(fail("not an export")); } - Ok(ModSig { file: file.into(), exports }) + Ok(ModSig { file: file.into(), exports, hosted, hosts, reexports }) } diff --git a/compiler/src/spans.rs b/compiler/src/spans.rs index 9eac036b1..9224ea3e4 100644 --- a/compiler/src/spans.rs +++ b/compiler/src/spans.rs @@ -1,7 +1,7 @@ //! What the parser's spans promise (spec/11 CP-8), checked on a parsed program: each span is inside the source and inside -//! its parent's, a declaration's and a markup item's span starts on the line the node records, and a leaf's span is the -//! text it was parsed from (a name is its name, a member ends with its property). `ref/crate.ts` runs this on every -//! program; an editor's positions are only as good as these. +//! its parent's, and a leaf's span is the text it was parsed from (a name is its name, a member ends with its property). `ref/crate.ts` runs this on every +//! program; an editor's positions are only as good as these. A node's line is its span's (rsvelte P4: no node records +//! one beside it), so the line checks this held before (CP-8b) hold by construction. use crate::ast::*; @@ -52,12 +52,9 @@ impl Spans<'_> { fn decl(&mut self, d: &Decl, parent: Span) { let at = d.span(); if !self.inside(at, parent, "declaration") { - self.bad(at, format!("a {} declaration has no span", d.to_json()["k"])); + self.bad(at, format!("a \"{}\" declaration has no span", d.kind())); return; } - if at.line(self.src) != d.line() { - self.bad(at, format!("declaration on line {}, its span starts on line {}", d.line(), at.line(self.src))); - } if let Some(n) = d.name() { self.word_in(at, n, "the declared name"); } @@ -116,6 +113,11 @@ impl Spans<'_> { self.stmts(t, at); self.stmts(f, at); } + StmtKind::For { name, e, body } => { + self.word_in(at, name, "the bound name"); + self.expr(e, at); + self.stmts(body, at); + } StmtKind::Try { body, handler, fin, .. } => { self.stmts(body, at); handler.iter().for_each(|h| self.stmts(h, at)); @@ -140,7 +142,8 @@ impl Spans<'_> { ExprKind::Member { p, .. } if !text.ends_with(p.as_str()) => self.bad(at, format!("the member `.{p}` spans `{text}`")), ExprKind::Use(n) | ExprKind::Pre { name: n, .. } => self.word_in(at, n, "the name"), ExprKind::Lit(Lit::Str(_)) if !(text.starts_with('"') || text.starts_with('\'')) => self.bad(at, format!("a string spans `{text}`")), - ExprKind::Lit(Lit::Num(_)) if !text.starts_with(|c: char| c.is_ascii_digit()) => self.bad(at, format!("a number spans `{text}`")), + ExprKind::Lit(Lit::Num(_) | Lit::BigInt(_)) if !text.starts_with(|c: char| c.is_ascii_digit() || c == '.') => self.bad(at, format!("a number spans `{text}`")), + ExprKind::Lit(Lit::Regex(..)) if !text.starts_with('/') => self.bad(at, format!("a regular expression spans `{text}`")), _ => {} } let mut sub = |x: &Expr| self.expr(x, at); @@ -171,7 +174,7 @@ impl Spans<'_> { sub(o); sub(i); } - ExprKind::Call { f, args } => { + ExprKind::Call { f, args, .. } => { sub(f); args.iter().for_each(&mut sub); } @@ -206,20 +209,12 @@ impl Spans<'_> { fn markup(&mut self, m: &Markup, parent: Span) { let at = m.span; if !self.inside(at, parent, "markup") { - // made by the parser: the space between two texts, and a module's view of its default component (MO-1c) - if m.line.is_some() && !matches!(m.kind, MarkupKind::El { .. }) { - self.bad(parent, "a markup item has no span".into()); - } - return; - } - if let Some(l) = m.line { - if at.line(self.src) != l { - self.bad(at, format!("markup on line {l}, its span starts on line {}", at.line(self.src))); - } + return; // made by a pass } match &m.kind { MarkupKind::El { tag, attrs, children } => { - if !tag.is_empty() && !at.text(self.src)[1..].starts_with(tag.as_str()) { + // MO-6d: a namespace's member, `Select$Item`, is written `Select.Item` + if !tag.is_empty() && !at.text(self.src)[1..].starts_with(tag.as_str()) && !at.text(self.src)[1..].starts_with(tag.replacen('$', ".", 1).as_str()) { self.bad(at, format!("the element <{tag}> spans `{}`", at.text(self.src))); } for a in attrs { @@ -231,7 +226,7 @@ impl Spans<'_> { self.markups(children, at); } MarkupKind::Read(e) => self.expr(e, at), - MarkupKind::Text(t) if at.text(self.src) != t => self.bad(at, format!("the text {t:?} spans {:?}", at.text(self.src))), + MarkupKind::Text(t) if crate::parse::jsx_text(at.text(self.src)) != *t => self.bad(at, format!("the text {t:?} spans {:?}", at.text(self.src))), MarkupKind::Text(_) | MarkupKind::Style(_) => {} MarkupKind::Mif { c, t, t_decls, f, f_decls } => { self.expr(c, at); @@ -240,8 +235,21 @@ impl Spans<'_> { self.decls(f_decls, at); self.markups(f, at); } - MarkupKind::Mfor { name, xs, decls, body } => { + MarkupKind::Mview { prop, params, decls, body } => { + if let Some(p) = prop { + self.word_in(at, p, "the render prop"); + } + for p in params { + self.word_in(at, p, "the bound name"); + } + self.decls(decls, at); + self.markups(body, at); + } + MarkupKind::Mfor { name, index, xs, decls, body } => { self.word_in(at, name, "the bound name"); + if let Some(i) = index { + self.word_in(at, i, "the bound index"); + } self.expr(xs, at); self.decls(decls, at); self.markups(body, at); @@ -274,35 +282,107 @@ fn is_word(c: char) -> bool { pub fn check_spans(src: &str, p: &Program) -> Vec { let mut s = Spans { src, out: vec![] }; s.decls(&p.decls, Span::NONE); - s.markups(&p.view, Span::NONE); + match (p.legacy_view, &p.view[..]) { + // MO-1c: the view of a module with a default component is that component, applied — written where it is declared + (None, [m]) => { + let ok = p.decls.iter().any(|d| matches!(d, Decl::Component { is_default: true, name, .. } if d.span() == m.span && matches!(&m.kind, MarkupKind::El { tag, .. } if tag == name))); + if !ok { + s.bad(m.span, "the view of a module's default component is not where the component is".into()); + } + } + _ => s.markups(&p.view, Span::NONE), + } + p.names.iter().for_each(|&l| _ = s.inside(l, Span::NONE, "a name's span")); // each leaf a range of the source (CP-8a) s.out } -/// The range a diagnostic on `line` covers (the checker is line-precise, CN-1a): from where the first node that starts on -/// that line starts, to the furthest any such node reaches on it; the line's text when no node starts there. -pub fn line_range(src: &str, p: &Program, line: usize) -> Option { - let (mut ls, mut n) = (0usize, 1usize); - while n < line { - ls = ls + src[ls..].find('\n')? + 1; - n += 1; +/// Where a text's lines end, read once (`LineIndex`), with the text: a place's line and column, and a line's place, without +/// reading from the top. +pub struct Lines<'a> { + src: &'a str, + ix: std::sync::Arc, +} +impl<'a> Lines<'a> { + pub fn new(src: &'a str) -> Self { + Lines { src, ix: std::sync::Arc::new(LineIndex::new(src)) } } - let le = src[ls..].find('\n').map(|j| ls + j).unwrap_or(src.len()); - let mut r: Option<(u32, u32)> = None; - let mut take = |at: Span| { - if !at.is_none() && (at.start as usize) >= ls && (at.start as usize) <= le { - let end = at.end.min(le as u32); - r = Some(r.map_or((at.start, end), |(a, b)| (a.min(at.start), b.max(end)))); + /// `src`'s lines, read before (a program's `lines`). + pub fn with(src: &'a str, ix: std::sync::Arc) -> Self { + Lines { src, ix } + } + pub fn index(&self) -> std::sync::Arc { + self.ix.clone() + } + /// The 1-based line a byte offset is on. + pub fn line(&self, at: usize) -> usize { + self.ix.line(at as u32) + } + /// Where a line starts and where its text ends (before its `\n`, `\r\n` or `\r`, or the end of the text); None when + /// there are fewer. + fn range(&self, line: usize) -> Option<(usize, usize)> { + let ends = self.ix.ends(); + (line <= ends.len() + 1).then(|| (if line < 2 { 0 } else { ends[line - 2] as usize + 1 }, self.end(line))) + } + fn end(&self, line: usize) -> usize { + match self.ix.ends().get(line - 1).map(|&e| e as usize) { + Some(e) if e > 0 && self.src.as_bytes()[e] == b'\n' && self.src.as_bytes()[e - 1] == b'\r' => e - 1, + Some(e) => e, + None => self.src.len(), } - }; - walk(p, &mut take); - if let Some((a, b)) = r { - let t = src[a as usize..b as usize].trim_end(); - return Some(Span::new(a as usize, a as usize + t.len())); } - let text = &src[ls..le]; - let t = text.trim_start(); - let a = ls + (text.len() - t.len()); - Some(Span::new(a, a + t.trim_end().len())) + /// A byte offset as a 1-based line and 0-based column in UTF-16 code units (what LSP and TypeScript count). An offset + /// on a line's end is the column past its text (CP-8h: the `\r` of `\r\n` is not a column), and a leading byte-order + /// mark is not one either: the column is the one an editor shows, which holds the text without it. + pub fn line_col(&self, at: usize) -> (usize, usize) { + let at = at.min(self.src.len()); + let line = self.line(at); + let (ls, le) = self.range(line).unwrap_or((0, self.src.len())); + let ls = if line == 1 { ls.max(crate::parse::bom_len(self.src)) } else { ls }; + let at = at.min(le); + (line, if at <= ls { 0 } else { self.src[ls..at].encode_utf16().count() }) + } + /// `at` and the end of its line, less the white space there. + pub fn rest(&self, at: usize) -> (usize, usize) { + let at = at.min(self.src.len()); + (at, at + self.src[at..self.end(self.line(at)).max(at)].trim_end().len()) + } +} + +/// The ranges a program's diagnostics cover. +pub struct Ranges<'a> { + pub lines: Lines<'a>, + /// per line: from where the first node that starts on it starts, to the furthest any such node reaches on it + nodes: Vec>, +} +impl<'a> Ranges<'a> { + pub fn new(src: &'a str, p: &Program) -> Self { + let lines = Lines::with(src, p.lines.clone()); + let mut nodes = vec![None; lines.ix.count() + 1]; + walk(p, &mut |at: Span| { + if !at.is_none() && at.start as usize <= src.len() { + let line = lines.line(at.start as usize); + let end = at.end.min(lines.end(line) as u32).max(at.start); + let r = &mut nodes[line - 1]; + *r = Some(r.map_or((at.start, end), |(a, b): (u32, u32)| (a.min(at.start), b.max(end)))); + } + }); + Ranges { lines, nodes } + } + /// The range a diagnostic on `line` covers (the checker is line-precise, CN-1a): its nodes' (`nodes`); the line's text + /// when no node starts there. + pub fn of(&self, line: usize) -> Option { + let src = self.lines.src; + let (ls, le) = self.lines.range(line)?; + if let Some((a, b)) = self.nodes[line.max(1) - 1] { + let t = src[a as usize..b as usize].trim_end(); + return Some(Span::new(a as usize, a as usize + t.len())); + } + let ls = if line <= 1 { ls.max(crate::parse::bom_len(src)).min(le) } else { ls }; + let text = &src[ls..le]; + let t = text.trim_start(); + let a = ls + (text.len() - t.len()); + Some(Span::new(a, a + t.trim_end().len())) + } } /// Every span `p` holds: declarations, statements, expressions, markup and attributes. @@ -344,6 +424,10 @@ pub fn walk(p: &Program, f: &mut dyn FnMut(Span)) { expr(c, f); t.iter().chain(e).for_each(|s| stmt(s, f)); } + StmtKind::For { e, body, .. } => { + expr(e, f); + body.iter().for_each(|s| stmt(s, f)); + } StmtKind::Try { body, handler, fin, .. } => body.iter().chain(handler.iter().flatten()).chain(fin.iter().flatten()).for_each(|s| stmt(s, f)), } } @@ -360,7 +444,7 @@ pub fn walk(p: &Program, f: &mut dyn FnMut(Span)) { ExprKind::Tpl(parts) => sub.extend(parts.iter().filter_map(|p| if let TplPart::Expr(x) = p { Some(x) } else { None })), ExprKind::Member { o, .. } => sub.push(o), ExprKind::Index { o, i, .. } => sub.extend([&**o, &**i]), - ExprKind::Call { f, args } => sub.extend(std::iter::once(&**f).chain(args.iter())), + ExprKind::Call { f, args, .. } => sub.extend(std::iter::once(&**f).chain(args.iter())), ExprKind::Arr(items) => sub.extend(items.iter()), ExprKind::Rec(fields) => sub.extend(fields.iter().map(|x| match x { Field::Kv { v, .. } => v, @@ -390,6 +474,7 @@ pub fn walk(p: &Program, f: &mut dyn FnMut(Span)) { MarkupKind::Text(_) | MarkupKind::Style(_) => (vec![], vec![], vec![]), MarkupKind::Mif { c, t, t_decls, f: fm, f_decls } => (t_decls.iter().chain(f_decls).collect(), t.iter().chain(fm).collect(), vec![c]), MarkupKind::Mfor { xs, decls, body, .. } => (decls.iter().collect(), body.iter().collect(), vec![xs]), + MarkupKind::Mview { decls, body, .. } => (decls.iter().collect(), body.iter().collect(), vec![]), MarkupKind::Loading { on, fallback, decls, body } => (decls.iter().collect(), fallback.iter().chain(body).collect(), on.iter().collect()), MarkupKind::Errored { fallback, decls, body, .. } => (decls.iter().collect(), fallback.iter().chain(body).collect(), vec![]), MarkupKind::Portal { to, decls, body } => (decls.iter().collect(), body.iter().collect(), to.iter().collect()), @@ -402,13 +487,6 @@ pub fn walk(p: &Program, f: &mut dyn FnMut(Span)) { p.view.iter().for_each(|m| markup(m, f)); } -/// A byte offset as a 1-based line and 0-based column in UTF-16 code units (what LSP and TypeScript count). -pub fn line_col(src: &str, at: u32) -> (usize, usize) { - let at = (at as usize).min(src.len()); - let ls = src[..at].rfind('\n').map(|i| i + 1).unwrap_or(0); - (src[..ls].matches('\n').count() + 1, src[ls..at].encode_utf16().count()) -} - #[cfg(test)] mod tests { use super::*; @@ -431,8 +509,15 @@ mod tests { } } assert_eq!(check_spans(src, &p).len(), 2); - let r = line_range(src, &p, 4).unwrap(); + let ranges = Ranges::new(src, &p); + let r = ranges.of(4).unwrap(); assert_eq!(r.text(src), "count := count + 1"); - assert_eq!(line_col(src, r.start), (4, 2)); + assert_eq!(ranges.lines.line_col(r.start as usize), (4, 2)); + // a statement's line is its span's (no node stores one): a statement spanned a line late is caught by its text + let Decl::Action { body, span, .. } = &mut p.decls[2] else { panic!() }; + let close = src[..span.end as usize].rfind('}').unwrap(); + body[0].span = Span::new(close, span.end as usize); + assert_eq!(p.line(p.decls[2].span()), 3); + assert!(check_spans(src, &p).iter().any(|e| e.contains("(line 5): the written name `count` is not in its text")), "{:?}", check_spans(src, &p)); } } diff --git a/compiler/src/tsx.rs b/compiler/src/tsx.rs new file mode 100644 index 000000000..e25fac73a --- /dev/null +++ b/compiler/src/tsx.rs @@ -0,0 +1,1652 @@ +//! TY-1, CP-8c: the TSX projection as a tree of its own, and the printer that writes it and records, as it writes, what each +//! printed piece is of the `.rx` (spec/archive/projection-printer-2026-11-29.md says why this way and not another; it +//! replaced an `oxc_ast` tree printed by oxc's codegen and parsed back, spec/archive/projection-tree-2026-11-29.md). +//! +//! **Keys.** Every node the projection builds that may be something of the `.rx` has a key, `k`, the order it was built in; +//! `Place` says what it is: text that is the same on both sides (a name, a literal, a written type: `copy`, a CP-8c +//! mapping), text written for a node of the `.rx` (`atom`, a range), or helper text written on purpose with no place +//! (`design`). Most nodes are the projection's own and keep nothing but their key (`slot_of[k]` is `NONE`). +//! +//! **The printer records as it writes** (rsvelte's `Emitter`): a placed node's printed extent is where its first token +//! starts and its last ends, and the parentheses it is printed in, when the printer adds them, are a second range from the +//! parenthesis (TypeScript reports an error on `(a + b)` there). Its layout is the one oxc's codegen gave this tree (two +//! spaces, the same parentheses, `` in TSX, an object of two fields a field a line), so the projection's text did not +//! move when the printer did; nothing is read back from the text. +//! +//! **Raw text.** A written type, a type parameter list, a literal as the projection writes it, are text in the `.rx` tree +//! (07 §2) and are printed as they are: a name whose text is the text (`raw`, `raw_type`). + +use crate::ast::Span as RxSpan; + +/// One mapping: `len` bytes at `gen` in the projection are the same text as `len` bytes at `src` in the `.rx`. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Mapping { + pub gen: u32, + pub src: u32, + pub len: u32, +} + +/// A coarser correspondence: `glen` bytes at `gen` in the projection were written for the `len` bytes at `src` (an +/// expression, a statement, a declaration), not the same text. An editor maps through it what falls between mappings (a +/// type error on `(a + b)` starts at its parenthesis); it is listed innermost first. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Range { + pub gen: u32, + pub glen: u32, + pub src: u32, + pub len: u32, +} + +/// The node of the `.rx` syntax tree a mapping is the text of, and whether it was found by its text in that node (a name +/// a node holds as a string) or placed by a span. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Of { + pub node: RxSpan, + pub found: bool, +} + +/// Text the same on both sides: `len` bytes of the `.rx` at `src`, starting `lead` bytes before the node's own start in the +/// print (a member's `.p`: its dot is the node's parent's). +#[derive(Debug, Clone, Copy)] +pub struct Copy { + pub lead: u32, + pub src: u32, + pub len: u32, + pub of: Of, +} + +/// What a node is of the `.rx`. +#[derive(Debug, Clone, Copy, Default)] +pub struct Place { + pub copy: Option, + /// a range: the node's printed text was written for this span of the `.rx` + pub atom: Option, + /// helper text the projection writes on purpose with no place in the `.rx` (the prelude's imports, the entry's mount, a + /// slot bound again after an `await`): listed as such (`Printed::generated`), so a check of the names in a projection + /// tells it from a name left unmapped + pub design: bool, +} +impl Place { + pub const GEN: Place = Place { copy: None, atom: None, design: false }; + pub const DESIGN: Place = Place { copy: None, atom: None, design: true }; + pub fn atom(sp: RxSpan) -> Place { + Place { atom: (!sp.is_none()).then_some(sp), ..Place::GEN } + } + /// `text` at `src` in the `.rx`, of node `of` (nothing when `src` is not known). + pub fn copy(text: &str, src: Option, of: Of) -> Place { + Place { copy: src.map(|s| Copy { lead: 0, src: s as u32, len: text.len() as u32, of }), ..Place::GEN } + } + /// Nothing of the `.rx`: a helper (kept for no node). + fn is_gen(&self) -> bool { + self.copy.is_none() && self.atom.is_none() && !self.design + } + pub fn with_atom(mut self, sp: RxSpan) -> Place { + if !sp.is_none() { + self.atom = Some(sp); + } + self + } +} + +/// A node's key: the order it was built in. +pub type K = u32; +const NONE: u32 = u32::MAX; + +// ---- the tree ---- + +/// A name, a raw text, a string literal's value: a leaf with a key. +pub struct Name { + pub k: K, + pub text: Box, +} + +/// A type the projection writes: a written type as text (`T`), or `typeof x`. +pub enum Ty { + Raw(Name), + Query(Name), +} +pub struct Param { + pub name: Name, + pub optional: bool, + pub ty: Option, +} +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Un { + Not, + Neg, + Plus, + Typeof, + BitNot, + Void, + Delete, +} +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Op { + And, + Or, + Coalesce, + Bin(&'static str), +} +pub enum Ex { + /// a name read, or raw text (a literal, a name that is not one word) + Id(Name), + Null(K), + Bool(K, bool), + Member(K, Box, Name, bool), + Computed(K, Box, Box, bool), + Call(K, Box, Option>, Vec), + /// `new f(args)`: 10 SV-7a's `new Date(…)` + New(K, Box, Vec), + /// `l = r`: 02 W-1c's local written again + Assign(K, Box, Box), + Arrow(K, Box), + Array(K, Vec), + Object(K, Vec), + Unary(K, Un, Box), + Bin(K, Op, Box, Box), + Cond(K, Box, Box, Box), + Seq(K, Vec), + Await(K, Box), + As(K, Box, Ty), + NonNull(K, Box), + /// an optional chain: its links one chain (as a parser reads `a?.b.c`) + Chain(K, Box), + Tpl(K, Vec>, Vec), + El(Box), + Frag(K, Vec), +} +pub enum Arg { + Ex(Ex), + Spread(K, Ex), +} +pub enum Prop { + /// `"key": v` (a string, so it is never shortened to `key`) + Kv(Name, Ex), + Spread(Ex), +} +pub struct Arrow { + pub is_async: bool, + pub params: Vec, + pub ret: Option, + pub body: Body, +} +pub enum Body { + Ex(Ex), + Block(Vec), +} +pub struct El { + pub k: K, + pub tag: Tag, + pub attrs: Vec, + /// the children and the closing tag (none: ``) + pub kids: Option<(Vec, Tag)>, +} +pub enum Tag { + /// lowercase or hyphenated: an intrinsic element's name + Ident(Name), + Ref(Name), + /// `Kit.Part.Sub` + Member(Name, Vec), +} +pub enum AttrName { + Id(Name), + Ns(Name, Name), +} +pub enum Attr { + Attr(AttrName, Option), + Spread(Ex), +} +pub enum Child { + Text(K, Box), + /// `{x}` + Ex(K, Ex), + El(Box), + Frag(K, Vec), +} +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum VarKind { + Const, + Let, +} +pub struct VarDecl { + pub k: K, + pub kind: VarKind, + pub declare: bool, + pub name: Name, + pub ty: Option, + pub init: Option, +} +pub struct Func { + pub k: K, + pub is_async: bool, + pub name: Name, + /// ``: a type parameter list written as text, between the printer's brackets + pub tparams: Option, + pub params: Vec, + pub ret: Option, + pub body: Vec, +} +pub enum Decl { + Var(VarDecl), + Fn(Box), + Type(K, Name, Ty), +} +pub enum Spec { + Default(Name), + Ns(Name), + /// the imported name and the local one + Named(Name, Name), +} +pub enum St { + Expr(K, Ex), + Decl(Decl), + Ret(K, Option), + Throw(K, Ex), + If(Ex, Vec, Vec), + ForOf(Name, Ex, Vec), + /// `try`, its `catch (name)`, its `finally` + Try(Vec, Option<(Name, Vec)>, Option>), + Block(Vec), + Import(K, bool, Vec, Name), + /// `export { local as exported } from "…"` + ExportFrom(Vec<(Name, Name)>, Name), + ExportDefault(Ex), + Export(K, Decl), + /// a statement written as text, the printer's `;` after it + Raw(Name), +} + +impl Ex { + pub fn key(&self) -> K { + match self { + Ex::Id(n) => n.k, + Ex::El(e) => e.k, + Ex::Null(k) + | Ex::Bool(k, _) + | Ex::Member(k, ..) + | Ex::Computed(k, ..) + | Ex::Call(k, ..) + | Ex::New(k, ..) + | Ex::Assign(k, ..) + | Ex::Arrow(k, _) + | Ex::Array(k, _) + | Ex::Object(k, _) + | Ex::Unary(k, ..) + | Ex::Bin(k, ..) + | Ex::Cond(k, ..) + | Ex::Seq(k, _) + | Ex::Await(k, _) + | Ex::As(k, ..) + | Ex::NonNull(k, _) + | Ex::Chain(k, _) + | Ex::Tpl(k, ..) + | Ex::Frag(k, _) => *k, + } + } +} +impl Child { + pub fn key(&self) -> K { + match self { + Child::Text(k, _) | Child::Ex(k, _) | Child::Frag(k, _) => *k, + Child::El(e) => e.k, + } + } +} + +/// A placed node: what it is of the `.rx`, and (once printed) its extent and the parentheses the printer put around it. +struct Slot { + place: Place, + start: u32, + end: u32, + wrap: Option<(u32, u32)>, + printed: bool, +} + +/// The builder: the keys handed out so far, and the places of those that are something of the `.rx` (most nodes are +/// helpers, and keep nothing but their key). +#[derive(Default)] +pub struct Tsx { + slot_of: std::cell::RefCell>, + slots: std::cell::RefCell>, + /// copies inside one raw node's text (a props type written in pieces): `(key, offset in its text, copy)` + pieces: std::cell::RefCell>, + /// a node's ranges after its first (`latest x` is `x`'s node, written for both) + atoms: std::cell::RefCell>, +} + +impl Tsx { + pub fn new() -> Self { + Self::default() + } + /// A key of its own for a node that is `p`. + pub fn key(&self, p: Place) -> K { + let mut so = self.slot_of.borrow_mut(); + let k = so.len() as K; + if p.is_gen() { + so.push(NONE); + } else { + let mut ss = self.slots.borrow_mut(); + so.push(ss.len() as u32); + ss.push(Slot { place: p, start: 0, end: 0, wrap: None, printed: false }); + } + k + } + /// The projection's own node (a range or a mark added to one later, `set_atom`, `set_design`, gives it a place). + pub fn gen(&self) -> K { + self.key(Place::GEN) + } + /// The place of node `k`, made when it has none. + fn place_mut(&self, k: K, f: impl FnOnce(&mut Place) -> R) -> R { + let mut so = self.slot_of.borrow_mut(); + let mut ss = self.slots.borrow_mut(); + let i = so[k as usize]; + let i = if i == NONE { + so[k as usize] = ss.len() as u32; + ss.push(Slot { place: Place::GEN, start: 0, end: 0, wrap: None, printed: false }); + ss.len() - 1 + } else { + i as usize + }; + f(&mut ss[i].place) + } + fn atom_of(&self, k: K) -> Option { + let i = self.slot_of.borrow()[k as usize]; + (i != NONE).then(|| self.slots.borrow()[i as usize].place.atom).flatten() + } + /// Adds a range onto `sp` to a node already built (what an expression is written as; a node written for two, both). + pub fn set_atom(&self, node: K, sp: RxSpan) { + if sp.is_none() { + return; + } + self.place_mut(node, |p| match p.atom { + None => p.atom = Some(sp), + Some(a) if a != sp => self.atoms.borrow_mut().push((node, sp)), + Some(_) => {} + }); + } + /// Marks a node already built as written by design with no place in the `.rx` (`Place::design`). + pub fn set_design(&self, node: K) { + self.place_mut(node, |p| p.design = true); + } + + // ---- leaves ---- + pub fn name(&self, text: &str, p: Place) -> Name { + Name { k: self.key(p), text: text.into() } + } + /// A name read (`x`), `p` what it is of the `.rx`. + pub fn id(&self, name: &str, p: Place) -> Ex { + Ex::Id(self.name(name, p)) + } + pub fn id_ref(&self, name: &str, p: Place) -> Name { + self.name(name, p) + } + pub fn bind(&self, name: &str, p: Place) -> Name { + self.name(name, p) + } + /// Text printed as it is, as an expression. + pub fn raw(&self, text: &str, p: Place) -> Ex { + self.id(text, p) + } + /// Text printed as it is, as a type; `pieces`: the copies inside it, by offset in `text`. + pub fn raw_type(&self, text: &str, p: Place, pieces: &[(u32, Copy)]) -> Ty { + let n = self.name(text, p); + if !pieces.is_empty() { + // (placed: the copies inside it are read from where it is printed) + self.place_mut(n.k, |_| {}); + self.pieces.borrow_mut().extend(pieces.iter().map(|&(o, c)| (n.k, o, c))); + } + Ty::Raw(n) + } + /// `` (the brackets the printer's), a type parameter list written as text. + pub fn raw_tparams(&self, inner: &str, p: Place) -> Name { + self.name(inner, p) + } + /// `` as type arguments. + pub fn raw_targs(&self, inner: &str, p: Place) -> Vec { + vec![self.raw_type(inner, p, &[])] + } + pub fn targs(&self, ts: Vec) -> Vec { + ts + } + /// A type written by the projection: `typeof x`. + pub fn type_of(&self, name: Name) -> Ty { + Ty::Query(name) + } + pub fn string(&self, value: &str, p: Place) -> Name { + self.name(value, p) + } + pub fn null(&self) -> Ex { + Ex::Null(self.gen()) + } + pub fn bool_(&self, v: bool) -> Ex { + Ex::Bool(self.gen(), v) + } + + // ---- expressions ---- + /// `__.name`: the prelude's helper. + pub fn helper(&self, name: &str) -> Ex { + let k = self.gen(); + let o = self.id("__", Place::GEN); + Ex::Member(k, Box::new(o), self.name(name, Place::GEN), false) + } + pub fn member(&self, k: K, o: Ex, p: Name, optional: bool) -> Ex { + Ex::Member(k, Box::new(o), p, optional) + } + pub fn computed(&self, k: K, o: Ex, i: Ex, optional: bool) -> Ex { + Ex::Computed(k, Box::new(o), Box::new(i), optional) + } + pub fn call(&self, k: K, f: Ex, targs: Option>, args: Vec) -> Ex { + Ex::Call(k, Box::new(f), targs, args) + } + /// `l = r` (02 W-1c). + pub fn assign(&self, k: K, l: Ex, r: Ex) -> Ex { + Ex::Assign(k, Box::new(l), Box::new(r)) + } + /// `new f(args)` (10 SV-7a). + pub fn new_(&self, k: K, f: Ex, args: Vec) -> Ex { + Ex::New(k, Box::new(f), args) + } + /// A call of a helper: `__.name(args)`. + pub fn call_helper(&self, name: &str, targs: Option>, args: Vec) -> Ex { + let k = self.gen(); + let f = self.helper(name); + self.call(k, f, targs, args.into_iter().map(Arg::Ex).collect()) + } + pub fn spread(&self, k: K, x: Ex) -> Arg { + Arg::Spread(k, x) + } + /// A parameter: its name, whether it may be left out, its type. + pub fn param(&self, name: Name, optional: bool, ty: Option) -> Param { + Param { name, optional, ty } + } + /// `(params) => x` (or `async`). + pub fn arrow(&self, k: K, is_async: bool, ps: Vec, x: Ex) -> Ex { + Ex::Arrow(k, Box::new(Arrow { is_async, params: ps, ret: None, body: Body::Ex(x) })) + } + /// `(params) => { ss }` (or `async`). + pub fn arrow_block(&self, k: K, is_async: bool, ps: Vec, ret: Option, ss: Vec) -> Ex { + Ex::Arrow(k, Box::new(Arrow { is_async, params: ps, ret, body: Body::Block(ss) })) + } + /// `(params): T => x` + pub fn arrow_ret(&self, k: K, ps: Vec, ret: Ty, x: Ex) -> Ex { + Ex::Arrow(k, Box::new(Arrow { is_async: false, params: ps, ret: Some(ret), body: Body::Ex(x) })) + } + pub fn array(&self, k: K, xs: Vec) -> Ex { + Ex::Array(k, xs) + } + pub fn object(&self, k: K, ps: Vec) -> Ex { + Ex::Object(k, ps) + } + /// `"key": v` (a string, so the printer never shortens it to `key`). + pub fn prop(&self, key_text: &str, key: Place, v: Ex) -> Prop { + Prop::Kv(self.string(key_text, key), v) + } + pub fn spread_prop(&self, x: Ex) -> Prop { + Prop::Spread(x) + } + pub fn unary(&self, k: K, op: Un, x: Ex) -> Ex { + Ex::Unary(k, op, Box::new(x)) + } + pub fn bin(&self, k: K, op: Op, l: Ex, r: Ex) -> Ex { + Ex::Bin(k, op, Box::new(l), Box::new(r)) + } + pub fn cond(&self, k: K, c: Ex, a: Ex, b: Ex) -> Ex { + Ex::Cond(k, Box::new(c), Box::new(a), Box::new(b)) + } + pub fn seq(&self, k: K, xs: Vec) -> Ex { + Ex::Seq(k, xs) + } + pub fn await_(&self, k: K, x: Ex) -> Ex { + Ex::Await(k, Box::new(x)) + } + pub fn as_(&self, k: K, x: Ex, t: Ty) -> Ex { + Ex::As(k, Box::new(x), t) + } + pub fn non_null(&self, k: K, x: Ex) -> Ex { + Ex::NonNull(k, Box::new(x)) + } + /// A statement printed as it is (`text`; the printer's `;` after it), with a copy inside it at an offset. + pub fn raw_stmt(&self, text: &str, p: Place, piece: Option<(u32, Copy)>) -> St { + let n = self.name(text, p); + if let Some((o, c)) = piece { + self.place_mut(n.k, |_| {}); + self.pieces.borrow_mut().push((n.k, o, c)); + } + St::Raw(n) + } + /// `f(o)`, where `o` may be an optional chain (`a?.b`): the link joins its spine, which stays one chain (as a parser + /// reads `a?.b.c`); `optional`: the link itself is one (`?.`). + pub fn chain(&self, o: Ex, f: impl FnOnce(Ex) -> Ex, optional: bool) -> Ex { + let (inner, was) = match o { + Ex::Chain(ck, x) => { + // the chain's range is the link's it held + if let Some(a) = self.atom_of(ck) { + self.place_mut(x.key(), |p| { + if p.atom.is_none() { + p.atom = Some(a); + } + }); + } + (*x, true) + } + o => (o, false), + }; + let x = f(inner); + if !(was || optional) { + return x; + } + match x { + Ex::Call(..) | Ex::NonNull(..) | Ex::Computed(..) | Ex::Member(..) => Ex::Chain(self.gen(), Box::new(x)), + x => x, + } + } + /// A template literal: its texts (as written between the backticks) and the expressions between them. + pub fn template(&self, quasis: Vec, xs: Vec) -> Ex { + Ex::Tpl(self.gen(), quasis.into_iter().map(String::into_boxed_str).collect(), xs) + } + /// `<>kids` + pub fn fragment(&self, kids: Vec) -> Ex { + Ex::Frag(self.gen(), kids) + } + + // ---- statements ---- + pub fn expr_stmt(&self, k: K, x: Ex) -> St { + St::Expr(k, x) + } + /// `const|let name: T = init;` (`declare`: no init). + pub fn var(&self, k: K, kind: VarKind, name: Name, ty: Option, init: Option, declare: bool) -> St { + St::Decl(Decl::Var(self.var_decl(k, kind, name, ty, init, declare))) + } + pub fn var_decl(&self, k: K, kind: VarKind, name: Name, ty: Option, init: Option, declare: bool) -> VarDecl { + VarDecl { k, kind, declare, name, ty, init } + } + pub fn block(&self, ss: Vec) -> St { + St::Block(ss) + } + pub fn ret(&self, k: K, x: Option) -> St { + St::Ret(k, x) + } + /// A function declaration. + #[allow(clippy::too_many_arguments)] + pub fn function(&self, k: K, is_async: bool, name: Name, tparams: Option, ps: Vec, ret: Option, ss: Vec) -> Func { + Func { k, is_async, name, tparams, params: ps, ret, body: ss } + } + /// `export` before a declaration, when `export`. + pub fn exported(&self, export: bool, k: K, d: Decl) -> St { + if export { + St::Export(k, d) + } else { + St::Decl(d) + } + } + /// `type name = t;` + pub fn type_alias(&self, k: K, name: Name, t: Ty) -> Decl { + Decl::Type(k, name, t) + } + + // ---- printing ---- + /// The program of `body`, printed, with its mappings and ranges; `size`: the `.rx`'s length (the buffers' first size). + pub fn print(&self, body: &[St], size: usize) -> Printed { + let slot_of = self.slot_of.borrow(); + let mut slots = self.slots.borrow_mut(); + let mut p = Printer { + out: String::with_capacity(size * 2 + 1024), + indent: 0, + start_of_stmt: usize::MAX, + start_of_arrow: usize::MAX, + prev_op: None, + prev_op_end: usize::MAX, + slot_of: &slot_of, + slots: &mut slots, + }; + for s in body { + p.stmt(s); + } + let code = p.out; + let n = slots.len(); + let mut out = Printed { code, mappings: Vec::with_capacity(n), of: Vec::with_capacity(n), ranges: Vec::with_capacity(n), generated: vec![] }; + let ext = |s: &Slot| s.printed.then_some((s.start, s.end)); + let range = |out: &mut Printed, s: &Slot, a: RxSpan| { + if let Some((g, e)) = ext(s).filter(|(g, e)| e > g) { + out.ranges.push(Range { gen: g, glen: e - g, src: a.start, len: a.end - a.start }); + if let Some((ws, we)) = s.wrap { + out.ranges.push(Range { gen: ws, glen: we - ws, src: a.start, len: a.end - a.start }); + } + } + }; + // in the order the nodes were built + for &i in slot_of.iter().filter(|&&i| i != NONE) { + let s = &slots[i as usize]; + if let (Some(c), Some((g, _))) = (s.place.copy, ext(s)) { + out.mappings.push(Mapping { gen: g.saturating_sub(c.lead), src: c.src, len: c.len }); + out.of.push(c.of); + } + if let (true, Some((g, e))) = (s.place.design, ext(s)) { + out.generated.push((g, e - g)); + } + if let Some(a) = s.place.atom { + range(&mut out, s, a); + } + } + for &(k, a) in self.atoms.borrow().iter() { + range(&mut out, &slots[slot_of[k as usize] as usize], a); + } + for &(k, o, c) in self.pieces.borrow().iter() { + let i = slot_of[k as usize]; + if let Some((g, _)) = (i != NONE).then(|| ext(&slots[i as usize])).flatten() { + out.mappings.push(Mapping { gen: g + o, src: c.src, len: c.len }); + out.of.push(c.of); + } + } + // innermost first: of two ranges one of which holds the other, the shorter + out.ranges.sort_by_key(|r| (r.glen, r.gen)); + out + } +} + +/// A printed projection. +pub struct Printed { + pub code: String, + pub mappings: Vec, + pub of: Vec, + pub ranges: Vec, + /// `(start, length)` of the helper text written by design with no place in the `.rx` (`Place::design`) + pub generated: Vec<(u32, u32)>, +} + +/// How tightly an expression binds where it is printed (oxc_syntax's `Precedence`, which decides the same parentheses). +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +enum Prec { + Lowest, + Comma, + Yield, + Assign, + Conditional, + Coalesce, + Or, + And, + BitOr, + BitXor, + BitAnd, + Equals, + Compare, + Shift, + Add, + Multiply, + Exponent, + Prefix, + Postfix, + New, +} +impl Op { + fn prec(self) -> Prec { + match self { + Op::And => Prec::And, + Op::Or => Prec::Or, + Op::Coalesce => Prec::Coalesce, + Op::Bin(o) => match o { + "|" => Prec::BitOr, + "^" => Prec::BitXor, + "&" => Prec::BitAnd, + "==" | "!=" | "===" | "!==" => Prec::Equals, + "<" | "<=" | ">" | ">=" | "instanceof" | "in" => Prec::Compare, + "<<" | ">>" | ">>>" => Prec::Shift, + "+" | "-" => Prec::Add, + "*" | "/" | "%" => Prec::Multiply, + "**" => Prec::Exponent, + o => unreachable!("binary {o}"), + }, + } + } + /// The precedence one below this operator's. + fn lower(self) -> Prec { + match self.prec() { + Prec::Or => Prec::Coalesce, + Prec::And => Prec::Or, + Prec::Coalesce => Prec::Conditional, + Prec::BitOr => Prec::And, + Prec::BitXor => Prec::BitOr, + Prec::BitAnd => Prec::BitXor, + Prec::Equals => Prec::BitAnd, + Prec::Compare => Prec::Equals, + Prec::Shift => Prec::Compare, + Prec::Add => Prec::Shift, + Prec::Multiply => Prec::Add, + Prec::Exponent => Prec::Multiply, + p => p, + } + } + fn text(self) -> &'static str { + match self { + Op::And => "&&", + Op::Or => "||", + Op::Coalesce => "??", + Op::Bin(o) => o, + } + } +} +impl Un { + fn text(self) -> &'static str { + match self { + Un::Not => "!", + Un::Neg => "-", + Un::Plus => "+", + Un::Typeof => "typeof", + Un::BitNot => "~", + Un::Void => "void", + Un::Delete => "delete", + } + } + fn is_keyword(self) -> bool { + matches!(self, Un::Typeof | Un::Void | Un::Delete) + } +} +/// The last operator written, so that `- -x` keeps its space (oxc's `print_space_before_operator`). +#[derive(Clone, Copy, PartialEq, Eq)] +enum LastOp { + Add, + Sub, + Plus, + Neg, + Not, + Other, +} + +/// Writes the tree, and the extent of each placed node as it is written. +struct Printer<'p> { + out: String, + indent: u32, + start_of_stmt: usize, + start_of_arrow: usize, + prev_op: Option, + prev_op_end: usize, + slot_of: &'p [u32], + slots: &'p mut [Slot], +} + +impl Printer<'_> { + fn s(&mut self, s: &str) { + self.out.push_str(s); + } + fn b(&mut self, b: u8) { + self.out.push(b as char); + } + fn len(&self) -> usize { + self.out.len() + } + fn print_indent(&mut self) { + for _ in 0..self.indent { + self.out.push_str(" "); + } + } + /// A space when the text before is a name's last character (oxc's `print_space_before_identifier`). + fn space_before_ident(&mut self) { + if let Some(c) = self.out.chars().next_back() { + if c.is_ascii_alphanumeric() || c == '_' || c == '$' || (!c.is_ascii() && oxc_syntax::identifier::is_identifier_part(c)) { + self.b(b' '); + } + } + } + /// The extent of node `k` written from `entry` to here (white space around it, a layout's, is not its own). + fn close(&mut self, k: K, entry: usize) { + let i = self.slot_of[k as usize]; + if i == NONE { + return; + } + let bytes = self.out.as_bytes(); + let mut start = entry; + let mut end = bytes.len(); + while start < end && matches!(bytes[start], b' ' | b'\n') { + start += 1; + } + while end > start && matches!(bytes[end - 1], b' ' | b'\n') { + end -= 1; + } + let s = &mut self.slots[i as usize]; + s.start = start as u32; + s.end = end as u32; + s.printed = true; + } + /// The parentheses the printer put around node `k`. + fn wrapped(&mut self, k: K, open: usize) { + let i = self.slot_of[k as usize]; + if i != NONE { + self.slots[i as usize].wrap = Some((open as u32, self.out.len() as u32)); + } + } + fn leaf(&mut self, n: &Name) { + self.space_before_ident(); + let entry = self.len(); + self.s(&n.text); + self.close(n.k, entry); + } + /// A JSX name: no space before it. + fn jsx_leaf(&mut self, n: &Name) { + let entry = self.len(); + self.s(&n.text); + self.close(n.k, entry); + } + fn string(&mut self, n: &Name) { + let entry = self.len(); + self.b(b'"'); + quote_into(&mut self.out, &n.text); + self.b(b'"'); + self.close(n.k, entry); + } + + // ---- statements ---- + fn stmt(&mut self, s: &St) { + match s { + St::Expr(k, x) => { + let entry = self.len(); + self.print_indent(); + self.start_of_stmt = self.len(); + self.ex(x, Prec::Lowest); + self.s(";\n"); + self.close(*k, entry); + } + St::Decl(d) => { + self.print_indent(); + self.decl(d); + self.after_decl(d); + } + St::Ret(k, x) => { + self.print_indent(); + let entry = self.len(); + self.space_before_ident(); + self.s("return"); + if let Some(x) = x { + self.b(b' '); + self.ex(x, Prec::Lowest); + } + self.s(";\n"); + self.close(*k, entry); + } + St::Throw(k, x) => { + self.print_indent(); + let entry = self.len(); + self.space_before_ident(); + self.s("throw "); + self.ex(x, Prec::Lowest); + self.s(";\n"); + self.close(*k, entry); + } + St::If(c, a, b) => { + self.print_indent(); + self.space_before_ident(); + self.s("if ("); + self.ex(c, Prec::Lowest); + self.s(") "); + self.block(a); + self.s(" else "); + self.block(b); + self.b(b'\n'); + } + St::ForOf(n, x, body) => { + self.print_indent(); + self.space_before_ident(); + self.s("for (const "); + self.leaf(n); + self.s(" of "); + self.ex(x, Prec::Comma); + self.s(") "); + self.block(body); + self.b(b'\n'); + } + St::Try(body, h, f) => { + self.print_indent(); + self.space_before_ident(); + self.s("try "); + self.block(body); + if let Some((n, h)) = h { + self.s(" catch ("); + self.leaf(n); + self.s(") "); + self.block(h); + } + if let Some(f) = f { + self.s(" finally "); + self.block(f); + } + self.b(b'\n'); + } + St::Block(ss) => { + self.print_indent(); + self.block(ss); + self.b(b'\n'); + } + St::Import(k, is_type, specs, from) => self.import(*k, *is_type, specs, from), + St::ExportFrom(specs, from) => { + self.print_indent(); + self.s("export {"); + if !specs.is_empty() { + self.b(b' '); + for (i, (l, e)) in specs.iter().enumerate() { + if i > 0 { + self.s(", "); + } + self.leaf(l); + if l.text != e.text { + self.b(b' '); + self.space_before_ident(); + self.s("as "); + self.leaf(e); + } + } + self.b(b' '); + } + self.s("} from "); + self.string(from); + self.s(";\n"); + } + St::ExportDefault(x) => { + self.print_indent(); + self.s("export default "); + self.ex(x, Prec::Comma); + self.s(";\n"); + } + St::Export(k, d) => { + self.print_indent(); + let entry = self.len(); + self.s("export "); + self.decl(d); + self.after_decl(d); + self.close(*k, entry); + } + St::Raw(n) => { + self.print_indent(); + self.start_of_stmt = self.len(); + self.leaf(n); + self.s(";\n"); + } + } + } + /// What ends a declaration as a statement of its own. + fn after_decl(&mut self, d: &Decl) { + match d { + Decl::Var(v) => { + let entry = self.len(); + self.s(";\n"); + self.extend(v.k, entry); + } + Decl::Type(k, ..) => { + let entry = self.len(); + self.s(";\n"); + self.extend(*k, entry); + } + Decl::Fn(_) => self.b(b'\n'), + } + } + /// Node `k` ends past the `;` written after it. + fn extend(&mut self, k: K, _entry: usize) { + let i = self.slot_of[k as usize]; + if i != NONE && self.slots[i as usize].printed { + self.slots[i as usize].end = (self.len() - 1) as u32; + } + } + fn decl(&mut self, d: &Decl) { + match d { + Decl::Var(v) => { + let entry = self.len(); + self.space_before_ident(); + if v.declare { + self.s("declare "); + } + self.s(if v.kind == VarKind::Const { "const " } else { "let " }); + self.leaf(&v.name); + if let Some(t) = &v.ty { + self.s(": "); + self.ty(t); + } + if let Some(x) = &v.init { + self.s(" = "); + self.ex(x, Prec::Comma); + } + self.close(v.k, entry); + } + Decl::Fn(f) => self.func(f), + Decl::Type(k, n, t) => { + let entry = self.len(); + self.s("type"); + self.space_before_ident(); + self.leaf(n); + self.s(" = "); + self.ty(t); + self.close(*k, entry); + } + } + } + fn func(&mut self, f: &Func) { + let entry = self.len(); + self.space_before_ident(); + if f.is_async { + self.s("async "); + } + self.s("function"); + self.space_before_ident(); + self.leaf(&f.name); + if let Some(t) = &f.tparams { + self.tparams(t); + } + self.b(b'('); + self.params(&f.params); + self.b(b')'); + if let Some(t) = &f.ret { + self.s(": "); + self.ty(t); + } + self.b(b' '); + self.block(&f.body); + self.close(f.k, entry); + } + fn block(&mut self, ss: &[St]) { + if ss.is_empty() { + self.s("{}"); + return; + } + self.s("{\n"); + self.indent += 1; + for s in ss { + self.stmt(s); + } + self.indent -= 1; + self.print_indent(); + self.b(b'}'); + } + fn import(&mut self, k: K, is_type: bool, specs: &[Spec], from: &Name) { + self.print_indent(); + let entry = self.len(); + self.space_before_ident(); + self.s("import"); + if is_type { + self.s(" type"); + } + if specs.is_empty() { + self.s(" {} from "); + let at = self.len(); + self.b(b'"'); + self.s(&from.text); + self.b(b'"'); + self.close(from.k, at); + self.s(";\n"); + self.close(k, entry); + return; + } + let mut in_block = false; + for (i, sp) in specs.iter().enumerate() { + match sp { + Spec::Default(l) => { + if in_block { + self.s(" },"); + in_block = false; + } else if i == 0 { + self.b(b' '); + } else { + self.s(", "); + } + self.leaf(l); + if i == specs.len() - 1 { + self.b(b' '); + } + } + Spec::Ns(l) => { + if in_block { + self.s(" },"); + in_block = false; + } else if i == 0 { + self.b(b' '); + } else { + self.s(", "); + } + self.s("* as "); + self.leaf(l); + self.b(b' '); + } + Spec::Named(imported, local) => { + if in_block { + self.s(", "); + } else { + if i != 0 { + self.b(b','); + } + in_block = true; + self.s(" { "); + } + self.leaf(imported); + if imported.text != local.text { + self.b(b' '); + self.space_before_ident(); + self.s("as "); + self.leaf(local); + } + } + } + } + if in_block { + self.s(" } "); + } + self.s("from "); + self.string(from); + self.s(";\n"); + self.close(k, entry); + } + fn params(&mut self, ps: &[Param]) { + for (i, p) in ps.iter().enumerate() { + if i > 0 { + self.s(", "); + } + self.leaf(&p.name); + if p.optional { + self.b(b'?'); + } + if let Some(t) = &p.ty { + self.s(": "); + self.ty(t); + } + } + } + fn ty(&mut self, t: &Ty) { + match t { + Ty::Raw(n) => self.leaf(n), + Ty::Query(n) => { + self.s("typeof "); + self.leaf(n); + } + } + } + /// ``: one type parameter in TSX keeps its comma (else it is an element). + fn tparams(&mut self, n: &Name) { + self.b(b'<'); + self.leaf(n); + self.s(",>"); + } + fn targs(&mut self, ts: &[Ty]) { + self.b(b'<'); + for (i, t) in ts.iter().enumerate() { + if i > 0 { + self.s(", "); + } + self.ty(t); + } + self.b(b'>'); + } + + // ---- expressions ---- + /// `x` where it binds with `prec`, in the parentheses that takes. + fn ex(&mut self, x: &Ex, prec: Prec) { + let wrap = match x { + Ex::Call(..) | Ex::New(..) => prec >= Prec::New, + Ex::Arrow(..) | Ex::Assign(..) => prec >= Prec::Assign, + Ex::Object(..) => self.start_of_stmt == self.len() || self.start_of_arrow == self.len(), + Ex::Unary(..) | Ex::Await(..) => prec >= Prec::Prefix, + Ex::Cond(..) => prec >= Prec::Conditional, + Ex::Seq(..) => prec >= Prec::Comma, + Ex::As(..) => prec >= Prec::Compare, + Ex::Chain(..) => prec >= Prec::Postfix, + Ex::Bin(_, op, ..) => Self::bin_wraps(*op, prec, *op), + _ => false, + }; + let open = self.len(); + let is_statement = self.start_of_stmt == open; + if wrap { + self.b(b'('); + } + let entry = self.len(); + let inner = if wrap { Prec::Lowest } else { prec }; + match x { + Ex::Id(n) => { + self.leaf(n); + return; + } + Ex::Null(_) => { + self.space_before_ident(); + self.s("null"); + } + Ex::Bool(_, v) => { + self.space_before_ident(); + self.s(if *v { "true" } else { "false" }); + } + Ex::Member(_, o, p, opt) => { + self.ex(o, Prec::Postfix); + self.s(if *opt { "?." } else { "." }); + self.leaf(p); + } + Ex::Computed(_, o, i, opt) => { + let let_ = matches!(&**o, Ex::Id(n) if &*n.text == "let"); + if let_ { + self.b(b'('); + } + self.ex(o, Prec::Postfix); + if let_ { + self.b(b')'); + } + if *opt { + self.s("?."); + } + self.b(b'['); + self.ex(i, Prec::Lowest); + self.b(b']'); + } + Ex::Assign(_, l, r) => { + if is_statement { + self.start_of_stmt = self.len(); + } + self.ex(l, Prec::Postfix); + self.s(" = "); + self.ex(r, Prec::Assign); + } + Ex::New(_, f, args) => { + if is_statement { + self.start_of_stmt = self.len(); + } + self.space_before_ident(); + self.s("new "); + self.ex(f, Prec::New); + self.b(b'('); + self.args(args); + self.b(b')'); + } + Ex::Call(_, f, ta, args) => { + if is_statement { + self.start_of_stmt = self.len(); + } + self.ex(f, Prec::Postfix); + if let Some(ta) = ta { + self.targs(ta); + } + self.b(b'('); + self.args(args); + self.b(b')'); + } + Ex::Arrow(_, a) => { + if a.is_async { + self.space_before_ident(); + self.s("async "); + } + self.b(b'('); + self.params(&a.params); + self.b(b')'); + if let Some(t) = &a.ret { + self.s(": "); + self.ty(t); + } + self.s(" => "); + match &a.body { + Body::Block(ss) => self.block(ss), + Body::Ex(x) => { + self.start_of_arrow = self.len(); + self.ex(x, Prec::Comma); + } + } + } + Ex::Array(_, xs) => { + let multi = xs.len() > 2; + self.b(b'['); + if multi { + self.indent += 1; + } + for (i, x) in xs.iter().enumerate() { + if i != 0 { + self.b(b','); + } + if multi { + self.b(b'\n'); + self.print_indent(); + } else if i != 0 { + self.b(b' '); + } + self.arg(x); + } + if multi { + self.b(b'\n'); + self.indent -= 1; + self.print_indent(); + } + self.b(b']'); + } + Ex::Object(_, ps) => { + let multi = ps.len() > 1; + self.b(b'{'); + if multi { + self.indent += 1; + } + for (i, p) in ps.iter().enumerate() { + if i != 0 { + self.b(b','); + } + if multi { + self.b(b'\n'); + self.print_indent(); + } else { + self.b(b' '); + } + match p { + Prop::Kv(key, v) => { + self.string(key); + self.s(": "); + self.ex(v, Prec::Comma); + } + Prop::Spread(v) => { + self.s("..."); + self.ex(v, Prec::Comma); + } + } + } + if multi { + self.b(b'\n'); + self.indent -= 1; + self.print_indent(); + } else if !ps.is_empty() { + self.b(b' '); + } + self.b(b'}'); + } + Ex::Unary(_, op, a) => { + if op.is_keyword() { + self.space_before_ident(); + self.s(op.text()); + self.b(b' '); + } else { + let next = match op { + Un::Plus => LastOp::Plus, + Un::Neg => LastOp::Neg, + Un::Not => LastOp::Not, + _ => LastOp::Other, + }; + self.space_before_operator(next); + self.s(op.text()); + self.prev_op = Some(next); + self.prev_op_end = self.len(); + } + self.ex(a, Prec::Exponent); + } + Ex::Bin(_, op, l, r) => self.bin(*op, l, r), + Ex::Cond(_, c, a, b) => { + let test = if matches!(&**c, Ex::As(..)) { Prec::Compare } else { Prec::Conditional }; + self.ex(c, test); + self.s(" ? "); + self.ex(a, Prec::Yield); + self.s(" : "); + self.ex(b, Prec::Yield); + } + Ex::Seq(_, xs) => { + for (i, x) in xs.iter().enumerate() { + if i > 0 { + self.s(", "); + } + self.ex(x, Prec::Lowest); + } + } + Ex::Await(_, a) => { + self.space_before_ident(); + self.s("await "); + self.ex(a, Prec::Exponent); + } + Ex::As(_, a, t) => { + self.ex(a, Prec::Exponent); + self.b(b' '); + self.space_before_ident(); + self.s("as "); + self.ty(t); + } + Ex::NonNull(_, a) => { + self.ex(a, Prec::Postfix); + self.b(b'!'); + self.prev_op = Some(LastOp::Not); + self.prev_op_end = self.len(); + } + Ex::Chain(_, a) => self.ex(a, inner), + Ex::Tpl(_, qs, xs) => { + self.b(b'`'); + script_close_escaped(&mut self.out, &qs[0]); + for (x, q) in xs.iter().zip(&qs[1..]) { + self.s("${"); + self.ex(x, Prec::Lowest); + self.b(b'}'); + script_close_escaped(&mut self.out, q); + } + self.b(b'`'); + } + Ex::El(e) => { + self.element(e); + return; + } + Ex::Frag(_, kids) => self.fragment(kids), + } + let k = x.key(); + self.close(k, entry); + if wrap { + self.b(b')'); + self.wrapped(k, open); + } + } + /// oxc's `- -x` rule: an operator written right after another that would read as one with it. + fn space_before_operator(&mut self, next: LastOp) { + if self.prev_op_end != self.len() { + return; + } + let Some(prev) = self.prev_op else { return }; + let plus = matches!(prev, LastOp::Add | LastOp::Plus) && matches!(next, LastOp::Add | LastOp::Plus); + let minus = matches!(prev, LastOp::Sub | LastOp::Neg) && matches!(next, LastOp::Sub | LastOp::Neg); + if plus || minus { + self.b(b' '); + } + } + fn args(&mut self, args: &[Arg]) { + for (i, a) in args.iter().enumerate() { + if i > 0 { + self.s(", "); + } + self.arg(a); + } + } + fn arg(&mut self, a: &Arg) { + match a { + Arg::Ex(x) => self.ex(x, Prec::Comma), + Arg::Spread(k, x) => { + let entry = self.len(); + self.s("..."); + self.ex(x, Prec::Comma); + self.close(*k, entry); + } + } + } + /// Whether a binary or logical expression is wrapped where it is printed: `outer` is the operator whose operand it is + /// (its own, at the top of a chain of them and on a right-hand side). + fn bin_wraps(op: Op, prec: Prec, outer: Op) -> bool { + prec >= op.prec() && (matches!(outer, Op::Bin(_)) || prec != outer.prec()) + } + /// `l op r` (its own parentheses written by `ex`, or by the operator it is the left side of). + fn bin(&mut self, op: Op, l: &Ex, r: &Ex) { + let mut lp = op.lower(); + let mut rp = op.lower(); + if op.prec() == Prec::Exponent { + lp = op.prec(); + } else { + rp = op.prec(); + } + let logical = |x: &Ex| matches!(x, Ex::Bin(_, Op::And | Op::Or, ..)); + if op == Op::Coalesce { + if logical(l) { + lp = Prec::Prefix; + } + if logical(r) { + rp = Prec::Prefix; + } + } + if op == Op::Bin("**") && matches!(l, Ex::Unary(..) | Ex::Await(..)) { + lp = Prec::New; + } + // the left side: wrapped by this operator's rule + match l { + Ex::Bin(lk, lop, ll, lr) => { + let wrap = Self::bin_wraps(*lop, lp, op); + let open = self.len(); + if wrap { + self.b(b'('); + } + let entry = self.len(); + self.bin(*lop, ll, lr); + self.close(*lk, entry); + if wrap { + self.b(b')'); + self.wrapped(*lk, open); + } + } + l => self.ex(l, lp), + } + self.b(b' '); + match op { + Op::Bin(o) if o == "in" || o == "instanceof" => { + self.space_before_ident(); + self.s(o); + } + Op::Bin(o) => { + let next = match o { + "+" => LastOp::Add, + "-" => LastOp::Sub, + _ => LastOp::Other, + }; + self.space_before_operator(next); + self.s(o); + self.prev_op = Some(next); + self.prev_op_end = self.len(); + } + op => self.s(op.text()), + } + self.b(b' '); + self.ex(r, rp); + } + + // ---- views ---- + fn element(&mut self, e: &El) { + let entry = self.len(); + self.b(b'<'); + self.tag(&e.tag); + for a in &e.attrs { + self.b(b' '); + match a { + Attr::Attr(n, v) => { + match n { + AttrName::Id(n) => self.jsx_leaf(n), + AttrName::Ns(a, b) => { + self.jsx_leaf(a); + self.b(b':'); + self.jsx_leaf(b); + } + } + if let Some(v) = v { + self.s("={"); + self.ex(v, Prec::Lowest); + self.b(b'}'); + } + } + Attr::Spread(x) => { + self.s("{..."); + self.ex(x, Prec::Comma); + self.b(b'}'); + } + } + } + match &e.kids { + None => self.s(" />"), + Some((kids, close)) => { + self.b(b'>'); + for c in kids { + self.child(c); + } + self.s("'); + } + } + self.close(e.k, entry); + } + fn tag(&mut self, t: &Tag) { + match t { + Tag::Ident(n) => self.jsx_leaf(n), + Tag::Ref(n) => self.leaf(n), + Tag::Member(first, rest) => { + self.leaf(first); + for n in rest { + self.b(b'.'); + self.jsx_leaf(n); + } + } + } + } + fn fragment(&mut self, kids: &[Child]) { + self.s("<>"); + for c in kids { + self.child(c); + } + self.s(""); + } + fn child(&mut self, c: &Child) { + match c { + Child::Text(k, t) => { + let entry = self.len(); + self.s(t); + self.close(*k, entry); + } + Child::Ex(k, x) => { + let entry = self.len(); + self.b(b'{'); + self.ex(x, Prec::Lowest); + self.b(b'}'); + self.close(*k, entry); + } + Child::El(e) => self.element(e), + Child::Frag(k, kids) => { + let entry = self.len(); + self.fragment(kids); + self.close(*k, entry); + } + } + } +} + +/// ` bool { + rest.len() >= 8 && rest[..2] == *b" out.push_str(if it.peek().is_some_and(|(_, n)| n.is_ascii_digit()) { "\\x00" } else { "\\0" }), + '\x07' => out.push_str("\\x07"), + '\x08' => out.push_str("\\b"), + '\x0B' => out.push_str("\\v"), + '\x0C' => out.push_str("\\f"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\x1B' => out.push_str("\\x1B"), + '\\' => out.push_str("\\\\"), + '"' => out.push_str("\\\""), + '<' if is_script_close(&b[i..]) => { + out.push_str("<\\/"); + it.next(); + } + '\u{2028}' => out.push_str("\\u2028"), + '\u{2029}' => out.push_str("\\u2029"), + '\u{A0}' => out.push_str("\\xA0"), + c => out.push(c), + } + } +} diff --git a/compiler/src/wasm.rs b/compiler/src/wasm.rs index 4d4c33373..dced5ba00 100644 --- a/compiler/src/wasm.rs +++ b/compiler/src/wasm.rs @@ -46,7 +46,7 @@ fn read(path: &str) -> Option { pub unsafe extern "C" fn rx_call(ptr: *mut u8, len: usize) -> *mut u8 { let req: Value = serde_json::from_slice(std::slice::from_raw_parts(ptr, len)).unwrap_or(Value::Null); rx_free(ptr, len); - let out = crate::serve::request(req["method"].as_str().unwrap_or_default(), &req["params"], &read).to_string(); + let out = crate::serve::request(req["method"].as_str().unwrap_or_default(), &req["params"], &read); let p = rx_alloc(out.len() + 4); std::ptr::copy_nonoverlapping((out.len() as u32).to_le_bytes().as_ptr(), p, 4); std::ptr::copy_nonoverlapping(out.as_ptr(), p.add(4), out.len()); diff --git a/compiler/src/wrap.rs b/compiler/src/wrap.rs new file mode 100644 index 000000000..edffd1272 --- /dev/null +++ b/compiler/src/wrap.rs @@ -0,0 +1,50 @@ +//! R-f-5 (round G, 2026-12-04, re-check 17's c04): what UNHANDLED_FAILURE prints where the reader that can fail is no +//! hole of the view — the boundary around the `{if …}` or the element that holds it, from its own text. ref's +//! `markupWrap` (`ref/src/check.ts`). +use crate::ast::{children, Decl, Markup, MarkupKind, Node, Span}; + +/// Round G (re-check 17's c04): where the reader that can fail is no hole — an `if`'s condition, an attribute — the +/// boundary printed around what holds it: the `{if …}` (its whole chain) or the element, from their own text. On one line, +/// the whole replacement; over several, what to write before its first line and after its last. ref's `markupWrap`. +pub fn markup_wrap(src: &str, decls: &[Decl], view: &[Markup], at: Span, cls: &str) -> Option { + if src.is_empty() || at.is_none() { + return None; + } + fn walk(n: Node<'_>, src: &str, at: Span, best: &mut Option<(usize, usize)>) { + if let Node::M(m) = n { + let want = match &m.kind { + MarkupKind::Mif { .. } => Some(b'{'), + MarkupKind::El { tag, .. } if !tag.is_empty() => Some(b'<'), + _ => None, + }; + if let Some(c) = want { + if !m.span.is_none() { + let (s0, s1) = (m.span.start as usize, m.span.end as usize); + if s1 <= src.len() && src.as_bytes().get(s0) == Some(&c) && m.span.start <= at.start && at.end <= m.span.end && best.is_none_or(|(a, b)| s1 - s0 < b - a) { + *best = Some((s0, s1)); + } + } + } + } + for c in children(n, false) { + walk(c, src, at, best); + } + } + let mut best = None; + for d in decls { + walk(Node::D(d), src, at, &mut best); + } + for m in view { + walk(Node::M(m), src, at, &mut best); + } + let (s0, s1) = best?; + let text = &src[s0..s1]; + let open = format!("{{errored fallback(e{}) {{ {{e.message}} }} {{", if cls == "Error" { String::new() } else { format!(": {cls}") }); + if !text.contains('\n') { + return Some(format!("write `{open} {text} }}}}` in place of `{text}`")); + } + let line_of = |i: usize| src[..i].split('\n').count(); + let first = text[..text.find('\n').unwrap_or(text.len())].trim_end(); + let last = text[text.rfind('\n').map_or(0, |i| i + 1)..].trim(); + Some(format!("write `{open}` before `{first}` (line {}), and `}}}}` after its last line, `{last}` (line {})", line_of(s0), line_of(s1))) +} diff --git a/compiler/test/aliases.mjs b/compiler/test/aliases.mjs new file mode 100644 index 000000000..3e950f6e4 --- /dev/null +++ b/compiler/test/aliases.mjs @@ -0,0 +1,213 @@ +// 09 MO-8x: a declaration file's own `export type` aliases are a shorter spelling of their bodies. Each case is a pair of +// declaration files — one whose rows name the file's aliases, one whose rows write every alias out by hand — and programs +// that use them. Both checkers must say the same of a program whichever file declares its module (every diagnostic: code, +// message, place), say it of each other (CP-5), and read the same rows from the two files (the crate's `rows`, the facts a +// row's words and parts come to, every row but the aliases themselves). And a file whose aliases cannot be followed — a +// cycle, a word in an alias's body, a wrong number of type arguments — is refused by both, with one message. +// Needs the crate's build (rxc). node --experimental-strip-types compiler/test/aliases.mjs +import { spawnSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, readFileSync, existsSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { fileURLToPath } from "node:url"; +import path from "node:path"; +import { loadModules } from "../../ref/src/modules.ts"; +import { checkModules } from "../../ref/src/check.ts"; +import { parseDeclarations } from "../../ref/src/parse.ts"; + +const here = path.dirname(fileURLToPath(import.meta.url)), root = path.resolve(here, "../.."); +const rxc = path.join(root, `compiler/target/${process.env.RX_PROFILE ?? "release"}/rxc`); +const tmp = mkdtempSync(path.join(tmpdir(), "rx-aliases-")); +let fail = 0, ran = 0; const bad = (what, why) => { fail++; console.log(`✗ ${what}: ${why}`); }; +const read = p => existsSync(p) ? readFileSync(p, "utf8") : undefined; + +/** What the crate says of a program: each diagnostic as `code line:col message`, the file's folder taken out. */ +function crate(file, dir) { + const r = spawnSync(rxc, ["check", "--json", file], { encoding: "utf8" }); + try { return JSON.parse(r.stdout).diagnostics.map(d => `${d.code} ${d.line} ${d.message}`.replaceAll(dir, "

    ")); } catch { return [`crate: ${r.stdout}${r.stderr}`.replaceAll(dir, "")]; } +} +function ref(file, dir) { + try { return checkModules(loadModules(file, read)).diags.map(d => `${d.code} ${d.line} ${d.msg}`.replaceAll(dir, "")); } catch (e) { return [`${e.code ?? "PARSE"} ${/^\S+: line (\d+)/.exec(e.message)?.[1]} ${e.message.replace(/^\S+: line \d+: /, "")}`.replaceAll(dir, "")]; } +} +/** The rows the crate reads from a declaration file, the aliases' own left out (`rows`: each row's facts). */ +function rows(file) { + const r = spawnSync(rxc, ["serve"], { input: JSON.stringify({ id: 1, method: "rows", params: { file } }) + "\n", encoding: "utf8" }); + const out = JSON.parse(r.stdout.split("\n")[0]).result; + return JSON.stringify(out.rows?.filter(x => x.kind !== "type").map(({ line, end, ...x }) => x) ?? out); +} +const refRows = file => { try { return JSON.stringify(parseDeclarations(readFileSync(file, "utf8")).filter(d => d.kind !== "type").map(({ line, ...d }) => d)); } catch (e) { return `throws ${e.message}`; } }; + +/** `named`: the rows as they name the aliases; `out`: the same rows with every alias written out by hand. Each program + * is checked against both; `codes`: what both checkers say of it. */ +const CASES = [ + { + name: "a generic alias (a render prop), a word through an alias, an alias of an alias", + types: [ + "export type State = { open: boolean }", + "export type RenderProp = (props: Record, state: S) => View", + "export type DialogRender = RenderProp", + "export type Change = (open: boolean) => void", + ], + named: [ + "export component Dialog(props: { render?: DialogRender; onOpenChange?: handler Change; onPick?: Change; onMeasure?: pure Change; children?: View })", + "export component Picker(props: { children: RenderProp<{ value: string; }>; label?: RenderProp })", + "export fn later(f: handler Change): void", + "export fn now(f: Change): void", + ], + out: [ + "export component Dialog(props: { render?: (props: Record, state: { open: boolean }) => View; onOpenChange?: handler (open: boolean) => void; onPick?: (open: boolean) => void; onMeasure?: pure (open: boolean) => void; children?: View })", + "export component Picker(props: { children: (props: Record, state: { value: string; }) => View; label?: (props: Record, state: {}) => View })", + "export fn later(f: handler (open: boolean) => void): void", + "export fn now(f: (open: boolean) => void): void", + ], + programs: [ + { src: `import { Dialog } from "./lib.js"\nsource n := 0\nexport default component App() {\n { n := 1 }}>{view render (p, s) {

    {s.open}

    }}
    \n}`, codes: [] }, + { src: `import { Dialog } from "./lib.js"\nsource n := 0\nexport default component App() {\n { n := 2 }} />\n}`, codes: [] }, // MO-10g (2026-11-29): a component's prop typed to answer nothing is a handler with no word + { src: `import { Dialog } from "./lib.js"\nsource n := 0\nexport default component App() {\n { n := 2 }} />\n}`, codes: ["REACTIVE_WRITE_IN_OWNED_SCOPE"] }, // …and `pure` through an alias says the library calls it while it computes + { src: `import { later } from "./lib.js"\nsource n := 0\nexport default component App() {\n \n}`, codes: [] }, + { src: `import { now } from "./lib.js"\nsource n := 0\nexport default component App() {\n \n}`, codes: null }, + { src: `import { Picker } from "./lib.js"\nexport default component App() {\n

    static

    \n}`, codes: ["VIEW_FN_EXPECTED"] }, + { src: `import { Picker } from "./lib.js"\nexport default component App() {\n {view (p, s) {

    {s.value}

    }}{view label (p, s) { x }}
    \n}`, codes: [] }, + { src: `import { Dialog } from "./lib.js"\nexport default component App() {\n {view (p) {

    x

    }}
    \n}`, codes: ["VIEW_FN_MISPLACED"] }, + ], + }, + { + name: "a record alias read field by field, a union alias among a union's members, props that are an alias", + types: [ + "export type Row = { id: number; title: string }", + "export type Label = string | View", + "export type BoxProps = { title: string; body?: Label | undefined; each: (row: Row) => View }", + "export type Off = () => void", + ], + named: [ + "export pure fn rows(): Row[]", + "export pure fn first(): Row", + "export component Box(props: BoxProps)", + "export fn listen(f: handler (e: string) => void): Off", + ], + out: [ + "export pure fn rows(): { id: number; title: string }[]", + "export pure fn first(): { id: number; title: string }", + "export component Box(props: { title: string; body?: string | View | undefined; each: (row: { id: number; title: string }) => View })", + "export fn listen(f: handler (e: string) => void): () => void", + ], + programs: [ + { src: `import { rows, Box } from "./lib.js"\nexport default component App() {\n {view each (r) {

    {r.title}

    }}
    \n
      {for r in rows() {
    • {r.id}
    • }}
    \n}`, codes: null }, + { src: `import { Box } from "./lib.js"\nexport default component App() {\n

    static

    \n}`, codes: null }, + { src: `import { first } from "./lib.js"\nexport default component App() {\n r = first()\n

    {r.title}

    \n}`, codes: null }, + { src: `import { listen } from "./lib.js"\nsource n := 0\nexport default component App() {\n \n}`, codes: null }, + ], + }, +]; +// a recursive alias (a route tree): written out once, and where it names itself inside a record, a list, a function or a +// type argument — what TypeScript defers — that reference stays its name +CASES.push({ + name: "a recursive alias", + types: [], + named: ["export type RouteDefinition = { path: string; load?: () => void; children?: RouteDefinition[] }", "export fn routes(r: RouteDefinition[], f: handler (r: RouteDefinition) => void): void", "export pure fn tree(): { root: RouteDefinition }"], + out: ["export interface RouteDefinition { path: string; load?: () => void; children?: RouteDefinition[] }", "export fn routes(r: { path: string; load?: () => void; children?: RouteDefinition[] }[], f: handler (r: { path: string; load?: () => void; children?: RouteDefinition[] }) => void): void", "export pure fn tree(): { root: { path: string; load?: () => void; children?: RouteDefinition[] } }"], + programs: [ + { src: `import { routes, tree } from "./lib.js"\nsource n := 0\nexport default component App() {\n t = tree()\n \n}`, codes: [] }, + ], +}); +// MO-8x (2026-11-28): a name the row or the type binds itself is no alias there — the row's own type parameter (c1, c11 of +// the review of 25a35680), a generic function type's, an alias body's own `` beside the alias's parameter T (c3), an +// `infer` name, a mapped type's key. Each was the file's alias written in its place (a callback, a record), so the row +// said another thing than TypeScript reads. +CASES.push({ + name: "a row's own type parameter", + types: [], + named: ["export type S = (x: number) => void", "export fn run(cb: S): void"], + out: ["export fn run(cb: S): void"], + programs: [ + { src: `import { run } from "./lib.js"\nsource n := 0\nexport default component App() {\n \n}`, codes: null }, + { src: `import { run } from "./lib.js"\nsource n := 0\nexport default component App() {\n r = run((x) => { n := 1 })\n

    {n}

    \n}`, codes: null }, + ], +}); +CASES.push({ + name: "an alias body's own type parameter", + types: [], + named: ["export type Id = (x: T) => T", "export fn f(g: Id): void"], + out: ["export fn f(g: (x: T) => T): void"], + programs: [], +}); +CASES.push({ + name: "a row's own type parameter, named as a record alias", + types: [], + named: ["export type T = { a: string }", "export pure fn g(x: T): T"], + out: ["export pure fn g(x: T): T"], + programs: [{ src: `import { g } from "./lib.js"\nexport default component App() {\n

    {g(1)}

    \n}`, codes: null }], +}); +CASES.push({ + name: "a generic function type's parameter, an infer name, a mapped type's key", + types: [], + named: ["export type T = { a: string }", "export type U = (x: number) => void", "export type K = { k: number }", "export fn f(g: (x: T) => T, h: string extends infer U ? U : never, m: { [K in \"a\" | \"b\"]: number }): void"], + out: ["export fn f(g: (x: T) => T, h: string extends infer U ? U : never, m: { [K in \"a\" | \"b\"]: number }): void"], + programs: [], +}); +// a method named as a word of a row (c10): `fails(`, `catches(` are a row's words only as a row reads them, before a type +CASES.push({ + name: "a method named fails", + types: [], + named: ["export type Api = { fails(): number; catches(x: string): boolean; size: number }", "export pure fn api(): Api"], + out: ["export pure fn api(): { fails(): number; catches(x: string): boolean; size: number }"], + programs: [{ src: `import { api } from "./lib.js"\nexport default component App() {\n a = api()\n

    {a.size}

    \n}`, codes: [] }], +}); +// a record whose fields are on lines of their own, as TypeScript separates them (c6, c9): each field read as a field (its +// type, a callback among them), the same as with `;` between them +CASES.push({ + name: "a record alias on several lines, with a comment", + lines: true, + types: [], + named: ["export type P = {", " a: string", " // note", " b: (x: number) => void", "}", "export fn f(p: P): void"], + out: ["export fn f(p: { a: string; b: (x: number) => void }): void"], + programs: [{ src: `import { f } from "./lib.js"\nsource n := 0\nexport default component App() {\n r = f({ a: "x", b: (x) => { n := 1 } })\n

    {n}

    \n}`, codes: null }], +}); +CASES.push({ + name: "a record on several lines in the row itself", + lines: true, + types: [], + named: ["export fn f(p: {", " a: string", " b: (x: number) => void", "}): void"], + out: ["export fn f(p: { a: string; b: (x: number) => void }): void"], + programs: [{ src: `import { f } from "./lib.js"\nsource n := 0\nexport default component App() {\n r = f({ a: "x", b: (x) => { n := 1 } })\n

    {n}

    \n}`, codes: null }], +}); +/** Files both checkers refuse: the message, and what it says. */ +const REFUSED = [ + { name: "a cycle", file: ["export type A = B | string", "export type B = A", "export fn f(a: A): void"], says: /type A: A names itself: A → B → A/ }, + { name: "a cycle through a type argument", file: ["export type Box = { v: T }", "export type Loop = Box"], says: /Loop names itself/ }, + { name: "a word in an alias's body", file: ["export type Change = handler (open: boolean) => void", "export fn later(f: Change): void"], says: /is a row's, not an alias's/ }, + { name: "too many type arguments", file: ["export type P = (s: S) => View", "export component C(props: { render: P })"], says: /P takes 1 type argument, and is given 2/ }, + { name: "a missing type argument", file: ["export type P = (s: S) => View", "export fn f(r: P): void"], says: /P is given 0 type arguments: its parameter S has no default/ }, + { name: "a failure row in an alias's body", file: ["export type R = fails(NotFound) string", "export fn f(): R"], says: /a word .* is a row's, not an alias's/ }, + { name: "an alias declared twice", file: ["export type P = string", "export type P = number"], says: /type P is declared twice/ }, +]; + +for (const [ci, c] of CASES.entries()) { + const dirs = { named: path.join(tmp, `c${ci}-named`), out: path.join(tmp, `c${ci}-out`) }; + for (const [k, dir] of Object.entries(dirs)) { mkdirSync(dir, { recursive: true }); writeFileSync(path.join(dir, "lib.d.rx"), [...c.types, ...c[k]].join("\n") + "\n"); } + // `lines`: the record is written on several lines in one file and on one in the other — the same rows but for that text + const text = x => !c.lines ? x : x.replace(/"(?:[^"\\]|\\.)*"/g, q => JSON.stringify(JSON.parse(q).replace(/\/\/[^\n]*/g, "").replace(/\s*\n\s*/g, "; ").replace(/\{(\s*;)+\s*/g, "{ ").replace(/(;\s*)+\}/g, " }").replace(/(;\s*){2,}/g, "; "))); + const r1 = text(rows(path.join(dirs.named, "lib.d.rx"))), r2 = text(rows(path.join(dirs.out, "lib.d.rx"))); + ran++; if (r1 !== r2) bad(`${c.name}: the crate's rows`, `\n named: ${r1}\n out: ${r2}`); + const f1 = text(refRows(path.join(dirs.named, "lib.d.rx"))), f2 = text(refRows(path.join(dirs.out, "lib.d.rx"))); + ran++; if (f1 !== f2) bad(`${c.name}: ref's rows`, `\n named: ${f1}\n out: ${f2}`); + for (const [pi, p] of c.programs.entries()) { + const what = `${c.name}, program ${pi}`; const said = {}; + for (const [k, dir] of Object.entries(dirs)) { const f = path.join(dir, `p${pi}.rx`); writeFileSync(f, p.src + "\n"); said[`crate ${k}`] = crate(f, dir); said[`ref ${k}`] = ref(f, dir); } + const all = Object.values(said).map(x => JSON.stringify(x)); ran++; + if (new Set(all).size !== 1) bad(what, Object.entries(said).map(([k, v]) => `\n ${k}: ${JSON.stringify(v)}`).join("")); + else if (p.codes && JSON.stringify(said["crate named"].map(d => d.split(" ")[0])) !== JSON.stringify(p.codes)) bad(what, `expected [${p.codes}], both say ${JSON.stringify(said["crate named"])}`); + else if (process.env.VERBOSE) console.log(`✓ ${what}: ${JSON.stringify(said["crate named"].map(d => d.split(" ")[0]))}`); + } +} +for (const [i, r] of REFUSED.entries()) { + const dir = path.join(tmp, `r${i}`); mkdirSync(dir, { recursive: true }); + writeFileSync(path.join(dir, "lib.d.rx"), r.file.join("\n") + "\n"); + const f = path.join(dir, "app.rx"); writeFileSync(f, `import { f } from "./lib.js"\nexport default component App() {\n

    x

    \n}\n`); + const a = crate(f, dir), b = ref(f, dir); ran++; + const msg = x => x.map(s => s.replace(/^\S+ \S+ /, "")).join(" | "); + if (!r.says.test(msg(a))) bad(r.name, `the crate says ${JSON.stringify(a)}`); + else if (!r.says.test(msg(b))) bad(r.name, `ref says ${JSON.stringify(b)}`); + else if (msg(a) !== msg(b) && !msg(b).includes(msg(a).replace(/^.*?: line/, "line"))) bad(r.name, `the two say it otherwise:\n crate: ${msg(a)}\n ref: ${msg(b)}`); +} +console.log(fail ? `aliases: ${fail} of ${ran} failed` : `aliases: ${ran} checks, each pair read alike by both checkers`); +process.exit(fail ? 1 : 0); diff --git a/compiler/test/aliasing.mjs b/compiler/test/aliasing.mjs new file mode 100644 index 000000000..5bf8dfcdc --- /dev/null +++ b/compiler/test/aliasing.mjs @@ -0,0 +1,368 @@ +// 02 W-1a, 06 ST-2a (re-check 15's F-C, 2026-12-02): a source's list or record kept somewhere else is its value when it +// was kept. The guide's undo — `past := p => [...p, items]; items := [...items, n]` — kept Solid's store of the list in the +// history, so the next write of the list changed every entry and undo put back nothing, in both builds (r15's p42, p44, +// app c04); the same for a local kept across a write (a rollback) and an action's argument. Here each runs in Chromium, +// development and production, and must show what the interpreter shows (ref/aliasing.ts holds the generated family). +// What is shared stays shared (ST-2, S-region-3): a path write of a record a history keeps reaches the history — that is +// ALIASED_STATE's advice, and its printed copy, pasted, keeps the history as it was. +// ALIASING_TOOLS=
    runs another checkout's compiler and runtime: the positive control (123ae8cd fails the undo, +// the plain history, the rollback and the argument in both builds). +// node compiler/test/aliasing.mjs [filter] +import { mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import path from "node:path"; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const TOOLS = process.env.ALIASING_TOOLS ? path.resolve(process.env.ALIASING_TOOLS) : path.resolve(here, "../.."); +const { ws, workspace, both, Runner } = await import(pathToFileURL(path.join(TOOLS, "bench/harness.mjs")).href); +if (!process.env.ALIASING_TOOLS) workspace(); +const root = path.join(ws, "aliasing"); rmSync(root, { recursive: true, force: true }); mkdirSync(root, { recursive: true }); +const filter = process.argv[2]; +let pass = 0, fail = 0; +const check = (name, ok, got) => { ok ? pass++ : fail++; console.log(`${ok ? "✓" : "✗"} ${name}${ok ? "" : `\n ${String(typeof got === "string" ? got : JSON.stringify(got)).slice(0, 900)}`}`); return ok; }; +const sleep = ms => new Promise(res => setTimeout(res, ms)); +const show = r => `crate: ${r.crate.diagnostics.map(d => `${d.code}@${d.line}`).join(",") || "accepted"} / ref: ${r.ref.diagnostics.map(d => `${d.code}@${d.line}`).join(",") || "accepted"}`; +const API = { + "api.js": `export const save = (ok) => new Promise((r, no) => setTimeout(() => ok ? r(ok) : no(new Error("refused")), 300))\n`, + "api.d.rx": `export fn save(ok: boolean): Promise\n`, +}; +const clicks = (...sels) => `(async () => { for (const s of ${JSON.stringify(sels)}) { document.querySelector(s).click(); await new Promise((r) => setTimeout(r, 120)); } })()`; +// [name, what, main.rx, clicks, the text of .out at the end, advice expected] +const CASES = [ + ["undo", "the guide's undo: an updater keeps the list, then the list is written whole (p42)", `export default component App() { + source items: number[] := [1] + source past: number[][] := [] +
    + + +

    {items.join(",")} | {past.map(p => p.join(",")).join(" / ")}

    +
    +}`, [".add", ".add", ".undo"], "1,2 | 1", null], + ["history", "a history written whole, then the list (p44)", `export default component App() { + source items: number[] := [1] + source past: number[][] := [] +
    + +

    {items.join(",")} | {past.map(p => p.join(",")).join(" / ")}

    +
    +}`, [".add", ".add"], "1,2,3 | 1 / 1,2", null], + ["keyed-undo", "a keyed list's undo: the history keeps the rows, a row a later write keeps by its key is the same row (ST-4a)", `type T = { id: number; text: string } +export default component App() { + source todos: T[] key id := [{ id: 1, text: "a" }] + source past: T[][] := [] +
    + + +

    {todos.map(t => t.text).join(",")} | {past.map(p => str(len(p))).join(" / ")}

    +
    +}`, [".add", ".add", ".undo"], "a,n | 1", null], + // re-check 16's F1: a keyed write changed the rows a history kept, where they were (q01, q09, q14, app c01) + ["keyed-edit-undo", "a keyed list's row edited by map, then undone: the history keeps the row as it was (q01)", `type T = { id: number; text: string } +export default component App() { + source todos: T[] key id := [{ id: 1, text: "a" }] + source past: T[][] := [] +
    + + +

    {todos.map(t => t.text).join(",")} | {past.map(p => p.map(t => t.text).join(",")).join(" / ")}

    +
    +}`, [".edit", ".edit", ".undo"], "az | a", null], + ["keyed-redo", "a keyed list's undo then redo (q09)", `type T = { id: number; text: string } +export default component App() { + source todos: T[] key id := [{ id: 1, text: "a" }, { id: 2, text: "b" }] + source past: T[][] := [] + source future: T[][] := [] +
    + + + +

    {todos.map(t => t.text).join(",")} | {past.map(p => p.map(t => t.text).join(",")).join(" / ")} | {future.map(p => p.map(t => t.text).join(",")).join(" / ")}

    +
    +}`, [".edit", ".undo", ".redo", ".undo"], "a,b | | z,b", null], + ["keyed-saved", "a keyed list saved whole, then edited: the saved copy is the list as it was (q14)", `type T = { id: number; text: string } +export default component App() { + source todos: T[] key id := [{ id: 1, text: "a" }] + source saved: T[] := [] + dirty = todos.map(t => t.text).join(",") != saved.map(t => t.text).join(",") +
    + + +

    {todos.map(t => t.text).join(",")} | {saved.map(t => t.text).join(",")} | {dirty ? "dirty" : "clean"}

    +
    +}`, [".snap", ".edit", ".edit"], "azz | a | dirty", null], + ["keyed-board", "a keyed board's cards moved twice, undone twice, redone once (app c01)", `type Card = { id: number; col: string } +export default component App() { + source cards: Card[] key id := [{ id: 1, col: "todo" }, { id: 2, col: "todo" }] + source past: Card[][] := [] + source future: Card[][] := [] + action move(id: number, col: string) { past := p => [...p, cards]; future := []; cards := cards.map(c => c.id == id ? { ...c, col: col } : c) } +
    + + + + +

    {cards.map(c => c.col).join(",")} | {str(len(past))} | {str(len(future))}

    +
    +}`, [".m1", ".m2", ".undo", ".undo", ".redo"], "doing,todo | 1 | 1", null], + ["keyed-row-kept", "a keyed row nothing else keeps is changed where it is: its region's state stays (ST-4a), whole write or an action given the row", `type T = { id: number; done: boolean } +export default component App() { + source todos: T[] key id := [{ id: 1, done: false }, { id: 2, done: false }] + action toggle(t: T) { todos := todos.map(x => x.id == t.id ? { ...x, done: !x.done } : x) } +
    + {for t in todos { + source hits := 0 + + + {t.done ? "x" : "o"}{hits} + }} +

    | end

    +
    +}`, [".h1", ".t1", ".h1", ".t1", ".t1", ".h2"], "x2 hittoggleo1 | end", null], + ["keyed-row-apart", "a keyed row a history keeps is a new row once it is written (its region made again); the rows not written keep theirs", `type T = { id: number; text: string } +export default component App() { + source todos: T[] key id := [{ id: 1, text: "a" }, { id: 2, text: "b" }] + source past: T[][] := [] +
    + {for t in todos { + source hits := 0 + + {t.text}{hits} + }} + +

    | {past.map(p => p.map(t => t.text).join(",")).join(" / ")}

    +
    +}`, [".h1", ".h2", ".edit"], "hitaz0 hitb1 edit| a,b", null], + // a guessed source's view is one optimistic store for its life (round E listed "a guessed source whose root is kept" as + // open, unmeasured): what keeps it keeps its value as it is then + ["guessed-keyed-undo", "a keyed list that is guessed, kept in a history, saved, then undone", `import { save } from "./api.js" +type T = { id: number; text: string } +export default component App() { + source todos: T[] key id := [{ id: 1, text: "a" }, { id: 2, text: "b" }] + source past: T[][] := [] + action edit() { past := p => [...p, todos]; guess todos := ts => ts.map(t => t.id == 1 ? { ...t, text: "z?" } : t); try { await save(true); todos := ts => ts.map(t => t.id == 1 ? { ...t, text: "z" } : t) } catch (e) { } } +
    + + + +

    {todos.map(t => t.text).join(",")} | {past.map(p => p.map(t => t.text).join(",")).join(" / ")}

    +
    +}`, [".edit", ".wait", ".wait", ".wait", ".wait"], "z,b | a,b", null], + ["guessed-undo", "a list with no key that is guessed, kept in a history, saved, then undone", `import { save } from "./api.js" +export default component App() { + source items: string[] := ["a"] + source past: string[][] := [] + action add() { past := p => [...p, items]; guess items := v => [...v, "n?"]; try { await save(true); items := v => [...v, "n"] } catch (e) { } } +
    + + + +

    {items.join(",")} | {past.map(p => p.join(",")).join(" / ")}

    +
    +}`, [".add", ".wait", ".wait", ".wait", ".wait", ".undo"], "a |", null], + ["rollback", "a local kept across a write: the list written back from it is the list as it was", `export default component App() { + source items: string[] := ["a"] +
    + +

    {items.join(",")}

    +
    +}`, [".bad"], "a", null], + ["argument", "an action's argument: the list as it was at the call", `import { save } from "./api.js" +export default component App() { + source items: string[] := ["a"] + source kept: string[][] := [] + action keep(list: string[]) { try { await save(true); kept := k => [...k, list] } catch (e) { } } +
    + + +

    {items.join(",")} | {kept.map(k => k.join(",")).join(" / ")}

    +
    +}`, [".go", ".add"], "a,b | a", null], + // (round H, re-check 18's F1: a path write leaves what another place holds as it was — it reached the history, and + // ALIASED_STATE advised a copy; the history keeps each value now, and nothing is advised) + ["record-path", "a record kept, then written along a path: the history keeps the record as it was (p45)", `type P = { x: number } +export default component App() { + source pos: P := { x: 0 } + source trail: P[] := [] +
    + +

    {pos.x} | {trail.map(p => str(p.x)).join(",")}

    +
    +}`, [".move", ".move"], "2 | 0,1", null], + // re-check 17's F1: a keyed row written into a source by itself, or inside a record — a source held in a signal (its + // first value \`null\`) — was not held, and the next whole write changed it where it was (k22, k17; the interpreter's + // S-r17-row* kept it) + ["row-kept", "a row written by itself and inside a record, then the list written whole (k22)", `type T = { id: number; text: string; done: boolean } +type Snap = { row: T; at: number } +export default component App() { + source todos: T[] key id := [{ id: 1, text: "a", done: false }] + source snap: Snap | null := null + source selected: T | null := null +
    + + + +

    {todos.map(t => t.text + (t.done ? "+" : "-")).join(",")} ; {snap == null ? "-" : snap.row.text} ; {selected == null ? "-" : selected.text + (selected.done ? "+" : "-")}

    +
    +}`, [".snap", ".sel", ".ed"], "a!+ ; a ; a-", null], + ["row-revert", "an edit keeps the row as it was before, and revert puts it back (k17)", `type T = { id: number; text: string } +export default component App() { + source todos: T[] key id := [{ id: 1, text: "a" }] + source lastRow: T | null := null +
    + {for t in todos { }} + +

    {todos.map(t => t.text).join(",")}|L:{lastRow == null ? "-" : lastRow.text}

    +
    +}`, [".ed", ".ed", ".rev"], "a!|L:a!", null], +]; +async function run(dir, script, production) { + const h = new Runner(dir, "main.rx", undefined, { production }); + try { + const page = await h.open(await h.serve()); await sleep(300); + await page.evaluate(script); await sleep(500); + const full = (await Promise.race([h.text(page, ".out"), sleep(3000).then(() => "")])).replace(/\s+/g, " ").trim(); + return { seen: full.replace(/^.*?(?=\S+ \|| ?[a-z0-9,]+$)/, "").trim(), full, problems: [...h.problems] }; + } catch (e) { return { seen: `run threw: ${String(e.message ?? e).slice(0, 200)}`, problems: [...h.problems] }; } + finally { await h.close().catch(() => {}); } +} +const stage = (name, src) => { + const dir = path.join(root, name); rmSync(dir, { recursive: true, force: true }); mkdirSync(dir, { recursive: true }); + for (const [f, text] of Object.entries({ ...API, "main.rx": src })) writeFileSync(path.join(dir, f), text); + return dir; +}; +for (const [name, what, src, sels, want, copy] of CASES) { + if (filter && !name.includes(filter)) continue; + const dir = stage(name, src), r = both(path.join(dir, "main.rx")); + const advised = x => (x.advice ?? []).filter(d => d.code === "ALIASED_STATE"); // (retired in round H: never said now) + const errors = x => x.diagnostics; + if (!check(`${name}: accepted by both checkers${copy ? ", ALIASED_STATE advised by both" : ", nothing advised"}`, r.agree && !errors(r.crate).length && !errors(r.ref).length && advised(r.crate).length === (copy ? 1 : 0) && advised(r.ref).length === (copy ? 1 : 0), show(r))) continue; + for (const production of [false, true]) { + const got = await run(dir, clicks(...sels), production); + check(`${name} (${production ? "production" : "development"}): ${what} — ends on ${JSON.stringify(want)}`, (got.seen.endsWith(want) || (got.full ?? "").endsWith(want)) && !got.problems.length, got); + } + if (!copy) continue; + // the advice's copy, pasted where the record was kept: the history keeps each value + const msg = advised(r.crate)[0].message; + check(`${name}: the advice prints \`${copy}\``, msg.includes("`" + copy + "`"), msg); + const dir2 = stage(`${name}-pasted`, src.replace("[...t, pos]", `[...t, ${copy}]`)), r2 = both(path.join(dir2, "main.rx")); + if (!check(`${name}, the copy pasted: accepted by both checkers, nothing advised`, r2.agree && !r2.crate.diagnostics.length && !r2.ref.diagnostics.length && !advised(r2.crate).length && !advised(r2.ref).length, show(r2))) continue; + for (const production of [false, true]) { + const got = await run(dir2, clicks(...sels), production); + check(`${name}, the copy pasted (${production ? "production" : "development"}): ends on "2 | 0,1"`, got.seen.endsWith("2 | 0,1") && !got.problems.length, got); + } +} +// re-check 16's F3: a list kept through an action's argument, then written along a path (q06). Round H (re-check 18's +// F1): the path write leaves the history as it was, so nothing is advised (ALIASED_STATE advised the copy, retired), in +// both builds +if (!filter || "argument-path".includes(filter)) { + const src = `export default component App() { + source items: number[] := [1, 2] + source past: number[][] := [] + action keep(list: number[]) { past := p => [...p, list] } +
    + + +

    {items.join(",")} | {past.map(p => p.join(",")).join(" / ")}

    +
    +}`; + const dir = stage("argument-path", src), r = both(path.join(dir, "main.rx")); + if (check("argument-path: accepted by both checkers, nothing advised", r.agree && !r.crate.diagnostics.length && !r.ref.diagnostics.length && !(r.crate.advice ?? []).length && !(r.ref.advice ?? []).length, show(r))) + for (const production of [false, true]) { const got = await run(dir, clicks(".keep", ".poke"), production); check(`argument-path (${production ? "production" : "development"}): the history keeps the list as it was — ends on "9,2 | 1,2"`, got.seen.endsWith("9,2 | 1,2") && !got.problems.length, got); } +} +// Round G (re-check 17's known limit): \`selected := t\` keeps the row as it was (W-1a, ST-4a, F1 above), so a selection +// no longer follows an edit of the row (k03, app c02's "Now playing ♥"). KEPT_ROW advises keeping the key, with the edit +// printed whole; pasted as printed it is accepted, rx-tsc is clean, and the selection follows in both builds. Not advised +// where the row is put back (row-revert above). +if (!filter || "kept-row".includes(filter)) { + const src = `type T = { id: number; text: string; done: boolean } +export default component App() { + source todos: T[] key id := [{ id: 1, text: "a", done: false }, { id: 2, text: "b", done: false }] + source selected: T | null := null +
    + {for t in todos { + + + }} + +

    list:{todos.map(t => t.text + (t.done ? "+" : "-")).join(",")}|detail:{selected == null ? "none" : selected.text + (selected.done ? "+" : "-")}

    +
    +}`; + const adv = x => (x.advice ?? []).filter(d => d.code === "KEPT_ROW"); + const dir = stage("kept-row", src), r = both(path.join(dir, "main.rx")); + if (check("kept-row: accepted, KEPT_ROW advised by both checkers with the same message", r.agree && !r.crate.diagnostics.length && !r.ref.diagnostics.length && adv(r.crate).length === 1 && adv(r.ref).length === 1 && adv(r.crate)[0].message === adv(r.ref)[0].message, show(r) + JSON.stringify([adv(r.crate), adv(r.ref)]))) { + for (const production of [false, true]) { const got = await run(dir, clicks(".sel1", ".toggle1"), production); check(`kept-row (${production ? "production" : "development"}): the kept row is the row as it was — "list:a+,b-|detail:a-"`, (got.full ?? "").endsWith("list:a+,b-|detail:a-") && !got.problems.length, got); } + const msg = adv(r.crate)[0].message; + const m = /keep its key: write `([^`]*)` and `([^`]*)` in place of `([^`]*)` \(line \d+\), and (.*)\. Where/.exec(msg); + if (check("kept-row: the advice prints the declarations and each write", !!m, msg)) { + let pasted = src.replace(m[3], `${m[1]}\n ${m[2]}`); + for (const e of m[4].matchAll(/`([^`]*)` in place of `([^`]*)` \(line \d+\)/g)) pasted = pasted.replace(e[2], e[1]); + const dir2 = stage("kept-row-pasted", pasted), r2 = both(path.join(dir2, "main.rx")); + if (check("kept-row, pasted: accepted by both checkers, nothing advised", r2.agree && !r2.crate.diagnostics.length && !r2.ref.diagnostics.length && !adv(r2.crate).length && !adv(r2.ref).length, show(r2) + "\n" + pasted)) { + { const { TSCONFIG_TEXT } = await import("./pasted-cases.mjs"); const { spawnSync } = await import("node:child_process"); writeFileSync(path.join(dir2, "tsconfig.json"), TSCONFIG_TEXT); const t = spawnSync(process.execPath, [path.join(TOOLS, "tooling/rx-language-server/bin/tsc.js"), "-p", "."], { cwd: dir2, encoding: "utf8", timeout: 300000 }); const out = (t.stdout ?? "") + (t.stderr ?? ""); check("kept-row, pasted: rx-tsc clean", t.status === 0 && !/error/.test(out), out.slice(0, 600)); } + for (const production of [false, true]) { + const got = await run(dir2, clicks(".sel1", ".toggle1"), production); + check(`kept-row, pasted (${production ? "production" : "development"}): the selection follows the row — "list:a+,b-|detail:a+"`, (got.full ?? "").endsWith("list:a+,b-|detail:a+") && (got.full ?? "").includes("a*") && !got.problems.length, got); + const got2 = await run(dir2, clicks(".sel1", ".none"), production); + check(`kept-row, pasted (${production ? "production" : "development"}): \`null\` clears it`, (got2.full ?? "").endsWith("detail:none") && !got2.problems.length, got2); + } + } + } + } + const [, rr] = [0, both(path.join(stage("kept-row-revert", CASES.find(c => c[0] === "row-revert")[2]), "main.rx"))]; + check("row-revert: a row put back is a copy on purpose — KEPT_ROW not advised", !adv(rr.crate).length && !adv(rr.ref).length, JSON.stringify([adv(rr.crate), adv(rr.ref)])); +} +// Round H (re-check 18): KEPT_ROW where r18 found it silent or its edit not whole — F3, a row picked from an equation +// that filters the keyed list, whose Close reads only the row's key (it was taken for a put-back: c02's detail panel); +// F4, a `T | undefined` source (the edit printed `| null := null` and `?? null`: rx-tsc TS18047, a crash at mount); and +// a path write of the list, which leaves a kept row as it was now (h03). Each: advised alike by both checkers, the edit +// pasted as printed accepted, rx-tsc clean, and the source follows the row in both builds. +for (const [name, src, sels, before, after] of [ + ["kept-row-filtered", `type T = { id: number; text: string; open: boolean } +export default component App() { + source todos: T[] key id := [{ id: 1, text: "a", open: true }, { id: 2, text: "b", open: true }] + source selected: T | null := null + shown = todos.filter((t) => t.open) +
    + {for t in shown { }} + +

    {todos.map((t) => t.text + (t.open ? "+" : "-")).join(",")}|{selected == null ? "-" : selected.text + (selected.open ? " open" : " closed")}

    +
    +}`, [".s1", ".close"], "a-,b+|a open", "a-,b+|a closed"], + ["kept-row-undefined", `type T = { id: number; text: string } +export default component App() { + source todos: T[] key id := [{ id: 1, text: "a" }, { id: 2, text: "b" }] + source cur: T | undefined := undefined +
    + + +

    {todos.map((t) => t.text).join(",")}|{cur == undefined ? "-" : cur.text}

    +
    +}`, [".c", ".up"], "A,b|a", "A,b|A"], + ["kept-row-path", `type T = { id: number; text: string } +export default component App() { + source todos: T[] key id := [{ id: 1, text: "a" }, { id: 2, text: "b" }] + source selected: T | null := null +
    + + +

    {todos.map((t) => t.text).join(",")}|{selected == null ? "-" : selected.text}

    +
    +}`, [".sel", ".z"], "Z,b|a", "Z,b|Z"], +]) { + if (filter && !name.includes(filter)) continue; + const adv = x => (x.advice ?? []).filter(d => d.code === "KEPT_ROW"); + const dir = stage(name, src), r = both(path.join(dir, "main.rx")); + if (!check(`${name}: accepted, KEPT_ROW advised by both checkers with the same message`, r.agree && !r.crate.diagnostics.length && !r.ref.diagnostics.length && adv(r.crate).length === 1 && adv(r.ref).length === 1 && adv(r.crate)[0].message === adv(r.ref)[0].message, show(r) + JSON.stringify([adv(r.crate), adv(r.ref)]))) continue; + for (const production of [false, true]) { const got = await run(dir, clicks(...sels), production); check(`${name} (${production ? "production" : "development"}): as written, the kept row as it was — "${before}"`, (got.full ?? "").endsWith(before) && !got.problems.length, got); } + const msg = adv(r.crate)[0].message; + const m = /keep its key: write `([^`]*)` and `([^`]*)` in place of `([^`]*)` \(line \d+\), and (.*)\. Where/.exec(msg); + if (!check(`${name}: the advice prints the declarations and each write`, !!m, msg)) continue; + let pasted = src.replace(m[3], `${m[1]}\n ${m[2]}`); + for (const e of m[4].matchAll(/`([^`]*)` in place of `([^`]*)` \(line \d+\)/g)) pasted = pasted.replace(e[2], e[1]); + const dir2 = stage(`${name}-pasted`, pasted), r2 = both(path.join(dir2, "main.rx")); + if (!check(`${name}, pasted: accepted by both checkers, nothing advised`, r2.agree && !r2.crate.diagnostics.length && !r2.ref.diagnostics.length && !adv(r2.crate).length && !adv(r2.ref).length, show(r2) + "\n" + pasted)) continue; + { const { TSCONFIG_TEXT } = await import("./pasted-cases.mjs"); const { spawnSync } = await import("node:child_process"); writeFileSync(path.join(dir2, "tsconfig.json"), TSCONFIG_TEXT); const t = spawnSync(process.execPath, [path.join(TOOLS, "tooling/rx-language-server/bin/tsc.js"), "-p", "."], { cwd: dir2, encoding: "utf8", timeout: 300000 }); const out = (t.stdout ?? "") + (t.stderr ?? ""); check(`${name}, pasted: rx-tsc clean`, t.status === 0 && !/error/.test(out), out.slice(0, 600)); } + for (const production of [false, true]) { const got = await run(dir2, clicks(...sels), production); check(`${name}, pasted (${production ? "production" : "development"}): the source follows the row — "${after}"`, (got.full ?? "").endsWith(after) && !got.problems.length, got); } +} +console.log(`\n${pass} passed, ${fail} failed`); +process.exit(fail ? 1 : 0); diff --git a/compiler/test/async-writers.mjs b/compiler/test/async-writers.mjs new file mode 100644 index 000000000..565dddeba --- /dev/null +++ b/compiler/test/async-writers.mjs @@ -0,0 +1,252 @@ +// 06 AC-1m (2026-12-02, round D1): the run that started last writes — among the runs of one family. AC-1l numbers the runs +// of one declared action, and of every handler that is an action (F1); a write it cannot order landed in the order the +// runs ended. Measured on this tree before the rule, in Solid's development and production builds (click the slow one, then +// the fast one 10 ms later): nine ordinary shapes ended on the older click's answer, with nothing said — two declared +// actions writing one source after their `await`; an action and a handler; two actions that call one helper; and a handler +// that awaits and writes nothing itself, calling after its `await` an action, a prop's function (from one component or +// two) or a context's (such a handler is no action, AC-1b, so its runs were never numbered). Each is refused now, by both +// checkers alike; a handler's message prints its own steps as an action, which pasted as printed ends on the last click; +// the shapes that were right stay accepted and right. node compiler/test/async-writers.mjs (needs what bench/run.mjs needs) +import { mkdirSync, rmSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { ws, workspace, both, Runner } from "../../bench/harness.mjs"; + +workspace(); +const root = path.join(ws, "async-writers"); rmSync(root, { recursive: true, force: true }); mkdirSync(root, { recursive: true }); +let pass = 0, fail = 0; +const check = (name, ok, got) => { ok ? pass++ : fail++; console.log(`${ok ? "✓" : "✗"} ${name}${ok ? "" : `\n ${String(typeof got === "string" ? got : JSON.stringify(got)).slice(0, 900)}`}`); return !!ok; }; +const sleep = ms => new Promise(r => setTimeout(r, ms)); +const codes = r => r.diagnostics.map(d => d.code); +const show = r => `crate: ${codes(r.crate).join(",") || "accepted"} / ref: ${codes(r.ref).join(",") || "accepted"} — ${r.crate.diagnostics.map(d => d.message).join(" | ").slice(0, 600)}`; +const LIB = { "search.js": `export const save = (x) => new Promise((r) => setTimeout(() => r(x), x == "slow" ? 300 : 50))\n`, "search.d.rx": `export fn save(x: string): Promise\n` }; +const CLICK = `(async () => { document.querySelector(".s").click(); await new Promise((r) => setTimeout(r, 10)); document.querySelector(".f").click() })()`; +const TYPE = `(async () => { const i = document.querySelector(".q"); i.value = "slow"; i.dispatchEvent(new Event("input", { bubbles: true })); await new Promise((r) => setTimeout(r, 10)); i.value = "fast"; i.dispatchEvent(new Event("input", { bubbles: true })) })()`; +let seq = 0; +const stage = src => { const dir = path.join(root, `p${++seq}`); mkdirSync(dir, { recursive: true }); for (const [f, t] of Object.entries({ ...LIB, "main.rx": src })) writeFileSync(path.join(dir, f), t); return dir; }; +/** Both builds: what `.out` shows after the script. */ +async function ends(dir, script) { + const seen = []; + for (const production of [false, true]) { + const h = new Runner(dir, "main.rx", undefined, { production }); + try { const page = await h.open(await h.serve()); await sleep(300); await page.evaluate(script); await sleep(700); seen.push(await h.text(page, ".out") + (h.problems.length ? ` [${h.problems.join("; ").slice(0, 160)}]` : "")); } + finally { await h.close().catch(() => {}); } + } + return seen; +} +const lastShows = (seen, want = /fast$/) => seen.length === 2 && seen.every(s => want.test(s)); + +// ---------------------------------------------------------------- a handler that awaits and writes nothing itself +const HANDLERS = [ + ["an action called after the `await` (one handler, typed twice)", `import { save } from "./search.js" +export default component App() { + source shown := "none" + action put(v: string) { shown := v } +
    { try { let r = await save(e.target.value); put(r) } catch (err) { } }} />{shown}
    +} +`, TYPE, 1, null], + ["a prop's function called after the `await` (one component, typed twice)", `import { save } from "./search.js" +component Box(props: { onResult: (v: string) => void }) { + { try { let r = await save(e.target.value); props.onResult(r) } catch (err) { } }} /> +} +export default component App() { + source shown := "none" +
    { shown := v }} />{shown}
    +} +`, TYPE, 1, `import { save } from "./search.js" +component Box(props: { onAsk: (q: string) => void }) { + { props.onAsk(e.target.value) }} /> +} +export default component App() { + source shown := "none" + action load(q: string) { try { let r = await save(q); shown := r } catch (err) { } } +
    {shown}
    +} +`], + ["a prop's function, from two components", `import { save } from "./search.js" +component A(props: { onDone: (v: string) => void }) { + +} +component B(props: { onDone: (v: string) => void }) { + +} +export default component App() { + source shown := "none" +
    +} +`, CLICK, 2, `import { save } from "./search.js" +component A(props: { onAsk: (q: string) => void }) { + +} +component B(props: { onAsk: (q: string) => void }) { + +} +export default component App() { + source shown := "none" + action load(q: string) { try { let r = await save(q); shown := r } catch (e) { } } + +} +`], + ["a context's function", `import { save } from "./search.js" +context setter: (v: string) => void +component A() { + set = use setter + +} +component B() { + set = use setter + +} +export default component App() { + source shown := "none" + action put(v: string) { shown := v } + provide setter = put + +} +`, CLICK, 2, `import { save } from "./search.js" +context asker: (q: string) => void +component A() { + ask = use asker + +} +component B() { + ask = use asker + +} +export default component App() { + source shown := "none" + action load(q: string) { try { let r = await save(q); shown := r } catch (e) { } } + provide asker = load + +} +`], +]; +for (const [what, src, script, n, restructured] of HANDLERS) { + const dir = stage(src), r = both(path.join(dir, "main.rx")); + const said = r.crate.diagnostics.filter(d => d.code === "AWAIT_THEN_CALL"); + if (!check(`refused (AWAIT_THEN_CALL), by both alike: ${what}`, r.agree && said.length === n && codes(r.ref).filter(c => c === "AWAIT_THEN_CALL").length === n && r.crate.diagnostics.length === n, show(r))) continue; + if (restructured) { // a function given to it: the state's component does the waiting, as one action (another way to write it) + const d3 = stage(restructured), r3 = both(path.join(d3, "main.rx")); + if (check("…written with the waiting the state's: accepted by both", r3.agree && !r3.crate.diagnostics.length && !r3.ref.diagnostics.length, show(r3))) { + const seen = await ends(d3, script); + check(`…and the last click shows, in both builds: ${seen.join(" ")}`, lastShows(seen), seen); + } + } + // (round G: a given function's message prints the closure's steps as an action too — an action per component is a + // family per component, and AC-1l (c) orders their writes: the last click shows, measured below) + // the fix as printed: the action beside the closure (a declaration of the component it is in), the closure replaced by its call + let fixed = src; + for (const d of [...said].sort((a, b) => b.line - a.line)) { + const m = /`(action handle\d*\([^`]*\) \{[^`]*\})` beside it, and `([^`]*)` where the closure is/.exec(d.message); + if (!check(`…its message prints the closure's steps as an action and the call (${d.line})`, !!m, d.message)) break; + const lines = fixed.split("\n"), at = d.line - 1, line = lines[at]; + const body = m[1].slice(m[1].indexOf(") ") + 2), start = line.indexOf(body); const open = line.lastIndexOf("(", line.lastIndexOf("=>", start)); + lines[at] = line.slice(0, open) + m[2] + line.slice(start + body.length); + lines.splice(at, 0, " " + m[1]); + fixed = lines.join("\n"); + } + const d2 = stage(fixed), r2 = both(path.join(d2, "main.rx")); + if (!check(`…pasted as printed: accepted by both`, r2.agree && !r2.crate.diagnostics.length && !r2.ref.diagnostics.length, show(r2) + "\n" + fixed)) continue; + const seen = await ends(d2, script); + check(`…and the last click shows, in both builds: ${seen.join(" ")}`, lastShows(seen), seen); +} + +// ---------------------------------------------------------------- one source written after an `await` by two families +const TWO = [ + ["two declared actions", `import { save } from "./search.js" +export default component App() { + source shown := "none" + action loadA() { try { let r = await save("slow"); shown := r } catch (e) { } } + action loadB() { try { let r = await save("fast"); shown := r } catch (e) { } } +
    {shown}
    +} +`], + ["an action and a handler", `import { save } from "./search.js" +export default component App() { + source shown := "none" + action loadA() { try { let r = await save("slow"); shown := r } catch (e) { } } +
    {shown}
    +} +`], + ["two actions that call one helper after their `await`", `import { save } from "./search.js" +export default component App() { + source shown := "none" + action put(v: string) { shown := v } + action loadA() { try { let r = await save("slow"); put(r) } catch (e) { } } + action loadB() { try { let r = await save("fast"); put(r) } catch (e) { } } +
    {shown}
    +} +`], +]; +for (const [what, src] of TWO) { + const r = both(path.join(stage(src), "main.rx")); + check(`refused (TWO_ASYNC_WRITERS), by both alike: ${what}`, r.agree && JSON.stringify(codes(r.crate)) === '["TWO_ASYNC_WRITERS"]' && JSON.stringify(codes(r.ref)) === '["TWO_ASYNC_WRITERS"]' && /`action loadShown\((?:which: string|v1: string)\) \{ [^`]* \}`/.test(r.crate.diagnostics[0].message) && r.crate.diagnostics[0].message === r.ref.diagnostics[0].message, show(r)); +} +{ // the message's way: one action, called from each place with what tells them apart + const dir = stage(`import { save } from "./search.js" +export default component App() { + source shown := "none" + action loadShown(which: string) { try { let r = await save(which); shown := r } catch (e) { } } +
    {shown}
    +} +`); + const r = both(path.join(dir, "main.rx")); + if (check("…one action, as the message says: accepted by both", r.agree && !r.crate.diagnostics.length, show(r))) { const seen = await ends(dir, CLICK); check(`…and the last click shows, in both builds: ${seen.join(" ")}`, lastShows(seen), seen); } +} + +// ---------------------------------------------------------------- what stays accepted, and right +const KEPT = [ + ["handlers in two components writing one module source (one family: the handlers)", `import { save } from "./search.js" +source shown := "none" +component A() { + +} +component B() { + +} +export default component App() { +
    +} +`, CLICK, /fast$/], + ["a declared action that calls a prop's function after its `await`", `import { save } from "./search.js" +component Box(props: { onResult: (v: string) => void }) { + action find(q: string) { try { let r = await save(q); props.onResult(r) } catch (err) { } } + find(e.target.value)} /> +} +export default component App() { + source shown := "none" +
    { shown := v }} />{shown}
    +} +`, TYPE, /fast$/], + ["two actions writing one source functionally (every run's lands)", `import { save } from "./search.js" +export default component App() { + source log: string[] := [] + action loadA() { try { let r = await save("slow"); log := v => [...v, r] } catch (e) { } } + action loadB() { try { let r = await save("fast"); log := v => [...v, r] } catch (e) { } } +
    {log.join(",")}
    +} +`, CLICK, /fast,slow$/], + ["two actions writing their own keys of one record", `import { save } from "./search.js" +export default component App() { + source done: { a: string; b: string } := { a: "", b: "" } + action loadA() { try { let r = await save("slow"); done.a := r } catch (e) { } } + action loadB() { try { let r = await save("fast"); done.b := r } catch (e) { } } +
    {done.a}/{done.b}
    +} +`, CLICK, /slow\/fast$/], + ["a handler that awaits and calls an action before its `await`", `import { save } from "./search.js" +export default component App() { + source busy := false + action start() { busy := true } +
    {String(busy)}
    +} +`, CLICK, /true$/], +]; +for (const [what, src, script, want] of KEPT) { + const dir = stage(src), r = both(path.join(dir, "main.rx")); + if (!check(`accepted by both: ${what}`, r.agree && !r.crate.diagnostics.length && !r.ref.diagnostics.length, show(r))) continue; + const seen = await ends(dir, script); + check(`…and right, in both builds: ${seen.join(" ")}`, lastShows(seen, want), seen); +} + +console.log(`\n${pass} passed, ${fail} failed`); +process.exit(fail ? 1 : 0); diff --git a/compiler/test/callbacks.mjs b/compiler/test/callbacks.mjs new file mode 100644 index 000000000..6fb811906 --- /dev/null +++ b/compiler/test/callbacks.mjs @@ -0,0 +1,342 @@ +// 06 AC-1n (2026-12-02, re-check 15's F-A): a closure a handler gives to what calls it later — a promise's `.then`, a JS +// fn's parameter declared `handler` — wrote a source when the call came back, and of two clicks the older answer showed, +// in both builds (r15's p03, p41). Each is refused by both checkers with one message, its printed form pasted as printed: +// accepted, and the last click shows in development and production. Beside them what stays accepted: a functional write +// in such a callback, a callback an effect's apply hands out (round A's rule, p38). +// node compiler/test/callbacks.mjs +import { cpSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { spawnSync } from "node:child_process"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { ws, workspace, both, Runner } from "../../bench/harness.mjs"; + +const repo = path.join(path.dirname(fileURLToPath(import.meta.url)), "../.."); +workspace(); +const root = path.join(ws, "callbacks"); rmSync(root, { recursive: true, force: true }); mkdirSync(root, { recursive: true }); +let pass = 0, fail = 0; +const check = (name, ok, got) => { ok ? pass++ : fail++; console.log(`${ok ? "✓" : "✗"} ${name}${ok ? "" : `\n ${String(typeof got === "string" ? got : JSON.stringify(got)).slice(0, 900)}`}`); return !!ok; }; +const sleep = ms => new Promise(res => setTimeout(res, ms)); +const codes = r => r.diagnostics.map(d => d.code); +const show = r => `crate: ${codes(r.crate).join(",") || "accepted"} / ref: ${codes(r.ref).join(",") || "accepted"} — ${r.crate.diagnostics.map(d => d.message).join(" | ").slice(0, 600)}`; +const { TSCONFIG_TEXT } = await import("./pasted-cases.mjs"); +const tsc = dir => { writeFileSync(path.join(dir, "tsconfig.json"), TSCONFIG_TEXT); const r = spawnSync(process.execPath, [path.join(repo, "tooling/rx-language-server/bin/tsc.js"), "-p", "."], { cwd: dir, encoding: "utf8", timeout: 300000 }); return { status: r.status, out: `${r.stdout}${r.stderr}` }; }; +const API = { + "api.js": `export const load = (v, ms) => new Promise((r) => setTimeout(() => r(v), ms)) +export const after = (v, ms, cb) => { setTimeout(() => cb(v), ms) } +export const fail = (v, ms) => new Promise((_, no) => setTimeout(() => no(new Error(v)), ms)) +`, + "api.d.rx": `export fn load(v: string, ms: number): Promise +export fn after(v: string, ms: number, cb: handler (v: string) => void): void +export fn fail(v: string, ms: number): Promise +`, +}; +const stage = (name, src) => { + const dir = path.join(root, name); rmSync(dir, { recursive: true, force: true }); mkdirSync(dir, { recursive: true }); + cpSync(path.join(repo, "std/package.json"), path.join(dir, "node_modules/@reactivescript/std/package.json")); + cpSync(path.join(repo, "std/src"), path.join(dir, "node_modules/@reactivescript/std/src"), { recursive: true }); + for (const [f, text] of Object.entries({ ...API, "main.rx": src })) writeFileSync(path.join(dir, f), text); + return [dir, both(path.join(dir, "main.rx"))]; +}; +// ann answers in 300 ms, bob (clicked 30 ms later) in 20: the last click is bob's +const TWO = `(async () => { const b = document.querySelectorAll(".out button"); b[0].click(); await new Promise((r) => setTimeout(r, 30)); b[1].click() })()`; +async function run(dir, production) { + const h = new Runner(dir, "main.rx", undefined, { production }); + try { + const page = await h.open(await h.serve()); await sleep(300); + await page.evaluate(TWO); await sleep(700); + return { seen: (await Promise.race([h.text(page, ".out p"), sleep(3000).then(() => "")])).trim(), problems: [...h.problems] }; + } catch (e) { return { seen: `run threw: ${String(e.message ?? e).slice(0, 200)}`, problems: [...h.problems] }; } + finally { await h.close().catch(() => {}); } +} +const app = (imports, a, b) => `${imports}export default component App() { + source shown := "none" + source log: string[] := [] +
    + + +

    {shown}{log.join(",")}

    +
    +} +`; +const IMP = `import { load, after } from "./api.js"\n`; +const REFUSED = [ + ["then", "a promise's `.then` writes the panel (p03)", `load("ann", 300).then(r => { shown := r })`, `load("bob", 20).then(r => { shown := r })`], + ["then-catch", "`.then(…).catch(…)`", `load("ann", 300).then(r => { shown := r }).catch(e => { shown := "failed" })`, `load("bob", 20).then(r => { shown := r }).catch(e => { shown := "failed" })`], + ["handler-callback", "a JS fn's `handler` callback writes the panel (p41)", `after("ann", 300, v => { shown := v })`, `after("bob", 20, v => { shown := v })`], +]; +for (const [name, what, a, b] of REFUSED) { + const [, r] = stage(name, app(IMP, a, b)); + const msgs = r.crate.diagnostics.map(d => d.message); + if (!check(`${name}: ${what} — LATE_CALLBACK_WRITE twice, both checkers, the same messages`, r.agree && codes(r.crate).join() === "LATE_CALLBACK_WRITE,LATE_CALLBACK_WRITE" && JSON.stringify(msgs) === JSON.stringify(r.ref.diagnostics.map(d => d.message)), show(r))) continue; + // the printed form, pasted where the statement was (and the import it names, where it names one) + const fix = msgs.map(m => /write `([^`]*)` in place of `([^`]*)`/.exec(m)); + if (!check(`${name}: each message prints the statement to write`, fix.every(Boolean), msgs)) continue; + const imp = msgs.map(m => /\(with `(import [^`]*)`\)/.exec(m)?.[1]).find(Boolean); + let src = app(IMP + (imp ? imp + "\n" : ""), a, b); for (const f of fix) src = src.replace(f[2], f[1]); + const [dir, r2] = stage(`${name}-pasted`, src); + if (!check(`${name}, pasted: accepted by both checkers`, r2.agree && !r2.crate.diagnostics.length && !r2.ref.diagnostics.length, show(r2))) continue; + { const t = tsc(dir); check(`${name}, pasted: rx-tsc clean (the README's tsconfig)`, t.status === 0 && !/error/.test(t.out), t.out.slice(0, 600)); } + for (const production of [false, true]) { + const got = await run(dir, production); + check(`${name}, pasted (${production ? "production" : "development"}): the last click shows`, got.seen === "bob" && !got.problems.length, got); + } +} +// re-check 15 (C2): TWO_ASYNC_WRITERS printed a pattern (\`action loadShown(which: string) { … }\`); where the two actions +// differ only in literals the one action is printed whole, with each call — pasted as printed, the last click shows +{ + const src = `import { load } from "./api.js" +export default component App() { + source shown := "none" + action showUser() { try { let r = await load("ann", 300); shown := r } catch (e) { } } + action showTeam() { try { let r = await load("bob", 20); shown := r } catch (e) { } } +
    + + +

    {shown}

    +
    +} +`; + const [, r] = stage("two-actions", src), m = r.crate.diagnostics[0]?.message ?? ""; + if (check("two-actions: TWO_ASYNC_WRITERS, both checkers, one message", r.agree && codes(r.crate).join() === "TWO_ASYNC_WRITERS" && m === r.ref.diagnostics[0]?.message, show(r))) { + const x = /`(action [^`]*)` in place of the actions (\w+) and (\w+), and `([^`]*)` where `\w+\(\)` is called, `([^`]*)` where/.exec(m); + if (check("two-actions: the one action printed whole, with each call", !!x, m)) { + const lines = src.split("\n").filter(l => !l.includes(`action ${x[2]}()`) && !l.includes(`action ${x[3]}()`)); + lines.splice(3, 0, ` ${x[1]}`); + const pasted = lines.join("\n").replace(`${x[2]}()`, x[4]).replace(`${x[3]}()`, x[5]); + const [dir, r2] = stage("two-actions-pasted", pasted); + if (check("two-actions, pasted: accepted by both checkers", r2.agree && !r2.crate.diagnostics.length && !r2.ref.diagnostics.length, show(r2) + "\n" + pasted)) { + { const t = tsc(dir); check("two-actions, pasted: rx-tsc clean", t.status === 0 && !/error/.test(t.out), t.out.slice(0, 600)); } + for (const production of [false, true]) { const got = await run(dir, production); check(`two-actions, pasted (${production ? "production" : "development"}): the last click shows`, got.seen === "bob" && !got.problems.length, got); } + } + } + } +} +// Re-check 16 (F2, M1–M3): the same write through a call — a `.then` given a closure by its name, a callback that calls a +// closure, an action or a prop's function, a prop's function handed to a library — was accepted, and the older answer +// showed (q48, q51–q53, q55); a handler with no braces was not read at all. Each is refused now, and what each message +// prints is applied here as it is printed, message after message until both checkers accept: then rx-tsc is clean and +// the last click shows in both builds. The same for a `.finally` (M1: its steps are the `finally`, and a write before the +// `await` is `onFlush`'s), a `.catch` alone, AWAIT_THEN_CALL's actions (M2: a name each) and an action beside a handler +// (M3: TWO_ASYNC_WRITERS prints the one action whole). +const applyPrinted = (src, msgs, anchor) => { + const put = line => { src = src.replace(anchor, `${line}\n ${anchor}`); }; + for (const m of msgs) { + let x; + if ((x = /write `(action \w+\(\) \{[^`]*\})` beside the declarations of the block this is in \(the component's, or a `for`'s\), and `([^`]*)` in place of `([^`]*)`/.exec(m))) { src = src.replace(x[3], x[2]); put(x[1]); } + else if ((x = /write `([^`]*)` in place of `([^`]*)`/.exec(m))) src = src.replace(x[2], x[1]); + else if ((x = /`(action \w+(\([^`)]*\)) (\{[^`]*\}))` beside it, and `([^`]*)` where the closure is/.exec(m))) { src = src.replace(`${x[2]} => ${x[3]}`, x[4]); put(x[1]); } + else if ((x = /in one action, which both call with what tells them apart: `(action [^`]*)` (?:in place of the actions? ([\w ]+?)|beside the declarations), and (.*)$/.exec(m))) { + for (const n of (x[2] ?? "").split(" and ").filter(Boolean)) src = src.split("\n").filter(l => !l.includes(`action ${n}()`)).join("\n"); + for (const c of x[3].matchAll(/`([^`]*)` (?:where `(\w+\(\))` is called|in place of the handler's steps `([^`]*)`)/g)) src = src.replaceAll(c[2] ?? c[3], c[1]); + put(x[1]); + } else return null; + for (const y of m.matchAll(/, and `(onFlush\([^`]*\))` in place of `([^`]*)`/g)) src = src.replace(y[2], y[1]); + const imp = /\(with `(import [^`]*)`\)/.exec(m)?.[1]; if (imp && !src.includes(imp)) src = `${imp}\n${src}`; + } + return src; +}; +const BOX = `export default component App() { + source shown := "none" +
    + { shown := r }} /> + { shown := r }} /> +

    {shown}

    +
    +} +`; +const one = (decls, a, b) => `import { load, after, fail } from "./api.js" +export default component App() { + source shown := "none" +${decls}
    + + +

    {shown}

    +
    +} +`; +const CTX = `export default component App() { + source shown := "none" + action put(v: string) { shown := v } + provide panel = { put: put } +

    {shown}

    +} +`; +// [name, what, source, the line a printed declaration goes above, the codes of each round, the text at the end] +const THROUGH = [ + ["then-named", "`.then(done)`, a closure that writes given by its name (q48)", one("", `() => { let done = (r: string) => { shown := r }; load("ann", 300).then(done) }`, `() => { let done = (r: string) => { shown := r }; load("bob", 20).then(done) }`), `
    `, ["LATE_CALLBACK_WRITE,LATE_CALLBACK_WRITE"]], + ["then-local-call", "a `.then` callback calls a closure of the handler that writes (q53)", one("", `() => { let put = (r: string) => { shown := r }; load("ann", 300).then(r => put(r)) }`, `() => { let put = (r: string) => { shown := r }; load("bob", 20).then(r => put(r)) }`), `
    `, ["LATE_CALLBACK_WRITE,LATE_CALLBACK_WRITE"]], + ["then-action", "a `.then` callback calls an action that writes (q52): an action each, then the one action", one(` action set(r: string) { shown := r }\n`, `() => { load("ann", 300).then(r => set(r)) }`, `() => { load("bob", 20).then(r => set(r)) }`), `
    `, ["LATE_CALLBACK_WRITE,LATE_CALLBACK_WRITE", "TWO_ASYNC_WRITERS"]], + ["then-action-name", "`.then(set)`, an action given by its name, in a handler with no braces", one(` action set(r: string) { shown := r }\n`, `() => load("ann", 300).then(set)`, `() => load("bob", 20).then(set)`), `
    `, ["LATE_CALLBACK_WRITE,LATE_CALLBACK_WRITE", "TWO_ASYNC_WRITERS"]], + ["bare-then", "a handler with no braces whose `.then` writes", one("", `() => load("ann", 300).then(r => { shown := r })`, `() => load("bob", 20).then(r => { shown := r })`), `
    `, ["LATE_CALLBACK_WRITE,LATE_CALLBACK_WRITE"]], + ["then-prop", "a child's `.then` callback calls a prop's function (q51)", `import { load } from "./api.js" +component Btn(props: { v: string; ms: number; onDone: (r: string) => void }) { + +} +${BOX}`, ` +} +${BOX}`, ` +} +${CTX}`, ` +} +${CTX}`, ` +} +export default component App() { + source shown := "none" + action put(v: string) { shown := v } + api = { put: put } +

    {shown}

    +} +`, ` +} +${CTX}`, ` +} +${CTX}`, ` +

    {busy ? "busy" : "idle"} {shown}

    +
    +} +`; + const [, r] = stage("finally", src), msgs = r.crate.diagnostics.map(d => d.message); + if (check("finally: LATE_CALLBACK_WRITE once, both checkers, the same message", r.agree && codes(r.crate).join() === "LATE_CALLBACK_WRITE" && msgs[0] === r.ref.diagnostics[0]?.message, show(r))) { + const pasted = applyPrinted(src, msgs, `
    `); + check("finally: the printed form keeps the `finally`'s steps and gives the flag to `onFlush`", /finally \{ busy := false \}/.test(pasted ?? "") && /onFlush\(\(\) => \{ busy := true \}\)/.test(pasted ?? ""), msgs[0]); + const [dir, r2] = stage("finally-pasted", pasted ?? src); + if (check("finally, pasted: accepted by both checkers", r2.agree && !r2.crate.diagnostics.length && !r2.ref.diagnostics.length, show(r2) + "\n" + pasted)) { + { const t = tsc(dir); check("finally, pasted: rx-tsc clean", t.status === 0 && !/error/.test(t.out), t.out.slice(0, 600)); } + for (const production of [false, true]) { + const h = new Runner(dir, "main.rx", undefined, { production }); + try { + const page = await h.open(await h.serve()); await sleep(300); + await page.evaluate(`document.querySelector(".out button").click()`); await sleep(100); + const during = (await h.text(page, ".out p")).trim(); await sleep(600); + const end = (await h.text(page, ".out p")).trim(); + check(`finally, pasted (${production ? "production" : "development"}): busy while it waits, then idle with the answer`, during === "busy none" && end === "idle ann" && !h.problems.length, { during, end, problems: h.problems }); + } catch (e) { check(`finally, pasted (${production ? "production" : "development"})`, false, String(e.message ?? e)); } + finally { await h.close().catch(() => {}); } + } + } + } +} +// M5 (re-check 16): `pending? x` of a source that asks nothing, written only after an `await`, with no `affects x`: it +// stayed false and nothing said so (q66, q67). Advice now (PENDING_NEVER), with the statement to write; pasted as the +// first statement of the action it names, the flag is true while the action runs, in both builds. Not advised: with +// `affects`, and where the action writes the source before its `await` (a held write is pending). +{ + const prog = body => `import { load } from "./api.js" +export default component App() { + source title := "old" + action rename(v: string) { ${body} } +
    + +

    {title}{pending? title ? " (saving)" : ""}

    +
    +} +`; + const adv = x => (x.advice ?? []).filter(d => d.code === "PENDING_NEVER"); + const src = prog(`try { let r = await load(v, 300); title := r } catch (e) { }`); + const [, r] = stage("pending-never", src); + if (check("pending-never: accepted, PENDING_NEVER advised by both checkers with the same message", r.agree && !r.crate.diagnostics.length && !r.ref.diagnostics.length && adv(r.crate).length === 1 && adv(r.ref).length === 1 && adv(r.crate)[0].message === adv(r.ref)[0].message, show(r) + JSON.stringify([adv(r.crate), adv(r.ref)]))) { + const m = /write `(affects \w+)` as the first statement of `action (\w+)` \(line (\d+)\)/.exec(adv(r.crate)[0].message); + if (check("pending-never: the advice prints the statement and names the action and its line", !!m && m[2] === "rename" && src.split("\n")[Number(m?.[3]) - 1]?.includes("action rename"), adv(r.crate)[0].message)) { + const [dir, r2] = stage("pending-never-pasted", src.replace("action rename(v: string) { ", `action rename(v: string) { ${m[1]}; `)); + if (check("pending-never, pasted: accepted by both checkers, nothing advised", r2.agree && !r2.crate.diagnostics.length && !r2.ref.diagnostics.length && !adv(r2.crate).length && !adv(r2.ref).length, show(r2))) { + { const t = tsc(dir); check("pending-never, pasted: rx-tsc clean", t.status === 0 && !/error/.test(t.out), t.out.slice(0, 600)); } + for (const production of [false, true]) { + const h = new Runner(dir, "main.rx", undefined, { production }); + try { + const page = await h.open(await h.serve()); await sleep(300); + await page.evaluate(`document.querySelector(".out button").click()`); await sleep(100); + const during = (await h.text(page, ".out p")).trim(); await sleep(600); + const end = (await h.text(page, ".out p")).trim(); + check(`pending-never, pasted (${production ? "production" : "development"}): pending while the action runs, then the answer`, during === "old (saving)" && end === "new" && !h.problems.length, { during, end, problems: h.problems }); + } catch (e) { check(`pending-never, pasted (${production ? "production" : "development"})`, false, String(e.message ?? e)); } + finally { await h.close().catch(() => {}); } + } + } + } + } + for (const [name, body] of [["pending-held", `title := v; try { let r = await load(v, 300) } catch (e) { }`], ["pending-affects", `affects title; try { let r = await load(v, 300); title := r } catch (e) { }`]]) { + const [, r3] = stage(name, prog(body)); + check(`${name}: accepted by both checkers, PENDING_NEVER not advised`, r3.agree && !r3.crate.diagnostics.length && !r3.ref.diagnostics.length && !adv(r3.crate).length && !adv(r3.ref).length, show(r3) + JSON.stringify([adv(r3.crate), adv(r3.ref)])); + } +} +// what stays accepted +const KEPT = [ + ["then-functional", "a `.then` that appends functionally: both land", `load("ann", 300).then(r => { log := v => [...v, r] })`, `load("bob", 20).then(r => { log := v => [...v, r] })`, "nonebob,ann"], +]; +for (const [name, what, a, b, want] of KEPT) { + const [dir, r] = stage(name, app(IMP, a, b)); + if (!check(`${name}: ${what} — accepted by both checkers`, r.agree && !r.crate.diagnostics.length && !r.ref.diagnostics.length, show(r))) continue; + for (const production of [false, true]) { const got = await run(dir, production); check(`${name} (${production ? "production" : "development"}): ends on ${JSON.stringify(want)}`, got.seen === want && !got.problems.length, got); } +} +{ const [, r] = stage("effect-then", `import { load } from "./api.js" +export default component App() { + source q := "a" + source shown := "none" + effect (q) { load($0, 10).then(r => { shown := r }) } +

    {shown}

    +} +`); check("effect-then: a callback an effect's apply hands out (p38) — accepted by both checkers", r.agree && !r.crate.diagnostics.length && !r.ref.diagnostics.length, show(r)); } +console.log(`\n${pass} passed, ${fail} failed`); +process.exit(fail ? 1 : 0); diff --git a/compiler/test/confined.mjs b/compiler/test/confined.mjs new file mode 100644 index 000000000..391e97861 --- /dev/null +++ b/compiler/test/confined.mjs @@ -0,0 +1,412 @@ +// CN-7, 09 MO-10k (closed 2026-11-22): counterexamples of the fourth review, kept. Each was accepted by both checkers +// and did at run time what its rule says cannot happen; each is now refused — or, for a draft, made a copy — and this +// runs both halves: the verdict of the crate and of ref/ (which must agree), and what the program does when it runs. The +// safe forms beside each are still accepted, and run. +// - RFC 09: `d.items.forEach((row) => { kept.push(row) })` and `d.items.values()` — live rows and a live iterator +// left the callback; reading them after the library took its draft back threw "proxy revoked". +// - RFC 14/34: `box = { read: () => n }; peek box.read()` and `createLabel(box.read())` — a closure kept in a record +// lost what its body reads, and the value was frozen. +// Three more were here until 2026-11-23, for values no declaration makes any more (MO-8r): a result with held plain +// fields (RFC 06, `pending`/`fails(…)` on a field; before a `ref` part they are MO-10l's, and S-module-36's to hold), a +// `renders` value (RFC 17, `renders` alone), and a router's carried components (RFC 18, `renders(later)`: a route tree +// is given to a factory now, S-module-22 and S-module-23). +// The probes of this kind that bench/ once held as "mistakes" live here (2026-11-22): they are not what a Solid user +// writes by accident, they are what a review writes to find the edge of a rule. +// Needs what bench/run.mjs needs (the crate, the runtime's build, bench/.out/ws). node compiler/test/confined.mjs +import { mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import path from "node:path"; +import { ws, workspace, both, Runner } from "../../bench/harness.mjs"; + +workspace(); +const dir = path.join(ws, "confined"); rmSync(dir, { recursive: true, force: true }); mkdirSync(dir, { recursive: true }); +writeFileSync(path.join(dir, "lib.d.rx"), [ + "export pure fn createStore(init: T): [T, (update: (draft state: T) => T | void) => void]", + "export pure fn makeClock(): any instantiates", + "export pure fn createLabel(text: any): ref string", + "export pure fn createWatcher(label: string): ref string", + "export pure fn createFailing(): ref string", + "export component Run(props: { go: handler () => void })", + "export fn sink(label: string, x: any): void", + "export fn reverseIt(list: any[]): void", + "export pure fn clone(x: T): T", + "export pure fn same(x: T): T", + "export fn cloneable(x: any): string", + "export fn tagFirst(xs: { tags: string[] }[]): void", + "export pure fn makeChannel(): { post: (x: any) => string }", + "export fn other(x: any): string", + "export fn pick(): (x: any) => string", + "export const fns: ((x: any) => string)[]", + "export pure fn makeBox(): { put: (x: any) => string }", + "export fn tagRow(r: { tags: string[] }): void", + "export fn fillIn(o: any): string", + "export fn record(x: any): void", + "export fn lastResult(): string", + "export class Bag(xs: string[]): { n: number; add: (x: string) => number }", + "export class Keeper(xs: string[]): { add: (x: string) => number } instantiates", + 'export type Handle = import("./lib.js").Handle', + "export pure fn makeHandle(): Handle", + 'export type Options = import("./lib.js").Options', + "export pure fn makeOptions(): Options", + "", +].join("\n")); +writeFileSync(path.join(dir, "lib.js"), ` +import { createSignal, createMemo, onCleanup } from "solid-js"; +// MO-10a: a primitive that registers a cleanup where it is made, and one that fails while it is made +export const createWatcher = label => { onCleanup(() => { document.title += "|gone:" + label; }); return () => label; }; +export const createFailing = () => { throw new Error("made badly"); }; +export const sunk = {}; +export const sink = (label, x) => { sunk[label] = x; }; +export const reverseIt = list => { list.reverse(); }; +export const clone = x => structuredClone(x); +export const same = x => x; +// N5-1: what clones what it is given (structuredClone, as postMessage, history.pushState and IndexedDB do), a JS object's +// method that does, and a helper that changes what it is given in the call +export const cloneable = x => { try { structuredClone(x); return "ok"; } catch (e) { return e.name; } }; +export const tagFirst = xs => { xs[0].tags.push("x"); }; +export const makeChannel = () => ({ post: x => cloneable(x) }); +// N6-2: a JS fn reached as a value — what another answers, an item of a list, a method of a record a let holds; a helper +// that changes the row it is given; N6-3: a helper that fills in the options it is given, as many libraries do +export const other = x => "other"; +export const pick = () => cloneable; +export const fns = [cloneable]; +export const makeBox = () => ({ put: x => cloneable(x) }); +export const tagRow = r => { r.tags.push("x"); }; +export const fillIn = o => { o.opts.tries ??= 1; return cloneable(o.rows) + "/" + o.opts.tries; }; +let last = "none"; +export const record = x => { last = cloneable(x); }; +export const lastResult = () => last; +// R10-1, R10-2: a class instance a source holds; a library that keeps what it is given and pushes into it later (Fuse) +export class Bag { constructor(xs) { this.xs = xs; this.n = 0; } add(x) { this.xs.push(x); return this.xs.length; } } +export class Keeper { constructor(xs) { this.kept = xs; } add(x) { this.kept.push(x); return this.kept.length; } } +export const Run = props => { props.go(); return ""; }; +// K-1: a factory that answers a class instance (typed by an interface: tippy's Instance, noUiSlider's API), and one that +// answers a plain record +class HandleImpl { constructor() { this.n = 1; this.label = "a"; } describe() { return this.label + this.n; } } +export const makeHandle = () => new HandleImpl(); +export const makeOptions = () => ({ speed: 1, mode: "slow" }); +// a store whose setter takes its draft back: every object it hands the callback is revoked when the setter returns +export const createStore = init => { + const state = init; + const set = f => { + const revokes = []; const made = new WeakMap(); const targets = new WeakMap(); + const wrap = o => { + if (o === null || typeof o !== "object") return o; + if (made.has(o)) return made.get(o); + const { proxy, revoke } = Proxy.revocable(o, { get: (t, k, r) => { const v = Reflect.get(t, k, r); return typeof v === "function" ? v : wrap(v); }, set: (t, k, v) => Reflect.set(t, k, targets.get(v) ?? v) }); + made.set(o, proxy); targets.set(proxy, o); revokes.push(revoke); return proxy; + }; + try { f(wrap(state)); } finally { for (const r of revokes) r(); } + }; + return [state, set]; +}; +export const makeClock = () => ({ now: () => Date.now(), format: () => "noon" }); +export const createLabel = text => { const made = "[" + text + "]"; return () => made; }; +`); +let pass = 0, fail = 0; +const check = (name, ok, got) => { ok ? pass++ : fail++; console.log(`${ok ? "✓" : "✗"} ${name}${ok ? "" : `\n ${String(typeof got === "string" ? got : JSON.stringify(got)).slice(0, 700)}`}`); }; +const head = 'import { createStore, makeClock, createLabel, createWatcher, createFailing, Run, sink, reverseIt, clone, same, cloneable, tagFirst, makeChannel, other, pick, fns, makeBox, tagRow, fillIn, record, lastResult, Bag, Keeper, makeHandle, makeOptions } from "./lib.js"\n'; +let seq = 0; +const file = src => { const f = path.join(dir, `p${++seq}.rx`); writeFileSync(f, head + src); return f; }; +const show = r => `crate: ${r.crate.diagnostics.map(d => d.code).join(",") || "accepted"} / ref: ${r.ref.diagnostics.map(d => d.code).join(",") || "accepted"}`; +/** Refused by both checkers, alike, with `code`. */ +const refused = (name, code, src) => { const r = both(file(src)); check(`refused (${code}): ${name}`, r.agree && r.crate.diagnostics.some(d => d.code === code) && r.ref.diagnostics.some(d => d.code === code), show(r)); }; +/** Accepted by both checkers; returns a runner for its compiled program. */ +const accepted = (name, src) => { const f = file(src); const r = both(f); const ok = r.agree && !r.crate.diagnostics.length && !r.ref.diagnostics.length; check(`accepted: ${name}`, ok, `${show(r)} ${r.crate.diagnostics.map(d => d.message).join(" | ").slice(0, 400)}`); return ok ? new Runner(dir, path.basename(f)) : null; }; +const lib = await import(pathToFileURL(path.join(dir, "lib.js")).href); + +// ---------------------------------------------------------------- RFC 09: a library's draft +const store = body => `export default component App() {\n [todos, setTodos] = createStore<{ items: { n: number }[] }>({ items: [{ n: 0 }] })\n { ${body} }} />\n}\n`; +const draft = async (name, body, after) => { + const h = accepted(name, store(body)); if (!h) return; + for (const k of Object.keys(lib.sunk)) delete lib.sunk[k]; + const r = await h.ssr("/"); + // lib.js is one module for the test and the program: what the program sank is read here, after the setter returned + let got, threw = r.error; try { got = after(lib.sunk); } catch (e) { threw = e; } + check(`…and what left the callback is read after the library took its draft back: ${JSON.stringify(got)}`, !threw && got !== false, threw?.message ?? got); + await h.close(); +}; +await draft("rows a forEach callback kept", 'let kept = []; setTodos((d) => { d.items.forEach((row) => { kept.push(row) }) }); sink("row", kept[0])', s => s.row.n === 0 && s.row); +await draft("the draft's iterator", 'setTodos((d) => { sink("iter", d.items.values()) })', s => { const xs = [...s.iter]; return xs.length === 1 && xs[0].n === 0 && xs; }); +await draft("an iterator held in a local, stepped later", 'let its = []; setTodos((d) => { let it = d.items.values(); its.push(it) }); sink("first", its[0].next().value)', s => s.first.n === 0 && s.first); +await draft("what map and find answer", 'setTodos((d) => { sink("mapped", d.items.map((row) => row)); sink("found", d.items.find((row) => row.n == 0)) })', s => s.mapped[0].n === 0 && s.found.n === 0 && [s.mapped, s.found]); +await draft("a loop that adds to the list it loops over visits what was there when it started", 'setTodos((d) => { for (const row of d.items) { if (len(d.items) < 3) { d.items.push({ n: 7 }) }; row.n := 1 } }); sink("items", todos.items)', s => JSON.stringify(s.items) === '[{"n":1},{"n":7}]' && s.items); +await draft("a loop over the draft writes it (the safe form)", 'setTodos((d) => { for (const row of d.items) { row.n := 5 } }); sink("items", todos.items)', s => s.items[0].n === 5 && s.items); +await draft("a callback of the draft's own method writes its rows", 'setTodos((d) => { d.items.forEach((row) => { row.n := 9 }) }); sink("items", todos.items)', s => s.items[0].n === 9 && s.items); +refused("a function made elsewhere, given to a draft's forEach", "DRAFT_ESCAPES", store('let kept = []; let keep = (row) => { kept.push(row) }; setTodos((d) => { d.items.forEach(keep) })')); +refused("a method of the draft that is not plain data's", "DRAFT_ESCAPES", store('setTodos((d) => { d.items.each((row) => { sink("row", row) }) })')); +refused("a bound method of the draft", "DRAFT_ESCAPES", store('setTodos((d) => { sink("push", d.items.push.bind(d.items)) })')); +refused("a closure in a forEach callback that names the row later", "DRAFT_ESCAPES", store('let later = []; setTodos((d) => { d.items.forEach((row) => { later.push(() => row) }) })')); +{ // what the copies are for: the same rows, kept where nothing copies, are the library's revoked proxies + const [, set] = lib.createStore({ items: [{ n: 0 }] }); const kept = []; set(d => { d.items.forEach(row => { kept.push(row); }); }); + let threw = null; try { void kept[0].n; } catch (e) { threw = e; } + check("unchecked, a row kept by a forEach callback is a revoked proxy", /revoked/.test(threw?.message ?? ""), threw); +} + +{ // MO-10i (2026-11-22): a JS fn that is lent a copy of a draft and changes it. The change would be lost; in a development + // build it is refused where it is made, by an error that names the missing word — never a silent no-op + const h = accepted("a JS fn whose parameter is not `draft`, given a read of the draft", `export default component App() {\n [todos, setTodos] = createStore<{ items: { n: number }[] }>({ items: [{ n: 0 }, { n: 1 }] })\n \n}\n`); + if (h) { + const base = await h.serve(); const page = await h.open(base); + await page.click(".b"); await new Promise(r => setTimeout(r, 200)); + check("…changing what it was lent is an error in a development build, and says which word is missing", h.problems.some(p => /reverseIt\(…\) changed what it was given/.test(p) && /`draft`/.test(p)), h.problems); + await h.close(); + } +} + +{ // MO-10i (2026-11-29): a JS fn whose parameter is not `draft`, given a source's value: the store's own object reached the + // helper, and Solid dropped what it changed in place, in silence but for its own warning (newcomer test 2, entry 8). It + // is lent behind the same guard: in a development build the change is an error that names the fn and the fix + const h = accepted("a JS fn whose parameter is not `draft`, given a source's list in a handler", `export default component App() {\n source xs := [{ n: 0 }, { n: 1 }]\n \n}\n`); + if (h) { + const base = await h.serve(); const page = await h.open(base); + await page.click(".b"); await new Promise(r => setTimeout(r, 200)); + check("…changing a source's value in place is an error in a development build, naming the fn and the write to make", h.problems.some(p => /reverseIt\(…\) changed what it was given — its first argument, at \[0\] \(another object put there\): the value of a source/.test(p) && /changes only by a write, `:=`/.test(p)), h.problems); + check("…and the list is as it was", (await h.text(page, ".b")) === "0,1", await h.text(page, ".b")); + await h.close(); + } +} + +{ // MO-10i (2026-11-30, the fourth review's N4-3): what a JS fn is lent is the value itself, in both builds — the guard was a + // Proxy in a development build, and a correct program did otherwise there than in production: `structuredClone` of a + // source's list threw DataCloneError (r4/cost/p07), and a row a helper answered as it was given (`same(row)`), written + // to a second path, was lost (r4/srt/a4h). Each runs in Solid's development build and in its production build, and both + // show the same frames + const progs = [ + ["structuredClone of a source's list, changed and written back (r4 p07)", `export default component App() {\n source todos: { id: number; tags: string[] }[] := [{ id: 1, tags: ["x"] }, { id: 2, tags: [] }]\n \n}\n`, [".b"], ["x", "x new"]], + ["a row a helper answers as it was given, written to a second path after a path write (r4 a4h)", `type R = { n: number }\nexport default component App() {\n source st: { cur: R; rows: R[] } := { cur: { n: 0 }, rows: [{ n: 0 }] }\n
    {st.cur.n} {st.rows[0].n}
    \n}\n`, [".bump", ".pick"], ["bumppick0 0", "bumppick0 7", "bumppick7 7"]], + ]; + for (const [name, src, clicks, want] of progs) { + const h = accepted(name, src); if (!h) continue; + for (const production of [false, true]) { + const r = new Runner(dir, path.basename(h.entry), undefined, { production }); + const base = await r.serve(); const page = await r.open(base); const seen = [await r.text(page, ".b")]; + for (const c of clicks) { await page.click(c); await new Promise(res => setTimeout(res, 150)); seen.push(await r.text(page, ".b")); } + check(`…in Solid's ${production ? "production" : "development"} build: ${want.join(" → ")}, and nothing on the console`, JSON.stringify(seen) === JSON.stringify(want) && !r.problems.length, { seen, problems: r.problems }); + await r.close(); + } + } +} + +{ // MO-10i (2026-12-01, the fifth review's N5-1): what JavaScript is lent is decided by where the value comes from, not by + // how the argument is spelled. A list or a record written around a source, a field inside one, an equation over a + // source, a mapped copy and a row each reached JavaScript as Solid's store proxies, in both builds: what clones threw + // DataCloneError (r5/s/g12, r5/cost/n15's history.pushState({ nums })), and a helper's change through them got Solid's + // generic warning in dev and was lost in production (r5/s/g13). A JS object's method is lent its arguments too + // (`worker.postMessage({ type, items })`). Each runs in Solid's development build and in its production build + const shapes = [["array", "[todos]"], ["record", "{ items: todos }"], ["nested", "{ a: { b: todos[0].tags } }"], ["equation", "sorted"], ["map", "todos.map((t) => t)"], ["row", "todos[0]"]]; + const h = accepted("structuredClone of each shape of a source's value, and a JS object's method given a record around one", `type Row = { id: number; tags: string[] }\nexport default component App() {\n source todos: Row[] := [{ id: 2, tags: ["a"] }, { id: 1, tags: [] }]\n sorted = todos.toSorted((a, b) => a.id - b.id)\n ch = makeChannel()\n source out := ""\n
    \n${shapes.map(([k, x]) => ` \n`).join("")} \n

    {out}

    \n
    \n}\n`); + if (h) { + const want = [...shapes.map(([k]) => `${k} ok`), "post ok"].join(" "); + for (const production of [false, true]) { + const r = new Runner(dir, path.basename(h.entry), undefined, { production }); + const base = await r.serve(); const page = await r.open(base); + for (const c of [...shapes.map(([k]) => k), "post"]) { await page.click("." + c); await new Promise(res => setTimeout(res, 100)); } + const got = (await r.text(page, ".o")).trim(); + check(`…in Solid's ${production ? "production" : "development"} build each is cloned: ${want}, and nothing on the console`, got === want && !r.problems.length, { got, problems: r.problems }); + await r.close(); + } + } + const m = accepted("a helper that changes the rows of an equation over a source, in the call", `type Row = { id: number; tags: string[] }\nexport default component App() {\n source todos: Row[] := [{ id: 2, tags: [] }, { id: 1, tags: [] }]\n sorted = todos.toSorted((a, b) => a.id - b.id)\n

    {todos.map((t) => t.id + ":" + t.tags.join("")).join(" ")}

    \n}\n`); + if (m) { + const base = await m.serve(); const page = await m.open(base); + await page.click(".eq"); await page.click(".rec"); await new Promise(res => setTimeout(res, 200)); + check("…in a development build the change is the guard's error, naming the fn, the place and the write to make — through the equation and through a list written around it", m.problems.filter(p => /tagFirst\(…\) changed what it was given — its first argument, at \[0\]\.tags \(its length 0 → 1\): a value made from the program's state/.test(p) && /changes only by a write, `:=`/.test(p)).length === 2, m.problems); + check("…and the source is as it was", (await m.text(page, ".v")) === "2: 1:", await m.text(page, ".v")); + await m.close(); + } +} + +{ // MO-10i (2026-12-01, the sixth review's N6-2): what is lent is decided by what the callee is, not by how the call is + // written. A JS fn given point-free to a list's own method, held in a local, picked by `?:`, answered by a call, taken + // from a list or called through a record a `let` holds — or given to a `.rx` fn that calls it — got Solid's store + // proxies in both builds (r6/s/L1: DataCloneError from each). And (N6-3) a record written at the call is the call's own + // whatever it holds: a helper that fills in a nested options record (`fillIn({ rows: todos, opts: {} })`) threw in + // the development build only (r6/s/L3) + const shapes = [["mapfn", "", "todos.map(cloneable).join(\",\")", "ok,ok"], ["foreach", "todos.forEach(record); ", "lastResult()", "ok"], ["alias", "let g = cloneable; ", "g(todos)", "ok"], ["callres", "", "pick()(todos)", "ok"], ["cond", "", "(flag ? cloneable : other)(todos)", "ok"], ["index", "", "fns[0](todos)", "ok"], ["box", "let b = makeBox(); ", "b.put(todos)", "ok"], ["viarx", "", "apply(cloneable, todos)", "ok"], ["nested", "", "fillIn({ rows: todos, opts: {} })", "ok/1"]]; + const h = accepted("a JS fn reached as a value, given what clones it; a nested options record filled in", `type Row = { id: number; tags: string[] }\nfn apply(f: (x: Row[]) => string, x: Row[]): string => f(x)\nexport default component App() {\n source todos: Row[] := [{ id: 2, tags: ["a"] }, { id: 1, tags: [] }]\n source flag := true\n source out := ""\n
    \n${shapes.map(([k, pre, x]) => ` \n`).join("")}

    {out}

    \n
    \n}\n`); + if (h) { + const want = shapes.map(([k, , , w]) => `${k} ${w}`).join(" "); + for (const production of [false, true]) { + const r = new Runner(dir, path.basename(h.entry), undefined, { production }); + const base = await r.serve(); const page = await r.open(base); + for (const [c] of shapes) { await page.click("." + c); await new Promise(res => setTimeout(res, 100)); } + const got = (await r.text(page, ".o")).trim(); + check(`…in Solid's ${production ? "production" : "development"} build each is given plain values: ${want}, and nothing on the console`, got === want && !r.problems.length, { got, problems: r.problems }); + await r.close(); + } + } + const m = accepted("a JS fn given point-free to a source's forEach, that changes the row it is given", `type Row = { id: number; tags: string[] }\nexport default component App() {\n source todos: Row[] := [{ id: 2, tags: [] }, { id: 1, tags: [] }]\n

    {todos.map((t) => t.id + ":" + t.tags.join("")).join(" ")}

    \n}\n`); + if (m) { + const base = await m.serve(); const page = await m.open(base); + await page.click(".fe"); await new Promise(res => setTimeout(res, 200)); + check("…in a development build the change is the guard's error, naming the fn and the place (it was Solid's generic warning, and lost in production)", m.problems.some(p => /tagRow\(…\) changed what it was given — the rows it was called with, at \[0\]\.tags \(its length 0 → 1\)/.test(p)), m.problems); + check("…and the source is as it was", (await m.text(page, ".v")) === "2: 1:", await m.text(page, ".v")); + await m.close(); + } +} + +{ // MO-10i (2026-12-02, the seventh review's N7-2): a JS fn is lent where it enters a value the program makes, too — a + // record or a list written out (`let h = { f: cloneable }`, `[cloneable][0]`, a list of commands, a prop's record), a + // context's value (`provide saver = { save: cloneable, … }`, `provide fnctx = cloneable`) and a `.rx` fn's answer + // (`fn chooser(b) => b ? cloneable : other`). Each got Solid's store proxies in both builds (r7/s/N1-lend7, N1b, N1c: + // DataCloneError), and r7's notes app, its IndexedDB service given by context, failed on its first save + const h = accepted("a JS fn written into a record, a list, a context, a prop's record, a list of commands, or answered by a fn", `type Row = { id: number; tags: string[] } +type Cmd = { label: string; run: (x: any) => string } +fn chooser(b: boolean) => b ? cloneable : other +context saver: { save: (x: any) => string; rows: Row[] } +context fnctx: (x: any) => string +component Reader() { + sv = use saver + f = use fnctx + source r := "" + {r} +} +component Kid(props: { api: { save: (x: any) => string }; cmds: Cmd[]; rows: Row[] }) { + source r := "" + {for c in props.cmds { }}{r} +} +export default component App() { + source todos: Row[] := [{ id: 2, tags: ["a"] }, { id: 1, tags: [] }] + source out := "" + commands = [{ label: "export", run: cloneable }, { label: "noop", run: other }] + provide saver = { save: cloneable, rows: todos } + provide fnctx = cloneable +
    + + + + {for c in commands { }} + + +

    {out}

    +
    +} +`); + if (h) { + const clicks = ["reclit", "listlit", "fnret", "cexport", "cnoop", "ctx", "ctxfn", "proprec", "pexport"]; + const want = { o: "reclit ok listlit ok fnret ok cexport ok cnoop other", r1: "ctx ok ctxfn ok", r2: "proprec ok pexport ok" }; + for (const production of [false, true]) { + const r = new Runner(dir, path.basename(h.entry), undefined, { production }); + const base = await r.serve(); const page = await r.open(base); + for (const c of clicks) { await page.click("." + c); await new Promise(res => setTimeout(res, 100)); } + const got = { o: (await r.text(page, ".o")).trim(), r1: (await r.text(page, ".r1")).trim(), r2: (await r.text(page, ".r2")).trim() }; + check(`…in Solid's ${production ? "production" : "development"} build each is given plain values: ${JSON.stringify(want)}, and nothing on the console`, JSON.stringify(got) === JSON.stringify(want) && !r.problems.length, { got, problems: r.problems }); + await r.close(); + } + } +} + +// ---------------------------------------------------------------- R10-1: a path into what a source holds whole (re-check 10) +// A source whose value is no record and no list is a signal, and its path writer throws ("a path write to an atomic +// source"): accepted, `video.volume := $0` in an effect halted the page at mount (r10/c1 R12c), and `canvas.width :=` in a +// handler threw on every click (R10). Refused, WRITE_TO_NON_SOURCE, with the JavaScript helper that sets it printed whole. +{ + const el = (ty, decl, body) => `export default component App() {\n source el: ${ty} | null := null\n source vol := 1\n${decl}
    { el := x }} width="100" />
    \n}\n`; + refused("an element's property by the source that holds it, in a handler (r10 R10)", "WRITE_TO_NON_SOURCE", el("HTMLCanvasElement", "", "if (el) { el.width := 300 }")); + refused("…in an effect, the element read by its name (R12c)", "WRITE_TO_NON_SOURCE", el("HTMLCanvasElement", " effect (vol) { if (el) { el.width := $0 * 300 } }\n", "")); + refused("…under peek (R12b)", "WRITE_TO_NON_SOURCE", el("HTMLCanvasElement", " effect (vol) { if (peek(el)) { el.width := $0 * 300 } }\n", "")); + refused("a class instance's field (R11, signature_pad's `pad.penColor = …`)", "WRITE_TO_NON_SOURCE", `export default component App() {\n source bag: Bag | null := null\n effect () { bag := new Bag(["a"]) }\n \n}\n`); + refused("a record that begins as null (its slot is a signal too)", "WRITE_TO_NON_SOURCE", `type User = { name: string }\nexport default component App() {\n source user: User | null := null\n \n}\n`); + { const r = both(file(el("HTMLVideoElement", " effect (el, vol) { if ($0) { el.width := $1 } }\n", ""))); + check("an effect's input written by path (R12): WRITE_TO_NON_SOURCE, not a loop across instants", r.agree && r.crate.diagnostics.some(d => d.code === "WRITE_TO_NON_SOURCE") && !r.crate.diagnostics.some(d => d.code === "EFFECT_WRITES_OWN_SOURCE"), show(r)); } + // the printed helper, pasted as printed: its module, its `.d.ts`, its import, its call — accepted, and it sets the property + const { appliers } = await import(pathToFileURL(path.join(path.dirname(fileURLToPath(import.meta.url)), "paste-apply.mjs")).href); + const { APPLY } = appliers({ repo: path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../.."), ws }); + const f = file(el("HTMLCanvasElement", "", "if (el) { el.width := 300 }")), r = both(f), m = r.crate.diagnostics.find(d => d.code === "WRITE_TO_NON_SOURCE"); + let pasted = false; try { if (m) { APPLY.setter({ code: m.code, msg: m.message, file: path.basename(f), line: m.line }, dir); pasted = true; } } catch (e) { check("…its helper is printed whole, to paste", false, e.message); } + if (pasted) { + const r2 = both(f); + check("…the helper pasted as printed is accepted by both checkers", r2.agree && !r2.crate.diagnostics.length && !r2.ref.diagnostics.length, show(r2)); + if (!r2.crate.diagnostics.length) for (const production of [false, true]) { + const h = new Runner(dir, path.basename(f), undefined, { production }); const page = await h.open(await h.serve()); + await page.click(".w"); await new Promise(res => setTimeout(res, 150)); + const w = await page.evaluate(() => document.querySelector("canvas")?.width); + check(`…and it sets the canvas's width, in Solid's ${production ? "production" : "development"} build`, w === 300 && !h.problems.length, { w, problems: h.problems }); + await h.close(); + } + } +} + +// ---------------------------------------------------------------- K-1: what a factory answers, in a source made by its call +// `source h := makeHandle()`, the fn's row typing its answer by a name (an interface: tippy's Instance, noUiSlider's API), +// a class's instance at run time: the runtime holds it whole, as a signal (ST-1), and `h.n := 7` threw "a path write to an +// atomic source" on the click, and at mount (REACTIVITY_HALTED) in an effect (re-check 11's K-1, r11/c1 S02p, S02bp). No +// checker can tell that type from a record's (a record alias of a `.d.ts`, `Wizard`, is the same opaque name to both: +// compiler/test/pasted/b09), so the runtime sets the property on the object the source holds, and the source changes: +// what reads it reads it again. A plain record so made is a store, as before. +{ + const k = (init, body, pre = "") => `export default component App() {\n source h := ${init}\n source n := 3\n source said := ""\n${pre}
    {said} {h.n}
    \n}\n`; + const runs = async (h, want, what) => { if (h) for (const production of [false, true]) { + const r = new Runner(dir, path.basename(h.entry), undefined, { production }); const page = await r.open(await r.serve()); + const seen = [(await r.text(page, ".k")).trim()]; + await page.click(".w"); await new Promise(res => setTimeout(res, 150)); seen.push((await r.text(page, ".k")).trim()); + check(`…${what}, in Solid's ${production ? "production" : "development"} build`, JSON.stringify(seen) === JSON.stringify(want) && !r.problems.length, { seen, problems: r.problems }); + await r.close(); + } }; + await runs(accepted("a field of a factory's class instance, typed by an interface, in a handler (r11 S02p)", k("makeHandle()", "h.n := 7; said := h.describe()")), ["w 1", "wa7 7"], "the field is set, and what reads the source follows"); + await runs(accepted("…in an effect (S02bp)", k("makeHandle()", "n := 9; said := h.describe()", " effect (n) { h.n := $0 }\n")), ["w 3", "wa3 9"], "it mounts, and the effect sets the field each time"); + await runs(accepted("…with the type written on the source (S02t)", `import { Handle } from "./lib.js"\n${k("makeHandle()", "h.n := 7; said := h.describe()").replace("source h :=", "source h: Handle :=")}`), ["w 1", "wa7 7"], "the field is set"); + await runs(accepted("a plain record a factory answers, typed by an interface (a store, as before)", k("makeOptions()", "h.speed := 5").replace("{h.n}", "{h.speed}")), ["w 1", "w 5"], "the record is written along its path"); +} + +// ---------------------------------------------------------------- R10-2: what is made where the component is made, lent +// `k = new Keeper(peek(items))` under `instantiates` handed the library the store itself: what it pushed into it later was +// dropped in production (said 2, 2). Lent as a call in a handler is: said 3, 4 (compiler/test/lending.mjs: every way) +{ const h = accepted("a library that keeps what it is made with and pushes into it later, made where the component is made (r10 R01a)", `export default component App() {\n source items: string[] := ["a", "b"]\n source said := 0\n k = new Keeper(peek(items))\n
    {items.join(",")} {said}
    \n}\n`); + if (h) for (const production of [false, true]) { + const r = new Runner(dir, path.basename(h.entry), undefined, { production }); const page = await r.open(await r.serve()); const seen = []; + for (let i = 0; i < 2; i++) { await page.click(".add"); await new Promise(res => setTimeout(res, 120)); seen.push(await r.text(page, ".b")); } + check(`…in Solid's ${production ? "production" : "development"} build what it kept grows (3, 4) and the source does not`, JSON.stringify(seen) === JSON.stringify(["adda,b 3", "adda,b 4"]) && !r.problems.length, { seen, problems: r.problems }); + await r.close(); + } } + +// ---------------------------------------------------------------- RFC 14, RFC 34: what is read once +const clock = body => `export default component App() {\n source n := 0\n clock = makeClock()\n${body}\n \n}\n`; +refused("a closure kept in a record, read under a kept peek", "SNAPSHOT_KEPT", clock(" box = { read: () => n }\n result = peek box.read()\n

    {result}

    ")); +refused("…given to a value parameter", "SNAPSHOT_ARGUMENT", clock(" box = { read: () => n }\n result = createLabel(box.read())\n

    {result}

    ")); +refused("…kept in an array", "SNAPSHOT_ARGUMENT", clock(" fs = [() => n]\n result = createLabel(fs[0]())\n

    {result}

    ")); +refused("…read out of an array written where it is called (a record's formatter)", "SNAPSHOT_ARGUMENT", clock(" box = { read: () => n }\n result = createLabel([box.read][0]())\n

    {result}

    ")); +refused("…through a closure that returns it", "SNAPSHOT_ARGUMENT", clock(" mk = () => () => n\n result = createLabel(mk()())\n

    {result}

    ")); +refused("…a record reached through another name", "SNAPSHOT_KEPT", clock(" box = { read: () => n }\n again = box\n result = peek again.read()\n

    {result}

    ")); +refused("a method of the instance its declaration does not name, in a record's closure", "SNAPSHOT_ARGUMENT", clock(" box = { read: () => clock.now() }\n result = createLabel(box.read())\n

    {result}

    ")); +{ const h = accepted("the same closure read live; a method's answer read once (`peek`); a literal's own slot; another field of the record", clock(' box = { read: () => n, unit: () => "clicks" }\n made = createLabel(peek clock.format())\n slot = createLabel([clock, 5][1])\n unit = createLabel(box.unit())\n

    {box.read()} {made} {slot} {unit}

    ')); + if (h) { + const base = await h.serve(); const page = await h.open(base); + check("…mounted", await h.until(async () => /0 \[noon\] \[5\] \[clicks\]/.test(await h.text(page))), await h.text(page)); + await page.click(".b"); await page.click(".b"); + check("…the live read follows the source (a kept peek of it would have shown 0 for ever); what was made once is as it was", await h.until(async () => /2 \[noon\] \[5\] \[clicks\]/.test(await h.text(page))), await h.text(page)); + await h.close(); + } } + +// ---------------------------------------------------------------- MO-10a: a primitive's own owner (2026-11-23) +// A declared JS primitive is called in an owner of its own, under the region it is written in. What that owner is to +// the region, through a compiled program: a cleanup the primitive registers runs when its region goes (a branch that +// closes), not before; and a failure while it is made is the caller's, shown by the `errored` region the caller is under. +{ const h = accepted("a primitive that registers a cleanup, in a branch; one that fails while it is made, under an errored region", `component Watch() { + w = createWatcher("a") + {w} +} +component Boom() { + v = createFailing() + {v} +} +export default component App() { + source open := true + {if open { }} + {errored fallback(e) {

    caught: {e.message}

    } { }} + +} +`); + if (h) { + const base = await h.serve(); const page = await h.open(base); + check("…mounted: the primitive's value is shown, and its cleanup has not run", await h.until(async () => (await h.text(page, ".w")) === "a") && !/gone/.test(await page.title()), `${await h.text(page)} / ${await page.title()}`); + check("…the failure while a primitive is made is shown by the errored region above its caller", /caught: made badly/.test(await h.text(page, ".err")), await h.text(page)); + await page.click(".b"); + check("…the branch closed: the primitive's cleanup ran with its region, once", await h.until(async () => /^[^|]*\|gone:a$/.test(await page.title())) && (await page.locator(".w").count()) === 0, await page.title()); + await h.close(); + } } + +rmSync(dir, { recursive: true, force: true }); +console.log(`\n${pass} passed, ${fail} failed`); +process.exit(fail ? 1 : 0); diff --git a/compiler/test/corpus.json b/compiler/test/corpus.json new file mode 100644 index 000000000..a508746ce --- /dev/null +++ b/compiler/test/corpus.json @@ -0,0 +1,17 @@ +{ + "trials": 7821, + "met": 6546, + "suggestions": 7258, + "accepted": 6541, + "atOnce": 119, + "failed": 5, + "ran": "64/64", + "failures": { + "bench/tasks/query-mutation/src/api.d.rx#fetchTodo/io:extend-pure": "no-spelling", + "bench/tasks/query-mutation/src/api.d.rx#fetchTodo/io:fn-extend-pure": "no-spelling", + "bench/tasks/query-mutation/src/api.d.rx#fetchTodo/io:fn-import": "no-spelling", + "bench/tasks/query-mutation/src/api.d.rx#fetchTodo/io:import": "no-spelling", + "bench/tasks/query-mutation/src/api.d.rx#fetchTodo/io:instantiates": "no-spelling" + }, + "why": "compiler/test/corpus.mjs: each failure listed is a trial whose printed suggestion does not work, with the reason recorded in spec/archive or OPEN" +} diff --git a/compiler/test/corpus.mjs b/compiler/test/corpus.mjs new file mode 100644 index 000000000..0f72591d0 --- /dev/null +++ b/compiler/test/corpus.mjs @@ -0,0 +1,407 @@ +// 99 (2026-12-04, re-check 9's C2): "a printed fix works", checked against the declarations programs really import — not +// against cases written for it. Every re-check's fresh sample of apps found a library shape where a printed spelling did not +// parse, was not accepted, or was accepted and broke at mount (re-check 9: an `instantiates` class row that dropped `new`, +// `extend class C(...args: handler)` and `(source: { 0: handler })` refused as PARSE): fixing the shapes one at a time did +// not converge, so the shapes are taken from the corpus itself. +// +// The corpus: every row of a function or a class in every declaration the benchmark has — the drafts rx-tsc wrote for its +// install (bench/.out/ws/node_modules/.rx-types), a library's shared declaration it installs (node_modules/@rx-types, 09 MO-8k: none since 2026-12-02) +// and the hand-written `.d.rx` of its tasks, coverage and probes. For each row +// the call shapes that meet each declaration-related refusal are synthesized: +// - io: `x = f(…)` (`x = new C(…)`) bound where the component is made and read: IO_IN_REACTIVE, pasted three ways where +// the message prints them (`import pure`, `extend pure`, `… instantiates`); +// - owned, effect, action: a closure that writes given at each place the row types a callback — a parameter, a field of +// an options record, an index signature, an item of a list, the rest — where the component is made +// (REACTIVE_WRITE_IN_OWNED_SCOPE), in an effect whose input it writes (EFFECT_WRITES_OWN_SOURCE), and an expression +// closure that calls an action (ACTION_CALLED_IN_OWNED_SCOPE). +// (re-check 10's B, 2026-12-05: every declaration-related refusal, not four — the shapes the tenth re-check's fresh +// apps met outside the corpus, each over every row it applies to) +// - method: the rows of an object's methods (`export fn default.createInstance(…)`, `toast.success`), met through the +// object the program imports — every shape above; +// - io:fn: the call in a `fn`'s body (IO_IN_FN), pasted the two ways a fn can take (`import pure`, `extend pure`); +// - inst: a row that instantiates, called in the view (INSTANTIATION_NOT_BOUND: `x = f(…)`, bound); +// - snap: a reactive value given to such a row's value parameter (SNAPSHOT_ARGUMENT: `peek(…)`); +// - path: a field of a class instance a source holds, written by path (WRITE_TO_NON_SOURCE: the JavaScript helper it +// prints, its module, its `.d.ts`, its import and its call); +// - prop: a callback prop of a library's component given a closure that writes (taken as it is: a component calls its +// callback props on its events) — no refusal, and in the Chromium sample the stand-in component calls it; +// - untyped: a package that ships no types (one per package of the corpus, its code standing in), imported and called +// where the component is made: the `npx rx-declare` the message prints, then the rows it says to write by hand. +// Each message's spelling is pasted as printed, by compiler/test/paste-apply.mjs's appliers (the text in its backticks, in +// the file it names — never one written here), until both checkers accept the program. A suggestion fails where its +// applier finds nothing to paste, where the pasted text does not parse or names a row that is not there, where the same +// refusal stands after it, or where the program is not accepted when nothing is left to paste. Every accepted program is +// compiled by the crate, and a class's construction must be `new` (or the runtime's `lentNew`); a deterministic sample is +// also run in Chromium, development and production builds, over a stand-in package that keeps each callback it is given and +// calls it on an event: the page must mount, and the callbacks must have run. +// +// compiler/test/corpus.json records the counts and each failing trial with why; `--check` (scripts/ci) fails on a failure +// that is not recorded, and on a recorded one that passes now (a ratchet); `--record` writes it. CORPUS_TOOLS=
    +// asks that checkout's checkers instead of this one's (a before/after count; the corpus and the appliers are this one's). +// node --experimental-strip-types compiler/test/corpus.mjs [--check | --record] [--jobs N] [--only ] [--no-run] +import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync, cpSync } from "node:fs"; +import { spawn, spawnSync } from "node:child_process"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { createRequire } from "node:module"; +import os from "node:os"; +import path from "node:path"; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const repo = path.resolve(here, "../.."); +const ws = path.join(repo, "bench/.out/ws"); +const TOOLS = process.env.CORPUS_TOOLS ? path.resolve(process.env.CORPUS_TOOLS) : repo; +const RXC = path.join(TOOLS, "compiler/target/release/rxc"); +const RECORD = path.join(here, "corpus.json"); +const args = process.argv.slice(2); +const flag = n => args.includes(n), opt = (n, d) => { const i = args.indexOf(n); return i >= 0 ? args[i + 1] : d; }; + +// the codes whose messages a declaration's words decide, and which a trial pastes +const FAMILY = new Set(["IO_IN_REACTIVE", "IO_IN_FN", "EFFECT_WRITES_OWN_SOURCE", "REACTIVE_WRITE_IN_OWNED_SCOPE", "ACTION_CALLED_IN_OWNED_SCOPE", "IMPORT_ROW_MISMATCH", "UNBOUND", "WRITE_TO_NON_SOURCE", "INSTANTIATION_NOT_BOUND", "SNAPSHOT_ARGUMENT"]); + +// ---------------------------------------------------------------- the corpus +const walk = (d, skip = () => false) => !existsSync(d) ? [] : readdirSync(d, { withFileTypes: true }).flatMap(e => skip(e.name) ? [] : e.isDirectory() ? walk(path.join(d, e.name), skip) : e.name.endsWith(".d.rx") ? [path.join(d, e.name)] : []); +/** Each declaration file of the corpus: where it is read from, the specifier a program imports it by, and the files a + * program's folder holds for it (a hand-written row is the project's: `rx-types/.d.rx`, or `./x.d.rx` beside `./x.js`). */ +function files() { + const out = []; + const drafts = path.join(ws, "node_modules/.rx-types"); + // (the packages the benchmark installs: a draft another run left in the install is no part of the corpus) + const pkg = JSON.parse(readFileSync(path.join(repo, "bench/package.json"), "utf8")), deps = new Set(Object.keys({ ...pkg.dependencies, ...pkg.devDependencies })); + const top = spec => spec.split("/").slice(0, spec[0] === "@" ? 2 : 1).join("/"); + for (const f of walk(drafts).filter(f => deps.has(top(path.relative(drafts, f).replace(/\.d\.rx$/, ""))))) out.push({ file: f, spec: path.relative(drafts, f).replace(/\.d\.rx$/, ""), origin: "draft", copy: [] }); + // 09 MO-8k: a shared declaration of a library in the install (none since round D2, 2026-12-02: the repository ships + // Solid's own alone), read in place of its package's draft — the rows a draft of theirs had are theirs + const shared = path.join(ws, "node_modules/@rx-types"); + for (const d of existsSync(shared) ? readdirSync(shared).filter(d => d !== "solid-js") : []) for (const f of walk(path.join(shared, d))) { + const name = d.includes("__") ? `@${d.replace("__", "/")}` : d, sub = path.relative(path.join(shared, d), f).replace(/\.d\.rx$/, ""); + if (deps.has(name)) out.push({ file: f, spec: sub === "index" ? name : `${name}/${sub}`, origin: "shared", copy: [] }); + } + for (const base of ["bench/tasks", "bench/coverage", "bench/probes"]) for (const f of walk(path.join(repo, base), n => n === "node_modules" || n.startsWith(".") || n === "dist")) { + const rel = path.relative(path.join(repo, base), f), i = f.lastIndexOf(`${path.sep}rx-types${path.sep}`); + if (i >= 0) { const spec = f.slice(i + "/rx-types/".length).replace(/\.d\.rx$/, ""); out.push({ file: f, spec, origin: `${base}/${rel}`, copy: [[f, `rx-types/${spec}.d.rx`]] }); continue; } + const js = f.replace(/\.d\.rx$/, ".js"), ts = f.replace(/\.d\.rx$/, ".ts"), name = path.basename(f).replace(/\.d\.rx$/, ""); + if (!existsSync(js) && !existsSync(ts)) continue; // (a host's declaration, a route tree's: no module of its own to import) + out.push({ file: f, spec: `./${name}.js`, origin: `${base}/${rel}`, copy: [[f, `${name}.d.rx`], ...(existsSync(js) ? [[js, `${name}.js`]] : [])] }); + } + return out; +} +const require_ = createRequire(import.meta.url); +/** A row's parts as the crate's own parser reads them (tooling/rx-language-server/src/rows.js, `rxc rows`). */ +function rows(f) { try { return require_(path.join(repo, "tooling/rx-language-server/src/rows.js")).rowsOf(f.file); } catch { return []; } } + +// ---------------------------------------------------------------- the trials +const isFnType = t => /^\(?\s*(\(|<)/.test(t ?? "") && /=>/.test(t ?? "") && !/^\{/.test(t ?? ""); +const listOfFns = t => !!t && (/^(\(.*=>.*\)|[A-Za-z_$][\w$.]*)\[\]$/.test(t.trim()) && /=>/.test(t)) || /^(Array|ReadonlyArray)<\s*\(/.test(t ?? "") || /\bMany<.*Accessor … }` in a record type: the index signature's place (its key) where its values are functions. */ +const indexFn = t => /\[\s*[\w$]+\s*:\s*string\s*\]\s*\??:\s*(handler\s+)?\(/.test(t ?? ""); +/** A value for a parameter no trial is about: what the checkers read as nothing in particular. */ +const placeholder = p => isFnType(p.type) ? "() => 0" : /^\{/.test((p.type ?? "").trim()) ? "{}" : /\[\]$/.test((p.type ?? "").trim()) ? "[]" : "0"; +/** Each place of a row a callback goes: the parameter's index and what is written there around the closure. */ +function sites(r) { + const out = [], ps = r.facts.params; + const handled = new Set(r.facts.callbacks.filter(c => c.handler).map(c => `${c.index}:${c.field ?? ""}`)); + for (const c of r.facts.callbacks) if (!c.handler && /^[A-Za-z_$][\w$]*$/.test(c.field ?? "x")) out.push({ i: c.index, at: c.field === null ? "param" : "field", field: c.field, key: `${c.index}:${c.field ?? ""}` }); + ps.forEach((p, i) => { + if (handled.has(`${i}:`)) return; + if (p.rest && !out.some(o => o.i === i)) out.push({ i, at: "rest", key: `${i}:...` }); + else if (listOfFns(p.type)) out.push({ i, at: "list", key: `${i}:[]` }); + else if (indexFn(p.type) && !out.some(o => o.i === i && o.at === "field")) out.push({ i, at: "index", key: `${i}:[k]` }); + }); + return out; +} +/** What is written at a site around the closure. */ +const wrap = (s, x) => s.at === "field" ? `{ ${s.field}: ${x} }` : s.at === "list" ? `[${x}]` : s.at === "index" ? `{ anyKey: ${x} }` : x; +const CLOSURE = { owned: "() => { n := n + 1 }", effect: "() => { open := false }", action: "() => bump()" }; +/** The call of the row's export, `target` at site `s` (the other parameters given what nothing is about). */ +function callOf(r, callee, s, target) { + const ps = r.facts.params, xs = []; + const upto = s ? s.i : ps.findLastIndex(p => !p.optional && !p.rest); + for (let i = 0; i <= upto && i < ps.length; i++) { + if (s && i === s.i) { xs.push(wrap(s, target)); break; } + if (ps[i].rest) break; + xs.push(placeholder(ps[i])); + } + return `${r.facts.ctor ? "new " : ""}${callee}(${xs.join(", ")})`; +} +/** The import a row is met through, and the callee it is called by: a method's (`default.createInstance`) through its object. */ +function head(r, f) { + const [obj, ...rest] = r.name.split("."), alias = obj === "default" ? "Made" : obj, callee = [alias, ...rest].join("."); + return { imp: obj === "default" ? `import Made from ${JSON.stringify(f.spec)}` : `import { ${obj} } from ${JSON.stringify(f.spec)}`, callee, alias }; +} +/** The call with `arg` at value parameter `i` (the others as nothing in particular). */ +function callWith(r, callee, i, arg) { + const ps = r.facts.params, xs = []; + for (let k = 0; k <= i && k < ps.length; k++) xs.push(k === i ? arg : placeholder(ps[k])); + return `${r.facts.ctor ? "new " : ""}${callee}(${xs.join(", ")})`; +} +function program(r, f, shape, s) { + const { imp, callee, alias } = head(r, f); + if (shape === "io:fn-import" || shape === "io:fn-extend-pure") return `${imp}\nfn make(): any => ${callOf(r, callee, undefined)}\nexport default component App() {\n source n := 0\n

    {make() ? "made" : "none"} {n}

    \n}\n`; + if (shape === "inst") return `${imp}\nexport default component App() {\n source n := 0\n

    {${callOf(r, callee, undefined)} ? "made" : "none"} {n}

    \n}\n`; + if (shape === "snap") return `${imp}\nexport default component App() {\n source n := 0\n x = ${callWith(r, callee, s.i, "n")}\n

    {x ? "made" : "none"} {n}

    \n}\n`; + // (a constructor that instantiates is made where the component is made, and the source is given it, `peek`: made in an + // effect's apply it is INSTANTIATION_NOT_BOUND first — round C2, `QueryClient`) + if (shape === "path" && r.facts.instantiates) return `${imp}\nexport default component App() {\n c = ${callOf(r, callee, undefined)}\n source x: ${alias} | null := peek(c)\n source n := 0\n

    { if (x) { x.made := n } }}>{x ? "made" : "none"} {n}

    \n}\n`; + if (shape === "path") return `${imp}\nexport default component App() {\n source x: ${alias} | null := null\n source n := 0\n effect () { x := ${callOf(r, callee, undefined)} }\n

    { if (x) { x.made := n } }}>{x ? "made" : "none"} {n}

    \n}\n`; + if (shape === "prop") return `${imp}\nexport default component App() {\n source n := 0\n <${callee} ${s.prop}={() => { n := n + 1 }} />\n

    {n}

    \n}\n`; + if (shape === "untyped") return `import { ${s.name} } from "${s.pkg}"\nexport default component App() {\n source n := 0\n x = ${s.name}(0)\n

    {x ? "made" : "none"} {n}

    \n}\n`; + const body = shape === "effect" + ? ` source open := true\n effect (open) {\n if ($0) {\n let off = ${callOf(r, callee, s, CLOSURE.effect)}\n }\n }\n

    {open ? "open" : "shut"}

    ` + : shape.startsWith("io:") + ? ` source n := 0\n x = ${callOf(r, callee, undefined)}\n

    {x ? "made" : "none"} {n}

    ` + : ` source n := 0\n action bump() { n := n + 1 }\n x = ${callOf(r, callee, s, CLOSURE[shape])}\n

    {n}

    `; + return `${imp}\nexport default component App() {\n${body}\n}\n`; +} +const TRIAL_SHAPES = { io: ["io:import", "io:extend-pure", "io:instantiates"], cb: ["owned", "effect", "action"], fn: ["io:fn-import", "io:fn-extend-pure"] }; +/** The line of the program a shape's refusal is on. */ +const lineOf = shape => shape === "effect" ? 6 : shape.startsWith("io:fn") ? 2 : shape === "path" ? 6 : shape.startsWith("io:") || shape === "inst" || shape === "snap" || shape === "untyped" || shape === "prop" ? 4 : 5; +const CODE = { owned: "REACTIVE_WRITE_IN_OWNED_SCOPE", effect: "EFFECT_WRITES_OWN_SOURCE", action: "ACTION_CALLED_IN_OWNED_SCOPE", inst: "INSTANTIATION_NOT_BOUND", snap: "SNAPSHOT_ARGUMENT", path: "WRITE_TO_NON_SOURCE", prop: null, untyped: "IO_IN_REACTIVE" }; +/** A value parameter a reactive value may be given (no callback, no `ref`, no `draft`, not the rest). */ +const valueParam = r => r.facts.params.findIndex(p => !p.ref && !p.draft && !p.rest && !isFnType(p.type) && !listOfFns(p.type) && !/=>/.test(p.type ?? "")); +function trials() { + const out = [], seen = new Set(), untypedSeen = new Set(); + for (const f of files()) for (const r of rows(f)) { + // a component's callback props (MO-10g: a component calls them on its events, so a closure that writes is one) + if (r.kind === "component" && /^[A-Za-z_$][\w$]*$/.test(r.name)) { + const key = `${f.spec}\u0000${r.text}`; if (seen.has(key)) continue; seen.add(key); + for (const p of (r.facts.props ?? []).filter(p => p.function && !p.handler && !p.render && !p.component && !p.components && !p.view && /^[A-Za-z_$][\w$]*$/.test(p.name)).slice(0, 2)) + out.push({ id: `${f.origin === "draft" ? f.spec : f.origin}#${r.name}/prop@${p.name}`, f, r, shape: "prop", s: { prop: p.name, at: "prop" }, code: null }); + continue; + } + if (r.kind !== "fn" || !/^[A-Za-z_$][\w$]*(\.[A-Za-z_$][\w$]*)?$/.test(r.name)) continue; + const key = `${f.spec}\u0000${r.text}`; if (seen.has(key)) continue; seen.add(key); + const id0 = `${f.origin === "draft" ? f.spec : f.origin}#${r.name}`; + const method = r.name.includes("."); + // a fn's body: what a call there may do is io (R-io-2) — the two words a fn can take (a fn makes nothing to bind) + if (!r.facts.pure && !r.facts.instantiates && !r.facts.params.some(p => p.draft) && !r.facts.params.some(p => p.ref)) for (const sh of TRIAL_SHAPES.fn) out.push({ id: `${id0}/${sh}`, f, r, shape: sh, code: "IO_IN_FN" }); + // a row that makes what lives with the component, called in the view; a reactive value given to its value parameter + // (a factory that answers a component is applied, not read: MO-11f — no value to bind and show) + // (…and one that reads a context is called under its provider: CONTEXT_NOT_FOUND's ground, which no shape here makes) + if (r.facts.instantiates && !method && !r.facts.uses.length && !/\)\s*:\s*(?:import\([^)]*\)\.)?(?:Component|ValidComponent)\b/.test(r.text)) { out.push({ id: `${id0}/inst`, f, r, shape: "inst", code: "INSTANTIATION_NOT_BOUND" }); const i = valueParam(r); if (i >= 0) out.push({ id: `${id0}/snap@${i}`, f, r, shape: "snap", s: { i, at: "param" }, code: "SNAPSHOT_ARGUMENT" }); } + // a field of a class's instance, written by path from a source that holds it + if (r.facts.ctor && !method) out.push({ id: `${id0}/path`, f, r, shape: "path", code: "WRITE_TO_NON_SOURCE" }); + // a package that ships no types: one a package of the corpus, its first fn's name standing in for it + if (f.origin === "draft" && !method && !r.facts.ctor && r.name !== "default" && !untypedSeen.has(f.spec) && untypedSeen.size < Number(opt("--untyped", 24))) { untypedSeen.add(f.spec); const pkg = `untyped-${f.spec.replace(/[^\w]+/g, "-").replace(/^-|-$/g, "")}`; out.push({ id: `${id0}/untyped`, f, r, shape: "untyped", s: { name: r.name, pkg, at: "call" }, code: "IO_IN_REACTIVE", files: [[`node_modules/${pkg}/package.json`, JSON.stringify({ name: pkg, version: "1.0.0", type: "module", exports: { ".": "./index.js" } })], [`node_modules/${pkg}/index.js`, `export function ${r.name}(...a) { return { made: true } }\n`]] }); } + // (a fn that changes what it is given, `draft`, is no value to compute: called in a view it is a mistake, refused with no + // spelling to paste — MO-10i) + if (!r.facts.pure && !r.facts.params.some(p => p.draft)) for (const sh of TRIAL_SHAPES.io) out.push({ id: `${id0}/${sh}`, f, r, shape: sh, code: "IO_IN_REACTIVE" }); + // (an effect's apply calls what makes nothing: a row that instantiates is bound where the component is made, RG-6) + for (const s of sites(r)) for (const sh of TRIAL_SHAPES.cb.filter(sh => sh !== "effect" || !r.facts.instantiates)) out.push({ id: `${id0}/${sh}@${s.key}`, f, r, shape: sh, s, code: { owned: "REACTIVE_WRITE_IN_OWNED_SCOPE", effect: "EFFECT_WRITES_OWN_SOURCE", action: "ACTION_CALLED_IN_OWNED_SCOPE" }[sh] }); + } + return out; +} + +// ---------------------------------------------------------------- one trial +const ticks = msg => [...msg.matchAll(/`([^`]+)`/g)].map(m => m[1]); +/** Which applier pastes a message, for the way a trial takes (io: `pure` at the import, `pure` over the draft, `instantiates`). */ +function chooseApplier(m, shape) { + const t = ticks(m.msg), has = re => t.some(x => re.test(x)); + if (m.code === "IO_IN_REACTIVE" || m.code === "IO_IN_FN") { + if (shape === "untyped" && has(/^npx rx-declare /)) return { how: "command" }; // (the package's own way through: its rows drafted, or written by hand) + const want = shape === "io:import" || shape === "io:fn-import" || shape === "untyped" ? "import" : shape === "io:extend-pure" || shape === "io:fn-extend-pure" ? "pure" : "instantiates"; + const order = want === "import" ? ["import", "pure", "instantiates"] : want === "pure" ? ["pure", "import", "instantiates"] : ["instantiates", "pure", "import"]; + for (const w of order) { + if (w === "import" && has(/^import pure /)) return { how: "import" }; + if (w === "pure" && has(/^extend pure (fn|class) [\w$.]+$/) && !/\bits `extend` row\b|said over by its `extend` row/.test(m.msg)) return { how: "extend" }; + if (w === "pure" && has(/^extend pure (fn|class) [\w$.]+$/)) return { how: "extend-word", drop: /`extend [^`]*instantiates`/g }; + if (w === "pure" && has(/^export (?:(?:server|client) )?pure (fn|class) [\w$.]+$/)) return { how: "row" }; + if (w === "instantiates" && has(/^extend .*\(…\) instantiates$/)) return { how: "extend-word" }; + if (w === "instantiates" && has(/^extend .*\binstantiates$/)) return { how: "extend-instantiates" }; + if (w === "instantiates" && has(/^export (?:(?:server|client) )?(fn|class) [\w$.]+\(…\) … instantiates$/)) return { how: "row-instantiates" }; + } + if (has(/^npx rx-declare /)) return { how: "command" }; + return null; + } + if (m.code === "IMPORT_ROW_MISMATCH") return has(/^export (?:(?:server|client) )?pure (fn|class) /) ? { how: "row" } : null; + if (m.code === "UNBOUND") return has(/^export const [\w$]+ = /) ? { how: "factory" } : null; + if (m.code === "WRITE_TO_NON_SOURCE") return has(/^export const set[\w$]* = \(/) ? { how: "setter" } : has(/^[\w$]+ := \{ \.\.\./) ? { how: "whole" } : null; + if (m.code === "INSTANTIATION_NOT_BOUND") return has(/^[\w$]+ = (new )?[\w$.]+\(…\)$/) ? { how: "bind" } : null; + if (m.code === "SNAPSHOT_ARGUMENT") return /pass peek\(…\)/.test(m.msg) ? { how: "peek" } : null; + // the handler family + if (/replace its `extend` row in rx-types\/[^\s`]+?\.d\.rx with `/.test(m.msg)) return { how: "extend-replace" }; // (re-check 15: the row merged) + if (has(/^export const restoring = /)) return { how: "helper" }; + if (/after `extend (fn|class) /.test(m.msg) && has(/^\(.*\)$/)) return { how: "extend-params" }; + if (has(/(?:^|, )callback: handler /) && /before `[^`]+` in /.test(m.msg)) return { how: "before" }; + if (has(/^extend (?!.*\binstantiates$)/)) return { how: "extend" }; + if (has(/^(?:\[[^\]]*\]|[\w$]+\??): handler /)) return { how: "member" }; + if (has(/^npx rx-declare /)) return { how: "command" }; + return null; +} +async function worker(list, wid, ref) { + const { appliers } = await import(pathToFileURL(path.join(here, "paste-apply.mjs")).href); + const { APPLY } = appliers({ repo, ws }); + const root = path.join(ws, "corpus", `w${wid}`); rmSync(root, { recursive: true, force: true }); mkdirSync(root, { recursive: true }); + const check = d => { + const entry = path.join(d, "main.rx"); + const c = spawnSync(RXC, ["check", "--json", entry], { encoding: "utf8", maxBuffer: 1 << 26 }); + let crate; try { crate = JSON.parse(c.stdout).diagnostics ?? []; } catch { crate = [{ code: "CRASH", line: 0, message: (c.stderr || c.stdout || "").slice(0, 300) }]; } + let r; try { r = JSON.parse(JSON.stringify(ref(entry, false, false))); } catch (e) { r = { error: String(e.message ?? e) }; } + const refd = r.error ? [{ code: r.code ?? "PARSE", line: 0, message: r.error }] : r.diagnostics; + const ds = crate.map(x => ({ code: x.code, line: x.line, file: path.relative(d, x.file ?? entry) || "main.rx", msg: x.message ?? "" })); + return { ds, ref: refd.map(x => x.code), agree: JSON.stringify(crate.map(x => x.code)) === JSON.stringify(refd.map(x => x.code)) }; + }; + const results = []; + for (let t of list) { + const d = path.join(root, t.id.replace(/[^\w.-]+/g, "_").slice(-120)); + rmSync(d, { recursive: true, force: true }); mkdirSync(d, { recursive: true }); + for (const [from, to] of t.f.copy) { mkdirSync(path.dirname(path.join(d, to)), { recursive: true }); cpSync(from, path.join(d, to)); } + for (const [rel, text] of t.files ?? []) { mkdirSync(path.dirname(path.join(d, rel)), { recursive: true }); writeFileSync(path.join(d, rel), text); } + if (t.shape === "untyped") for (const [from, to] of t.f.copy) rmSync(path.join(d, to), { force: true }); // (no declaration of its own: the package has none) + writeFileSync(path.join(d, "main.rx"), program(t.r, t.f, t.shape, t.s)); + const at = lineOf(t.shape); + const res = { id: t.id, code: t.code, shape: t.shape, at: t.s?.at ?? "call", ctor: !!t.r.facts.ctor, origin: t.f.origin, steps: [] }; + const first = check(d); + // (a shape that takes what it is given — a component's callback prop — is accepted at once, by both checkers alike) + // …and one the row says is called while the library computes (a callback prop that answers a value, `isValidConnection`) + // is refused, and its printed way through pasted as any other + if (t.code === null && !first.ds.length && first.agree) { res.result = "accepted-at-once"; if (process.env.CORPUS_KEEP) res.dir = d; else rmSync(d, { recursive: true, force: true }); results.push(res); continue; } + if (t.code === null) { const h = first.ds.find(x => FAMILY.has(x.code) && x.file === "main.rx" && x.line === at); if (h) { t = { ...t, code: h.code }; res.code = h.code; } } + const hit = first.ds.filter(x => FAMILY.has(x.code) && x.file === "main.rx" && x.line === at); + if (!hit.some(x => x.code === t.code)) { res.result = "not-met"; res.why = first.ds.map(x => x.code).join(",") || "accepted"; results.push(res); rmSync(d, { recursive: true, force: true }); continue; } + const others0 = new Set(first.ds.filter(x => !FAMILY.has(x.code)).map(x => x.code)); + let state = first, fail = null; + for (let round = 0; round < 8 && !fail; round++) { + const ms = state.ds.filter(x => FAMILY.has(x.code)); + if (!ms.length) break; + const m = ms[0], ch = chooseApplier(m, t.shape); + const step = { code: m.code, how: ch?.how ?? null }; + res.steps.push(step); + if (!ch) { fail = { why: "no-spelling", code: m.code, msg: m.msg.slice(0, 600) }; break; } + try { const st = res.st ??= {}; APPLY[ch.how](ch.drop ? { ...m, msg: m.msg.replace(ch.drop, "") } : m, d, st); if (ch.how === "command" && st.declared?.status !== 0) { res.steps.push({ code: m.code, how: "hand" }); APPLY.hand(m, d, st); } } + catch (e) { fail = { why: "no-spelling", code: m.code, how: ch.how, err: String(e.message).slice(0, 200), msg: m.msg.slice(0, 600) }; break; } + const next = check(d); + const parse = next.ds.find(x => x.code === "PARSE" || x.code === "CRASH" || x.file !== "main.rx"); + if (parse) { fail = { why: "pasted-text-refused", code: m.code, how: ch.how, said: `${parse.code}: ${parse.msg.slice(0, 400)}`, msg: m.msg.slice(0, 600) }; break; } + if (next.ds.some(x => x.code === m.code && x.line === m.line && x.msg === m.msg)) { fail = { why: "no-progress", code: m.code, how: ch.how, msg: m.msg.slice(0, 600) }; break; } + state = next; + } + if (!fail) { + const left = state.ds.filter(x => FAMILY.has(x.code) || !others0.has(x.code)); + if (left.length) fail = { why: "not-accepted", left: left.map(x => `${x.code}@${x.line}: ${x.msg.slice(0, 300)}`).slice(0, 3) }; + else if (!state.agree) fail = { why: "checkers-disagree", crate: state.ds.map(x => x.code), ref: state.ref }; + } + // compiled by the crate where nothing is left; a class is constructed (`new`, or the runtime's lentNew) + if (!fail && !state.ds.length) { + const c = spawnSync(RXC, ["app", path.join(d, "main.rx"), "--target", "dom"], { encoding: "utf8", maxBuffer: 1 << 27 }); + let code = ""; try { code = Object.values(JSON.parse(c.stdout).modules ?? {}).map(m => m.code).join("\n"); } catch { /* none */ } + if (!code) fail = { why: "does-not-compile", said: (c.stderr || c.stdout).slice(0, 400) }; + else if (t.r.facts.ctor) { const alias = t.r.name === "default" ? "Made" : t.r.name; if (!new RegExp(`(new v\\$${alias.replace(/\$/g, "\\$")}\\(|lentNew\\(v\\$${alias.replace(/\$/g, "\\$")},)`).test(code)) fail = { why: "class-not-constructed", said: code.split("\n").filter(l => l.includes(`v$${alias}`)).slice(0, 4).join(" | ") }; } + res.compiled = !fail; + } + delete res.st; + res.result = fail ? "fail" : "pass"; if (fail) res.fail = fail; + if (!fail && process.env.CORPUS_KEEP) res.dir = d; else rmSync(d, { recursive: true, force: true }); + results.push(res); + } + return results; +} + +// ---------------------------------------------------------------- the sample run in Chromium +/** A stand-in package for a row: the export made as its row says it is (a class is constructed, `new`; a fn is called), each + * function it is given kept — as an argument, a field of a record, an item of a list — and called when the page's event + * `corpus-fire` is dispatched; the program's view then shows whether they ran. */ +function standIn(r) { + const keep = `const kept = []\nconst take = (x, d = 0) => { if (typeof x === "function") kept.push(x); else if (Array.isArray(x)) x.forEach(y => take(y, d + 1)); else if (x && typeof x === "object" && d < 2) Object.values(x).forEach(y => take(y, d + 1)) }\nif (typeof window !== "undefined") window.addEventListener("corpus-fire", () => { for (const f of kept) f() })\n`; + // (a component: each function prop kept — read through the props object, as a component reads them) + if (r.kind === "component") return `${keep}function Made(props) { for (const k of Object.keys(props)) { const v = props[k]; if (typeof v === "function") kept.push(v); } return document.createTextNode("") }\nexport ${r.name === "default" ? "default Made" : `{ Made as ${r.name} }`}\n`; + const [obj, ...rest] = r.name.split("."); + // (a `ref` parameter is an accessor the library reads: what it reads is what is kept) + const ps = r.facts.params ?? [], refs = JSON.stringify(ps.map(p => !!p.ref)), read = `a.forEach((x, i) => take(${refs}[Math.min(i, ${Math.max(0, ps.length - 1)})] && typeof x === "function" ? x() : x))`; + // (what it answers as its row says: a reader, `ref T`, is a function the program calls to read it) + const answer = /\)\s*:\s*ref\b/.test(r.text) ? "() => ({ made: true })" : "{ made: true }"; + const made = r.facts.ctor ? `class Made { constructor(...a) { ${read}; this.made = true } }` : `function Made(...a) { ${read}; return ${answer} }`; + // (a method's row: the object the program imports, with that method) + const value = rest.length ? `const Obj = { ${rest[0]}: Made }` : `const Obj = Made`; + return `${keep}${made}\n${value}\nexport ${obj === "default" ? "default Obj" : `{ Obj as ${obj} }`}\n`; +} +async function sampleRun(passed, n) { + const { Runner } = await import(pathToFileURL(path.join(repo, "bench/harness.mjs")).href); + // a deterministic sample: every class, then the others in order of their ids, spread over the shapes + // (a component whose children are a view of what it renders is not shown with none: no stand-in run says anything of it) + const pick = [...passed.filter(x => x.ctor), ...passed.filter(x => !x.ctor)].filter((x, i, a) => a.findIndex(y => y.id === x.id) === i).filter(x => !(x.shape === "prop" && (x.trial.r.facts.props ?? []).some(p => p.name === "children" && (p.view || p.render)))); + // (spread over the rows: each shape's trials in the order of a hash of their ids, so one package does not fill the sample) + const h = s => { let v = 2166136261; for (const c of s) v = Math.imul(v ^ c.charCodeAt(0), 16777619) >>> 0; return v; }; + pick.sort((a, b) => (b.ctor - a.ctor) || h(a.id) - h(b.id)); + const byShape = new Map(); for (const x of pick) { const k = `${x.ctor}:${x.shape}:${x.at}`; if (!byShape.has(k)) byShape.set(k, []); byShape.get(k).push(x); } + const chosen = []; for (let k = 0; chosen.length < n && [...byShape.values()].some(v => v.length > k); k++) for (const v of byShape.values()) if (v[k] && chosen.length < n) chosen.push(v[k]); + const out = []; + for (const x of chosen) { + const t = x.trial, d = x.dir; if (!d) continue; + // the package's own import replaced by the stand-in, a folder of the program's own beside it; its row kept as it is + const pkg = path.join(d, "node_modules", ...t.f.spec.split("/")); + if (t.shape === "untyped") { /* the package is the trial's own */ } + else if (!t.f.spec.startsWith(".")) { + const real = path.join(ws, "node_modules", ...t.f.spec.split("/"), "package.json"); + let version = "1.0.0"; try { version = JSON.parse(readFileSync(real, "utf8")).version; } catch { /* none */ } + mkdirSync(pkg, { recursive: true }); writeFileSync(path.join(pkg, "package.json"), JSON.stringify({ name: t.f.spec, version, type: "module", exports: { ".": "./index.js" } })); + writeFileSync(path.join(pkg, "index.js"), standIn(t.r)); + } else writeFileSync(path.join(d, t.f.spec), standIn(t.r)); + const got = []; + for (const production of [false, true]) { + const h = new Runner(d, "main.rx", undefined, { production }); + try { + const page = await h.open(await h.serve()); await new Promise(r => setTimeout(r, 300)); + const before = await h.text(page, ".out"); + await page.evaluate(() => window.dispatchEvent(new Event("corpus-fire"))); await new Promise(r => setTimeout(r, 300)); + got.push({ before, after: await h.text(page, ".out"), problems: h.problems.slice(0, 3) }); + } catch (e) { got.push({ error: String(e.message ?? e).slice(0, 300) }); } + await h.close().catch(() => {}); + } + const clean = g => !g.error && !g.problems?.length; + const ran = /^io:|^inst$|^snap$|^path$|^untyped$/.test(x.shape) ? got.every(g => clean(g) && /^made /.test(g.before)) : x.shape === "effect" ? got.every(g => clean(g) && g.after === "shut") : got.every(g => clean(g) && g.after === "1"); + out.push({ id: x.id, ran, got }); + } + return out; +} + +// ---------------------------------------------------------------- the run +if (args[0] === "--worker") { + const [, file, wid] = args; + const { answer } = await import(pathToFileURL(path.join(TOOLS, "bench/ref-check.ts")).href); + const list = JSON.parse(readFileSync(file, "utf8")); + const out = await worker(list, wid, answer); + writeFileSync(file + ".out", JSON.stringify(out)); + process.exit(0); +} +const all = trials().filter(t => !opt("--only") || t.id.includes(opt("--only"))); +const jobs = Number(opt("--jobs", Math.max(2, Math.min(8, os.cpus().length - 2)))); +const tmp = path.join(ws, "corpus"); rmSync(tmp, { recursive: true, force: true }); mkdirSync(tmp, { recursive: true }); +const parts = Array.from({ length: jobs }, () => []); all.forEach((t, i) => parts[i % jobs].push(t)); +const t0 = Date.now(); +const done = await Promise.all(parts.map((p, k) => new Promise((res, rej) => { + const file = path.join(tmp, `part${k}.json`); writeFileSync(file, JSON.stringify(p)); + const c = spawn(process.execPath, ["--experimental-strip-types", "--no-warnings", fileURLToPath(import.meta.url), "--worker", file, String(k)], { stdio: ["ignore", "inherit", "inherit"], env: { ...process.env, CORPUS_KEEP: flag("--no-run") ? "" : "1" } }); + c.on("exit", code => code === 0 ? res(JSON.parse(readFileSync(file + ".out", "utf8"))) : rej(new Error(`worker ${k} exited ${code}`))); +}))); +const results = done.flat().sort((a, b) => a.id.localeCompare(b.id)); +const met = results.filter(r => r.result !== "not-met" && r.result !== "accepted-at-once"), failed = results.filter(r => r.result === "fail"), atOnce = results.filter(r => r.result === "accepted-at-once"); +const steps = met.reduce((n, r) => n + r.steps.length, 0), stepFails = failed.filter(r => r.fail.why !== "not-accepted" && r.fail.why !== "checkers-disagree" && r.fail.why !== "does-not-compile" && r.fail.why !== "class-not-constructed").length; +const by = (xs, k) => Object.entries(xs.reduce((m, x) => (m[k(x)] = (m[k(x)] ?? 0) + 1, m), {})).sort((a, b) => b[1] - a[1]); +console.log(`corpus: ${new Set(all.map(t => `${t.f.spec}#${t.r.name}`)).size} rows (${files().length} declaration files), ${all.length} trials, ${met.length} met their refusal (${results.length - met.length} not: the row's words already answer, or another refusal comes first); ${steps} suggestions pasted; ${met.filter(r => r.result === "pass").length} trials accepted, ${failed.length} failed (${stepFails} at a suggestion), ${((Date.now() - t0) / 1000).toFixed(0)} s, tools ${path.relative(path.dirname(repo), TOOLS) || TOOLS}`); +console.log(` by code: ${by(met, r => r.code).map(([k, n]) => `${k} ${n} (failed ${failed.filter(r => r.code === k).length})`).join("; ")}`); +console.log(` codes met: ${new Set(met.map(r => r.code)).size} (${[...new Set(met.map(r => r.code))].sort().join(", ")}); by shape: ${by(results.filter(r => r.result !== "not-met"), r => r.shape.replace(/^io:fn.*/, "io:fn").replace(/^io:.*/, "io")).map(([k, n]) => `${k} ${n}`).join("; ")}; taken at once (a component's callback prop): ${atOnce.length} (refused: ${results.filter(r => r.shape === "prop" && r.result === "fail").length})`); +console.log(` failures by why: ${by(failed, r => `${r.fail.why}${r.fail.how ? `/${r.fail.how}` : ""}`).map(([k, n]) => `${k} ${n}`).join("; ") || "none"}`); +console.log(` not met: ${by(results.filter(r => r.result === "not-met"), r => `${r.code}: ${r.why.split(",").slice(0, 2).join(",")}`).slice(0, 8).map(([k, n]) => `${k} ${n}`).join("; ")}`); +let runs = []; +if (!flag("--no-run")) { + const byId = new Map(all.map(t => [t.id, t])); + runs = await sampleRun([...met, ...atOnce].filter(r => (r.result === "pass" || r.result === "accepted-at-once") && r.dir).map(r => ({ ...r, trial: byId.get(r.id) })), Number(opt("--sample", 64))); + console.log(` run in Chromium (a sample over a stand-in package, both builds): ${runs.filter(x => x.ran).length} of ${runs.length} mounted and ran their callbacks`); + for (const x of runs.filter(x => !x.ran)) console.log(` ✗ ${x.id}: ${JSON.stringify(x.got).slice(0, 400)}`); + if (flag("--list-sample")) for (const x of runs) console.log(` ${x.ran ? "✓" : "✗"} ${x.id}: ${x.got.map(g => g.after ?? g.error).join(" / ")}`); +} +rmSync(tmp, { recursive: true, force: true }); +for (const r of failed.slice(0, Number(opt("--show", 12)))) console.log(` ✗ ${r.id}: ${r.fail.why}${r.fail.how ? ` (${r.fail.how})` : ""} — ${(r.fail.err ?? r.fail.said ?? r.fail.left?.join(" | ") ?? r.fail.msg ?? "").slice(0, 300)}`); +const summary = { trials: all.length, met: met.length, suggestions: steps, accepted: met.filter(r => r.result === "pass").length, atOnce: atOnce.length, failed: failed.length, ran: runs.length ? `${runs.filter(x => x.ran).length}/${runs.length}` : undefined, failures: Object.fromEntries(failed.map(r => [r.id, `${r.fail.why}${r.fail.how ? `/${r.fail.how}` : ""}`])) }; +if (flag("--json")) writeFileSync(opt("--json"), JSON.stringify({ summary, results }, null, 1)); +if (flag("--record")) { writeFileSync(RECORD, JSON.stringify({ ...summary, why: "compiler/test/corpus.mjs: each failure listed is a trial whose printed suggestion does not work, with the reason recorded in spec/archive or OPEN" }, null, 1) + "\n"); console.log(`recorded ${RECORD}`); } +if (flag("--check")) { + const rec = existsSync(RECORD) ? JSON.parse(readFileSync(RECORD, "utf8")) : { failures: {} }; + const fresh = Object.keys(summary.failures).filter(k => !(k in rec.failures)), healed = Object.keys(rec.failures).filter(k => !(k in summary.failures) && all.some(t => t.id === k)); + const lostRuns = runs.filter(x => !x.ran); + console.log(fresh.length ? `✗ ${fresh.length} failure(s) not recorded in compiler/test/corpus.json:\n${fresh.map(k => ` ${k}: ${summary.failures[k]}`).join("\n")}` : "✓ no failure that compiler/test/corpus.json does not record"); + if (healed.length) console.log(`✗ ${healed.length} recorded failure(s) pass now — take them off (--record):\n${healed.slice(0, 20).map(k => ` ${k}`).join("\n")}`); + if (met.length < (rec.met ?? 0) * 0.98) console.log(`✗ fewer trials meet their refusal than recorded (${met.length} < ${rec.met}): the corpus or the synthesis shrank`); + process.exit(fresh.length || healed.length || lostRuns.length || met.length < (rec.met ?? 0) * 0.98 ? 1 : 0); +} +process.exit(0); diff --git a/compiler/test/dev.mjs b/compiler/test/dev.mjs new file mode 100644 index 000000000..fcd3df17a --- /dev/null +++ b/compiler/test/dev.mjs @@ -0,0 +1,78 @@ +// 14 DEV-1, DEV-2 on the Node-API build (what the Vite front end calls) and `rxc app --dev`: a development build's keys and +// shapes are stable across rebuilds, unchanged by an edit anywhere but the declaration itself, and changed by that; the +// module part of a key is relative to the root; a production build has none and is what it was. DEV-8: each element of +// an .rx component is made through its site, `||[#n]`, and each `for` row is marked with its item. +// Usage: node compiler/test/dev.mjs (after `npm run build` and `cargo build --release` here) +import { mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { execFileSync } from "node:child_process"; +import { createRequire } from "node:module"; +import { fileURLToPath } from "node:url"; +import path from "node:path"; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const { app } = createRequire(import.meta.url)("../index.js"); +const rxc = process.env.RXC ?? path.join(here, `../target/${process.env.RX_PROFILE ?? "release"}/rxc`); +const root = path.join(here, ".out/dev"); rmSync(root, { recursive: true, force: true }); mkdirSync(path.join(root, "src/parts"), { recursive: true }); +let fail = 0; +const check = (name, ok, detail = "") => { if (!ok) fail++; console.log(`${ok ? "✓" : "✗"} ${name}${!ok && detail ? `: ${detail}` : ""}`); }; +const put = (f, t) => writeFileSync(path.join(root, f), t); +const lib = (extra = "") => `export source total := 0\n${extra}export component Part(props: { label: string }) {\n source open := false\n if open { source note := "a"\n

    {note}

    } else { source note := "b"\n

    {note}

    }\n { open := !open }}>{props.label}\n}\n`; +const main = (init = "0", view = "

    {n}

    ") => `import { Part } from "./parts/part.rx"\n\nexport default component App() {\n source n := ${init}\n source rows = n * 2\n
    ${view}{for r in [1, 2] {\n \n }}
    \n}\n`; +const keys = devRoot => { + const out = JSON.parse(app(path.join(root, "src/main.rx"), "dom", undefined, false, false, false, [], false, devRoot)); + if (!out.modules) throw new Error(JSON.stringify(out).slice(0, 400)); + return Object.fromEntries(Object.values(out.modules).flatMap(m => [...m.code.matchAll(/rt\$key\(__app, "([^"]+)", "([0-9a-f]{8})"/g)].map(x => [x[1], x[2]]))); +}; +put("src/parts/part.rx", lib()); put("src/main.rx", main()); +const a = keys(root); +check("each source of every module is keyed `||[#n]`, relative to the root (DEV-2a)", JSON.stringify(Object.keys(a).sort()) === JSON.stringify(["src/main.rx|App|n", "src/main.rx|App|rows", "src/parts/part.rx|Part|note", "src/parts/part.rx|Part|note#1", "src/parts/part.rx|Part|open", "src/parts/part.rx||total"]), JSON.stringify(a)); +check("a rebuild gives the same keys and shapes (DEV-2c)", JSON.stringify(keys(root)) === JSON.stringify(a)); +put("src/main.rx", "// a comment\n\n" + main("0", "

    {n} and more

    ")); put("src/parts/part.rx", lib("export source other := 1\n")); +const b = keys(root); +check("an edit elsewhere — the view, a comment, a blank line, another declaration — changes no pair (DEV-2b)", Object.keys(a).every(k => a[k] === b[k]) && b["src/parts/part.rx||other"] !== undefined, JSON.stringify([a, b])); +put("src/main.rx", main("1")); +const c = keys(root); +check("the declaration's own edit changes its shape, and only its own (DEV-2b)", c["src/main.rx|App|n"] !== a["src/main.rx|App|n"] && Object.keys(a).filter(k => k !== "src/main.rx|App|n" && !k.startsWith("src/parts")).every(k => a[k] === c[k]), JSON.stringify([a, c])); +const other = keys(path.join(root, "src")); +check("the module part is relative to the root given", Object.keys(other).includes("main.rx|App|n") && Object.keys(other).includes("parts/part.rx||total"), JSON.stringify(Object.keys(other))); +const prod = JSON.parse(app(path.join(root, "src/main.rx"), "dom")); +const prodSame = JSON.parse(app(path.join(root, "src/main.rx"), "dom", undefined, false, false, false, [], false, null)); +check("a production build has no key and is the same with the dev argument absent (DEV-5a)", Object.values(prod.modules).every(m => !m.code.includes("rt$key(")) && JSON.stringify(prod) === JSON.stringify(prodSame)); +const dev = JSON.parse(app(path.join(root, "src/main.rx"), "dom", undefined, false, false, false, [], false, root)); +/** `rt$key(__app, "k", "shape", () => call)` → `call`: the close of the call's own parenthesis found by depth, outside + * strings; DEV-8: `const S$n = rt$site("site", V$X);` and `rt$row(v$x);` dropped, and `S$n` read as `V$X` */ +const strip = code => { + // (11 CP-4b: and the import of the helpers only a development build names) + code = code.replace(/^import \{([^}\n]*)\} from "@reactivescript\/runtime";$/m, (_, names) => `import {${names.split(",").filter(n => !/^\s*(key|site|row) as /.test(n)).join(",")}} from "@reactivescript/runtime";`); + const sites = new Map([...code.matchAll(/^\s*const (S\$\d+) = rt\$site\("[^"]+", ([\w$]+)\);\n/gm)].map(x => [x[1], x[2]])); + code = code.replace(/^\s*const S\$\d+ = rt\$site\("[^"]+", [\w$]+\);\n/gm, "").replace(/^\s*rt\$row\([\w$]+\);\n/gm, "").replace(/\bS\$\d+\b/g, a => sites.get(a) ?? a); + for (let at; (at = code.search(/rt\$key\(__app, "[^"]+", "[0-9a-f]{8}", \(\) => /)) >= 0;) { + const head = code.slice(at).match(/^rt\$key\(__app, "[^"]+", "[0-9a-f]{8}", \(\) => /)[0]; + let i = at + head.indexOf("("), depth = 0, q = null; + for (; i < code.length; i++) { + const ch = code[i]; + if (q) { if (ch === "\\") i++; else if (ch === q) q = null; continue; } + if (ch === '"' || ch === "'" || ch === "`") q = ch; else if (ch === "(") depth++; else if (ch === ")" && --depth === 0) break; + } + code = code.slice(0, at) + code.slice(at + head.length, i) + code.slice(i + 1); + } + return code; +}; +const sitesOf = out => Object.values(out.modules).flatMap(m => [...m.code.matchAll(/rt\$site\("([^"]+)", ([\w$]+)\)/g)].map(x => `${x[1]} ${x[2]}`)).sort(); +check("each element of an .rx component is made through its site, `||:[#n]` (DEV-8a)", JSON.stringify(sitesOf(dev).map(x => x.replace(/:[0-9a-f]{8}/, ""))) === JSON.stringify(["src/main.rx|App|Part V$Part", "src/main.rx|App|Part V$Part", "src/main.rx||App V$App"]) && new Set(sitesOf(dev)).size === 3, JSON.stringify(sitesOf(dev))); +put("src/main.rx", main("0", `

    {n}

    `)); +const inserted = sitesOf(JSON.parse(app(path.join(root, "src/main.rx"), "dom", undefined, false, false, false, [], false, root))); +check("…and an element of the same tag inserted before others, with other attributes, moves no site (DEV-8a)", inserted.length === 4 && sitesOf(dev).every(x => inserted.includes(x)), JSON.stringify([sitesOf(dev), inserted])); +put("src/main.rx", main("1")); +check("…and each `for` row is marked with its item (DEV-8b)", Object.values(dev.modules).some(m => /\(v\$r\) => \{\s*rt\$row\(v\$r\);/.test(m.code)) && Object.values(prod.modules).every(m => !m.code.includes("rt$row(") && !m.code.includes("rt$site(")), ""); +// (11 CP-4b, step 2: a production build names a source's shape where its first value is a primitive or a list or record +// written out, `signalSource`/`storeSource`; a development build keeps `source`, whose carried value may be of another +// shape: the one other difference, put back here — none of the programs above keys a source) +const canon = code => code.replace(/^import \{([^}\n]*)\} from "@reactivescript\/runtime";$/m, (_, names) => `import { ${[...new Set(names.split(",").map(n => n.trim()).filter(Boolean))].sort().join(", ")} } from "@reactivescript/runtime";`); +// (and since 2026-12-02 a primitive is given to `signalSource` as it is, where `source` takes it as `untrack(() => v)`) +const lit = String.raw`("(?:[^"\\]|\\.)*"|-?[\w.]+)`; +const shaped = code => { const signals = new RegExp(String.raw`\brt\$signalSource\(("[^"]*"), ${lit}\)`, "g").test(code); return canon(code.replace(new RegExp(String.raw`\brt\$signalSource\(("[^"]*"), ${lit}\)`, "g"), "rt$source($1, rt$untrack(() => $2))").replace(/\b(signal|store)Source as rt\$(signal|store)Source\b/g, "source as rt$source").replace(/\brt\$(signal|store)Source\(/g, "rt$source(").replace(/^(import \{[^}\n]*)\} from "@reactivescript\/runtime";$/m, (m, h) => signals ? `${h}, untrack as rt$untrack } from "@reactivescript/runtime";` : m)); }; +check("a development build differs only by `rt$key(__app, …, () => …)` around each source's creating call, DEV-8's sites and rows, and production's named shapes (DEV-1b)", Object.keys(prod.modules).every(p => canon(strip(dev.modules[p].code)) === shaped(prod.modules[p].code)), Object.keys(prod.modules).map(p => strip(dev.modules[p].code).split("\n").find((l, i) => l !== prod.modules[p].code.split("\n")[i])).join(" / ")); +const cli = JSON.parse(execFileSync(rxc, ["app", path.join(root, "src/main.rx"), "--dev"], { cwd: root, encoding: "utf8" })); +check("`rxc app --dev` keys relative to the cwd; --root names another", Object.values(cli.modules).some(m => m.code.includes(`"src/main.rx|App|n"`)) && Object.values(JSON.parse(execFileSync(rxc, ["app", path.join(root, "src/main.rx"), "--dev", "--root", "src"], { cwd: root, encoding: "utf8" })).modules).some(m => m.code.includes(`"main.rx|App|n"`))); +process.exit(fail ? 1 : 0); diff --git a/compiler/test/drafts.mjs b/compiler/test/drafts.mjs new file mode 100644 index 000000000..b9eaf67a7 --- /dev/null +++ b/compiler/test/drafts.mjs @@ -0,0 +1,198 @@ +// MO-10i (RFC 09, ruled 2026-11-22): a library's draft is a place, not a value. What this runs is the guarantee itself, +// not a list of cases: whatever a callback does with its draft, nothing `.rx` holds afterwards is the library's own +// object. The library here takes its draft back for real — every object it hands the callback is a revocable proxy, +// revoked when the setter returns, so touching one later throws — and the compiled callback +// - copies what it reads out (the draft whole, a field, a nested record, through fns, in records and arrays, into a +// closure's capture): every value that left is read, deeply, after the revocation; +// - writes the draft in place: by path, with an updater that reads the draft, in a loop over a list of its own and +// over a path of the draft (`for (const t of d.items) { t.done := true }`), by the draft's own methods; +// and, with Solid 2's own store (whose draft is the store itself, live and tracked), what was read out does not follow +// the store. The programs that could keep the draft are refused (`DRAFT_ESCAPES`): a closure that names it, an `await`, +// a callback made elsewhere, the setter under another name, in a prop, or inside the result it came in. +// Runs on the server (Node): a JS component calls the handler it is given while it renders. Needs the crate's Node-API +// build (`npm run build` in compiler/), the runtime's build (runtime/dist) and ref/node_modules (Solid). +// node compiler/test/drafts.mjs +import { createRequire } from "node:module"; +import { mkdirSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import path from "node:path"; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const repo = path.resolve(here, "../.."); +const { app } = createRequire(import.meta.url)("../index.js"); +const ws = path.join(here, ".out/drafts"); rmSync(ws, { recursive: true, force: true }); +mkdirSync(path.join(ws, "node_modules/@reactivescript"), { recursive: true }); +for (const d of readdirSync(path.join(repo, "ref/node_modules")).filter(f => !f.startsWith("."))) symlinkSync(path.join(repo, "ref/node_modules", d), path.join(ws, "node_modules", d), "dir"); +symlinkSync(path.join(repo, "runtime"), path.join(ws, "node_modules/@reactivescript/runtime"), "dir"); +writeFileSync(path.join(ws, "package.json"), JSON.stringify({ type: "module" })); +writeFileSync(path.join(ws, "lib.d.rx"), [ + "export pure fn createStore(init: T): [T, (update: (draft state: T) => T | void) => void]", + "export pure fn solidStore(init: T): [T, (update: (draft state: T) => T | void) => void]", + "export fn sink(label: string, x: any): void", + "export fn later(f: handler () => void): void", + "export fn moveItem(draft list: any[], from: number, to: number): void", // changes the list it is given in place (2026-11-22) + "export fn sortCopy(list: any[]): void", // changes it too, and does not say so + "export component Run(props: { go: handler () => void })", + "", +].join("\n")); +writeFileSync(path.join(ws, "lib.js"), ` +import { createStore as solid } from "solid-js"; +export const sunk = {}; export const laters = []; export const states = []; export const leaked = []; +export const sink = (label, x) => { sunk[label] = x; }; +export const later = f => { laters.push(f); }; +export const moveItem = (list, from, to) => { const [x] = list.splice(from, 1); list.splice(to, 0, x); }; +export const sortCopy = list => { sunk.lent = list; list.reverse(); }; +export const Run = props => { props.go(); return ""; }; +// a store whose setter takes its draft back: every object the callback is handed is revoked when the setter returns +export const createStore = init => { + const state = init; states.push(state); + const set = f => { + const revokes = []; const made = new WeakMap(); const targets = new WeakMap(); + const wrap = o => { + if (o === null || typeof o !== "object") return o; + if (made.has(o)) return made.get(o); + // what is written back is its own object, never its proxy (as Solid's store and Immer unwrap what they are given) + const { proxy, revoke } = Proxy.revocable(o, { get: (t, k, r) => wrap(Reflect.get(t, k, r)), set: (t, k, v) => Reflect.set(t, k, targets.get(v) ?? v) }); + made.set(o, proxy); targets.set(proxy, o); revokes.push(revoke); return proxy; + }; + const draft = wrap(state); leaked.push(draft); + try { f(draft); } finally { for (const r of revokes) r(); } + }; + return [state, set]; +}; +export const solidStore = init => solid(init); +`); +const head = 'import { createStore, solidStore, sink, later, Run } from "./lib.js"\nfn keep(x) { x }\n'; +const main = `${head}export default component App() { + [todos, setTodos] = createStore<{ done: number; step: number; items: { text: string; done: boolean }[]; sub: { n: number } }>({ done: 0, step: 10, items: [{ text: "a", done: false }, { text: "b", done: false }], sub: { n: 1 } }) + { setTodos((d) => { + sink("whole", d) + sink("kept", keep(keep(d))) + sink("held", [d.items, { s: d.sub }, true ? d : null]) + sink("scalar", d.done) + let xs = d.items + let n = d.done + let sub = d.sub + later(() => { sink("later", [xs, n, sub]) }) + for (const t of d.items) { t.done := true } + for (const x of [1, 2]) { d.done := d.done + x } + d.done := v => v + d.step + d.items.push({ text: "c", done: false }) + d.sub := { n: d.sub.n + 1 } + let i = d.items.findIndex((t) => t.text == "a") + if (i >= 0) { d.items.splice(i, 1) } + sink("found", d.items.find((t) => t.text == "b")) + sink("count", len(d.items)) + sink("after", d) + }) }} /> +

    {todos.done}

    +} +`; +const solid = `${head}export default component App() { + [todos, setTodos] = solidStore<{ items: string[] }>({ items: ["a"] }) + { + setTodos((d) => { sink("items", d.items); sink("store", d) }) + setTodos((d) => { d.items.push("b") }) + setTodos((d) => { for (const x of ["c", "d"]) { d.items.push(x) }; sink("len", len(d.items)) }) + }} /> +

    {len(todos.items)}

    +} +`; +const store = " [todos, setTodos] = createStore<{ done: number; items: string[] }>({ done: 0, items: [] })\n"; +const page = (body, pre = "") => `${head}${pre}export default component App() {\n${store}${body}\n

    {todos.done}

    \n}\n`; +const refused = { + "a closure made in the callback writes a path later": [page(" { setTodos((d) => { later(() => { d.done := 1 }) }) }} />"), "DRAFT_ESCAPES"], + "a closure made in the callback reads it later": [page(" { setTodos((d) => { later(() => { sink(\"n\", d.done) }) }) }} />"), "DRAFT_ESCAPES"], + "a closure given to a method names it (a loop is the statement)": [page(" { setTodos((d) => { [1, 2].forEach((x) => { d.done := d.done + x }) }) }} />"), "DRAFT_ESCAPES"], + "an await in the callback": [page(" { setTodos((d) => { let v = await sink(\"x\", 1); d.done := 2 }) }} />"), "DRAFT_ESCAPES"], + // (2026-11-22: a closure given a name and used only as the setter's argument is its callback, checked as one; any + // other use of the name is where it could be handed something else, or keep the draft) + "a named callback also passed elsewhere": [page(" { let up = (d) => { sink(\"d\", d) }; setTodos(up); later(up) }} />"), "DRAFT_ESCAPES"], + "a named callback also called by hand": [page(" { let up = (d) => { d.done := 1 }; setTodos(up); up(todos) }} />"), "DRAFT_ESCAPES"], + "a function that is not a closure written here, given to the setter": [page(" {}} />", "component Row(props: { up: any }) {\n [todos, setTodos] = createStore<{ done: number }>({ done: 0 })\n { setTodos(props.up) }} />\n}\n").replace(store, ""), "DRAFT_ESCAPES"], + "the setter under another name": [page(" { let set2 = setTodos; set2((d) => { sink(\"d\", d) }) }} />"), "DRAFT_ESCAPES"], + "the setter passed to a component": [page(" ", "component Row(props: { set: any }) {\n { props.set((d) => { sink(\"d\", d) }) }} />\n}\n"), "DRAFT_ESCAPES"], + "the setter inside the result it came in, passed whole": [`${head}component Row(props: { st: any }) {\n { props.st[1]((d) => { sink("d", d) }) }} />\n}\nexport default component App() {\n st = createStore<{ done: number }>({ done: 0 })\n \n}\n`, "DRAFT_ESCAPES"], + "a path of a local read from the draft (a copy) is not written": [page(" { setTodos((d) => { let a = d; a.done := 1 }) }} />"), "WRITE_TO_NON_SOURCE"], +}; +// a callback given a name and shared by two calls: its parameter is the draft, what it reads out a copy +const named = page(" { let up = (d) => { d.done := d.done + 1; sink(\"named\", d) }; setTodos(up); setTodos(up) }} />"); +const { createApp } = await import(pathToFileURL(path.join(ws, "node_modules/@reactivescript/runtime/dist/server.js")).href); +const lib = await import(pathToFileURL(path.join(ws, "lib.js")).href); +let pass = 0, fail = 0, seq = 0; +const check = (name, ok, detail) => { if (ok) pass++; else fail++; console.log(`${ok ? "✓" : "✗"} ${name}${ok ? "" : `\n ${String(typeof detail === "string" ? detail : JSON.stringify(detail)).slice(0, 900)}`}`); }; +const run = async (name, src) => { + const file = path.join(ws, `${name}.rx`); writeFileSync(file, src); + const out = JSON.parse(app(file, "ssr")); + if (out.diagnostics || out.error) return { refused: out }; + const js = path.join(ws, `${name}.gen.mjs`); writeFileSync(js, Object.values(out.modules)[0].code); + const m = (await import(pathToFileURL(js).href)).default; + let html = "", threw = null; + const a = createApp({ request: new Request("http://x/") }); + try { await new Promise((res, rej) => { try { a.stream(m(a), { write: c => { html += c; }, end: res }); } catch (e) { rej(e); } setTimeout(res, 1500); }); } catch (e) { threw = e; } + return { html, threw, code: Object.values(out.modules)[0].code }; +}; +const same = (a, b) => JSON.stringify(a) === JSON.stringify(b); +{ + const r = await run("main", main); + check("the callback is accepted, and runs", !r.refused && !r.threw && Object.keys(lib.sunk).length > 0, r.refused ?? r.threw?.stack ?? r.html); + // the library did take its draft back: its own object throws when touched + let revoked = false; try { void lib.leaked[0].done; } catch { revoked = true; } + check("the library's draft is revoked once its setter returns (touching it throws)", revoked); + // the guarantee: everything that left the callback is readable now, to its leaves — nothing of it is the draft + let alive = null; try { for (const f of lib.laters) f(); JSON.stringify(lib.sunk); } catch (e) { alive = e; } + check("everything read out of the draft is a copy: all of it reads after the revocation, the closure's captures too", alive === null, alive?.message); + const before = { done: 0, step: 10, items: [{ text: "a", done: false }, { text: "b", done: false }], sub: { n: 1 } }; + check("the draft read whole is what it held then", same(lib.sunk.whole, before) && same(lib.sunk.kept, before), lib.sunk.whole); + check("its parts, in a record and an array, and through `?:`", same(lib.sunk.held, [before.items, { s: before.sub }, before]), lib.sunk.held); + check("a scalar is itself", lib.sunk.scalar === 0 && lib.sunk.count === 2, [lib.sunk.scalar, lib.sunk.count]); + check("locals a later closure captured hold what the draft held at the read", same(lib.sunk.later, [before.items, 0, before.sub]), lib.sunk.later); + const after = { done: 13, step: 10, items: [{ text: "b", done: true }, { text: "c", done: false }], sub: { n: 2 } }; + check("the writes landed in the library's state: paths, a loop over a list, a loop over the draft's items, an updater reading the draft, its own methods", same(lib.states[0], after), lib.states[0]); + check("what a method of the draft answers is copied where it is kept", same(lib.sunk.found, { text: "b", done: true }) && same(lib.sunk.after, after), [lib.sunk.found, lib.sunk.after]); + check("the copies are the program's own: none is the library's object", lib.sunk.whole !== lib.states[0] && lib.sunk.after.items !== lib.states[0].items && lib.sunk.found !== lib.states[0].items[0]); + check("what goes straight back to the library is not copied (a value written to a path, a method's argument)", /v\$d\["sub"\] = \{/.test(r.code ?? "") && !/push\(rt\$copy/.test(r.code ?? "") && /rt\$copy\(v\$d\)/.test(r.code ?? ""), (r.code ?? "").slice((r.code ?? "").indexOf("v$setTodos"), (r.code ?? "").indexOf("v$setTodos") + 1500)); +} +{ + for (const k of Object.keys(lib.sunk)) delete lib.sunk[k]; + const r = await run("solid", solid); + check("Solid 2's store: the callbacks run", !r.refused && !r.threw && lib.sunk.len === 4, r.refused ?? r.threw?.stack ?? lib.sunk); + check("what was read out of Solid's draft does not follow the store (it is not the store)", same(lib.sunk.items, ["a"]) && same(lib.sunk.store, { items: ["a"] }), lib.sunk); +} +// the same guarantee over every way an expression hands a value on, and every pair of them (the matrix the checkers' +// tests run, `a_draft_is_named_only_in_its_callback`): each read of the draft is sunk, and all of it read afterwards +{ + for (const k of Object.keys(lib.sunk)) delete lib.sunk[k]; + const WRAPS = ["X", "[X]", "[X][0]", "({ a: X })", "({ a: X }).a", "keep(X)", "keep(keep(X))", "id(id(X))", "o.f(X)", "[(y) => y][0](X)", "(true ? keep : keep)(X)", "mk(X)()", "[].concat([X])", "[].concat([X])[0]", "(true ? X : null)", "(X ?? null)", "(X || null)", "map([X], (y) => y)", "map([X], (y) => y)[0]", "filter([X], (y) => true)", "[X, 1].filter((y) => true)", "[...[X]]", "({ ...({ a: X }) })", "X.part", "X[\"part\"]", "X[k]"]; + const one = WRAPS.map(w => w.replaceAll("X", "d")); const all = [...one]; for (const w of WRAPS) for (const inner of one.slice(1)) all.push(w.replaceAll("X", inner)); + const src = `${head}fn mk(x) { () => x }\nexport default component App() {\n [todos, setTodos] = createStore({ part: { n: 1, part: { m: [2] } }, done: 0 })\n o = { f: (x) => x }\n id = (x) => x\n k = "part"\n { setTodos((d) => {\n${all.map((e, i) => ` sink("w${i}", ${e})`).join("\n")}\n d.done := d.done + 1\n }) }} />\n

    {todos.done}

    \n}\n`; + const r = await run("matrix", src); + let alive = null; try { JSON.stringify(lib.sunk); } catch (e) { alive = e; } + check(`every way of handing a read of the draft on, and every pair of them (${all.length}): accepted, run, and all of it reads after the revocation`, !r.refused && !r.threw && Object.keys(lib.sunk).length === all.length && alive === null, r.refused ?? r.threw?.stack ?? alive?.message ?? Object.keys(lib.sunk).length); + check("and the callback still wrote the draft", lib.states[lib.states.length - 1]?.done === 1, lib.states[lib.states.length - 1]); +} +// MO-10i (2026-11-22): a draft given to JS. A fn whose parameter is declared `draft` is given the draft itself, and its +// change is the store's; a fn whose parameter is not marked is lent a copy — what it keeps reads after the revocation, +// and what it changes is its copy (in a development build the call throws, once it returns, and the copy is put back: compiler/test/confined.mjs) +{ + for (const k of Object.keys(lib.sunk)) delete lib.sunk[k]; + const src = `import { createStore, moveItem, sortCopy, sink, Run } from "./lib.js"\nexport default component App() {\n [todos, setTodos] = createStore<{ items: string[] }>({ items: ["a", "b", "c"] })\n { setTodos((d) => { moveItem(d.items, 0, 2); sortCopy(d.items) }) }} />\n}\n`; + const r = await run("helper", src); + const state = lib.states[lib.states.length - 1]; + let kept = null, threw = r.threw; try { kept = JSON.stringify(lib.sunk.lent); } catch (e) { threw = e; } + check("a JS helper with a `draft` parameter is given the draft itself: its change is the store's", !r.refused && !threw && same(state?.items, ["b", "c", "a"]), r.refused ?? threw?.stack ?? state); + check(`…and one without is lent a copy: what it kept reads after the revocation (${kept}), and what it changed was not the store`, !threw && kept === '["a","c","b"]', threw?.stack ?? kept); + check("the compiled call: the draft as it is at the `draft` parameter, a copy lent at the other (`rt$lent`)", /v\$moveItem\(v\$d\.items, 0, 2\)/.test(r.code ?? "") && /rt\$lent\(v\$sortCopy, "sortCopy", "d", rt\$copy\(v\$d\.items\)\)/.test(r.code ?? ""), (r.code ?? "").slice((r.code ?? "").indexOf("v$setTodos"), (r.code ?? "").indexOf("v$setTodos") + 300)); +} +{ + const r = await run("named", named); + let read = null, threw = r.threw; try { read = JSON.stringify(lib.sunk.named); } catch (e) { threw = e; } + check(`a named callback, given to the setter twice: accepted, the draft written, and what it read out read after the revocation (${read})`, !r.refused && !threw && read === '{"done":2,"items":[]}', r.refused ?? threw?.stack ?? read); +} +for (const [name, [src, code]] of Object.entries(refused)) { + const r = await run(`r${++seq}`, src); + check(`refused (${code}): ${name}`, (r.refused?.diagnostics ?? []).some(d => d.code === code), r.refused ?? "accepted"); +} +rmSync(ws, { recursive: true, force: true }); +console.log(`\n${pass} passed, ${fail} failed`); +process.exit(fail ? 1 : 0); diff --git a/compiler/test/formisch.mjs b/compiler/test/formisch.mjs new file mode 100644 index 000000000..d90a03201 --- /dev/null +++ b/compiler/test/formisch.mjs @@ -0,0 +1,74 @@ +// Formisch (its Solid 2 build) and Solid 2's store from .rx (spec/09 MO-10i, E-10), end to end: examples/formisch installed +// from npm into .out/formisch (once; again when its package.json changes), with this package, the runtime and the language +// server linked as installed; type-checked by rx-tsc (the .rx with the libraries' own types, its .d.rx against them, TY-6) +// and refused where it should be; built by Vite; and driven in Chromium: the form validates with valibot and its submit +// writes an .rx source, and the store is written through its setter's draft. +// The Node-API build first (`npm run build` here), the WebAssembly one (`cargo build --lib --release --target +// wasm32-unknown-unknown`), and the runtime's (`npm run build` in ../runtime). Usage: node compiler/test/formisch.mjs +import { cpSync, existsSync, mkdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { execFileSync } from "node:child_process"; +import { createServer } from "node:http"; +import { createRequire } from "node:module"; +import { fileURLToPath } from "node:url"; +import path from "node:path"; +import { relinked } from "../../scripts/lib/relink.mjs"; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const repo = path.resolve(here, "../.."); +const ws = path.join(here, ".out/formisch"); +const pkg = relinked(readFileSync(path.join(repo, "examples/formisch/package.json"), "utf8"), path.join(repo, "examples/formisch"), ws); // Solid is the pin's, linked (scripts/lib/relink.mjs) +mkdirSync(ws, { recursive: true }); +if (!existsSync(path.join(ws, "node_modules/@formisch/solid")) || (existsSync(path.join(ws, "package.json")) && readFileSync(path.join(ws, "package.json"), "utf8") !== pkg)) { + writeFileSync(path.join(ws, "package.json"), pkg); + execFileSync("npm", ["install", "--no-audit", "--no-fund", "--silent", "--legacy-peer-deps"], { cwd: ws, stdio: "inherit" }); +} +rmSync(path.join(ws, "src"), { recursive: true, force: true }); +for (const f of ["src", "index.html", "vite.config.mjs", "tsconfig.json"]) cpSync(path.join(repo, "examples/formisch", f), path.join(ws, f), { recursive: true }); +const rx = path.join(ws, "node_modules/@reactivescript"); rmSync(rx, { recursive: true, force: true }); mkdirSync(path.join(rx, "runtime"), { recursive: true }); +symlinkSync(path.join(repo, "compiler"), path.join(rx, "compiler")); +symlinkSync(path.join(repo, "tooling/rx-language-server"), path.join(rx, "language-server")); +for (const f of ["package.json", "dist", "rx-lib.d.ts"]) cpSync(path.join(repo, "runtime", f), path.join(rx, "runtime", f), { recursive: true }); + +let pass = 0, fail = 0; +const check = (name, ok, got) => { ok ? pass++ : fail++; console.log(`${ok ? " ✓" : " ✗"} ${name}${ok ? "" : `\n ${JSON.stringify(got).slice(0, 500)}`}`); }; +const rxTsc = () => { try { execFileSync(process.execPath, [path.join(rx, "language-server/bin/tsc.js"), "--noEmit", "-p", "tsconfig.json"], { cwd: ws, encoding: "utf8" }); return ""; } catch (e) { return String(e.stdout ?? "") + String(e.stderr ?? ""); } }; +const main = path.join(ws, "src/main.rx"); const good = readFileSync(main, "utf8"); +check("rx-tsc: main.rx with Formisch's, valibot's and Solid's types, and the .d.rx against them (TY-6)", rxTsc() === "", rxTsc()); +const refused = (name, edit, want) => { const bad = edit(good); if (bad === good) { check(name, false, "the edit did not apply"); return; } writeFileSync(main, bad); const out = rxTsc(); writeFileSync(main, good); check(name, want.test(out), out); }; +refused("the draft itself is not reassigned: the callback returns the new value (MO-10i)", s => s.replace("{ d.done := v => v + 1 }", "{ d := { items: [], done: 0 } }"), /WRITE_TO_NON_SOURCE/); +refused("a draft's field is written with its own type (TS2345)", s => s.replace("d.done := v => v + 1", "d.done := \"many\""), /main\.rx\(\d+,\d+\): error TS2345/); +refused("a closure made in the callback may not name the draft: a loop is the statement (DRAFT_ESCAPES)", s => s.replace("for (const item of d.items) { d.done := d.done + 1 }", "d.items.forEach((item) => { d.done := d.done + 1 })"), /DRAFT_ESCAPES/); +refused("the setter is called by its own name, not passed on (DRAFT_ESCAPES)", s => s.replace("setTodos((d) => { kept := d.items })", "let set = setTodos; set((d) => { kept := d.items })"), /DRAFT_ESCAPES/); +refused("a schema that reads a source is still a snapshot (E-10)", s => s.replace("form = createForm({ schema: schema })", "form = createForm({ schema: object({ email: pipe(string(), minLength(len(text))) }) })"), /SNAPSHOT_ARGUMENT/); +execFileSync(process.execPath, [path.join(ws, "node_modules/vite/bin/vite.js"), "build"], { cwd: ws, stdio: ["ignore", "ignore", "inherit"], env: { ...process.env, RX_TYPECHECK: "0" } }); + +const dist = path.join(ws, "dist"); +const http = createServer((req, res) => { const f = path.join(dist, req.url === "/" ? "index.html" : req.url.split("?")[0]); if (!existsSync(f)) { res.statusCode = 404; return res.end(); } res.setHeader("content-type", f.endsWith(".js") ? "text/javascript" : f.endsWith(".css") ? "text/css" : "text/html"); res.end(readFileSync(f)); }); +await new Promise(r => http.listen(0, "127.0.0.1", r)); +const { chromium } = createRequire(path.join(repo, "ref/package.json"))("playwright"); +const browser = await chromium.launch(); const page = await browser.newPage(); +const problems = []; page.on("console", m => { if (["error", "warning"].includes(m.type())) problems.push(m.text().slice(0, 200)); }); page.on("pageerror", e => problems.push(String(e).slice(0, 200))); +const text = async () => (await page.textContent("body")).replace(/\s+/g, " ").trim(); +const until = async ok => { for (let i = 0; i < 60; i++) { if (await ok()) return true; await page.waitForTimeout(50); } return false; }; +await page.goto(`http://127.0.0.1:${http.address().port}/`); +check("mounted: the form and the list", await until(async () => (await text()).includes("Sign in") && (await text()).includes("0 of 0 done")), await text()); +await page.click(".submit"); +check("an empty submit shows valibot's messages", await until(async () => (await text()).includes("Enter a valid email") && (await text()).includes("At least 8 characters")), await text()); +await page.fill(".email", "ann@example.com"); await page.fill(".password", "longenough1"); await page.click(".submit"); +check("a valid submit writes the .rx source from onSubmit", await until(async () => (await text()).includes("signed in: ann@example.com") && !(await text()).includes("Enter a valid email")), await text()); +await page.fill(".text", "milk"); await page.click(".add"); await page.fill(".text", "eggs"); await page.click(".add"); +check("the store's draft is appended to through its setter", await until(async () => (await text()).includes("milkeggs") && (await text()).includes("0 of 2 done")), await text()); +await page.click(".finish"); +check("and a field of it written", await until(async () => (await text()).includes("1 of 2 done")), await text()); +// MO-10i (ruled 2026-11-22): a read of the draft is a copy — Solid's draft is the store itself, live and tracked, so a +// source that held it would follow the store; and a loop is the statement, in the callback's own scope +await page.click(".keep"); +check("what is read out of the draft is kept as it was", await until(async () => (await text()).includes("2 kept")), await text()); +await page.fill(".text", "tea"); await page.click(".add"); +check("...and does not follow the store when it changes (a copy, not Solid's live draft)", await until(async () => (await text()).includes("1 of 3 done")) && (await text()).includes("2 kept"), await text()); +await page.click(".all"); +check("a loop over the draft's items writes the draft (for … of)", await until(async () => (await text()).includes("3 of 3 done")), await text()); +check("no console errors or warnings", problems.length === 0, problems); +await browser.close(); http.close(); +console.log(`\n${pass} passed, ${fail} failed`); +process.exit(fail ? 1 : 0); diff --git a/compiler/test/habits.mjs b/compiler/test/habits.mjs new file mode 100644 index 000000000..7b5bce8fb --- /dev/null +++ b/compiler/test/habits.mjs @@ -0,0 +1,152 @@ +// 07, EF-5, R-f-6 (2026-12-02): habits of TypeScript and Solid whose refusal printed nothing to write (the study rx-remaining, +// B2-1–B2-4: `fn f({ x, y }: P)`, `onClick={async () => …}`, `while` with a write, `onCleanup(…)`), and the messages met on +// the way through them. Each is checked by both checkers as first written; where it is refused, what the message prints is +// pasted as printed and checked again, and the program that comes out is run in Chromium (Solid's development and +// production builds) and must do what the first one meant. node compiler/test/habits.mjs (needs what bench/run.mjs needs) +import { cpSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { spawnSync } from "node:child_process"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { ws, workspace, both, Runner } from "../../bench/harness.mjs"; + +const repo = path.join(path.dirname(fileURLToPath(import.meta.url)), "../.."); +workspace(); +const dir = path.join(ws, "habits"); rmSync(dir, { recursive: true, force: true }); mkdirSync(dir, { recursive: true }); +cpSync(path.join(repo, "std/package.json"), path.join(dir, "node_modules/@reactivescript/std/package.json")); +cpSync(path.join(repo, "std/src"), path.join(dir, "node_modules/@reactivescript/std/src"), { recursive: true }); + +let pass = 0, fail = 0; +const check = (name, ok, got) => { ok ? pass++ : fail++; console.log(`${ok ? "✓" : "✗"} ${name}${ok ? "" : `\n ${String(typeof got === "string" ? got : JSON.stringify(got)).slice(0, 900)}`}`); return !!ok; }; +let seq = 0; +const file = src => { const f = path.join(dir, `p${++seq}.rx`); writeFileSync(f, src); return f; }; +const codes = r => r.diagnostics.map(d => d.code); +const show = r => `crate: ${codes(r.crate).join(",") || "accepted"} / ref: ${codes(r.ref).join(",") || "accepted"} — ${[...r.crate.diagnostics, ...r.ref.diagnostics].map(d => d.message).join(" | ").slice(0, 700)}`; +const msg = r => r.crate.diagnostics.map(d => d.message).join("\n"); +/** Refused alike, with `code`, and a message that holds every one of `says`. */ +const refused = (name, src, code, says = []) => { const r = both(file(src)); check(`refused (${code}) and says what to write: ${name}`, r.agree && codes(r.crate).includes(code) && codes(r.ref).includes(code) && says.every(s => msg(r).includes(s) && r.ref.diagnostics.map(d => d.message).join("\n").includes(s)), show(r)); return r; }; +const accepted = (name, src) => { const f = file(src); const r = both(f); return check(`accepted: ${name}`, r.agree && !r.crate.diagnostics.length && !r.ref.diagnostics.length, show(r)) ? f : null; }; +/** Clicks `.b` `clicks` times, in both builds: what `.o` shows after each. */ +async function run(name, f, clicks, want) { + if (!f) return; + for (const production of [false, true]) { + const h = new Runner(dir, path.basename(f), undefined, { production }); + const base = await h.serve(); const page = await h.open(base); const seen = [await h.text(page, ".o")]; + for (let k = 0; k < clicks; k++) { await page.click(".b"); await new Promise(res => setTimeout(res, 150)); seen.push(await h.text(page, ".o")); } + check(`${name}, ${production ? "production" : "development"}: ${seen.join(" → ")}`, JSON.stringify(seen) === JSON.stringify(want) && !h.problems.length, { seen, problems: h.problems }); + await h.close(); + } +} + +// B2-1: a fn's parameter destructured is read as a component's props are (RG-4b): each name an equation of the body +{ + const f = accepted("fn len({ x, y }: P) (rx-remaining h01)", 'type P = { x: number; y: number }\nfn len({ x, y }: P): number => Math.sqrt(x * x + y * y)\nexport default component App() {\n source p: P := { x: 3, y: 4 }\n \n}\n'); + await run("…and computes from the record it is given", f, 1, ["5", "10"]); + accepted("…a default, a rename, an array pattern, and a block body", 'type P = { a: number; b?: number }\nfn f({ a: first, b = 2 }: P, [k, j]: number[]): number {\n s = first + b\n s * k + j\n}\nexport default component App() {\n

    {f({ a: 1 }, [10, 1])}

    \n}\n'); + const g = accepted("…exported, and called from another module's handler", 'type P = { x: number; y: number }\nexport fn sum({ x, y }: P): number => x + y\nexport default component App() {\n source n := 0\n \n}\n'); + await run("…and a handler's call of it", g, 2, ["0", "2", "4"]); + refused("…a `ref` parameter is a name (an accessor is not destructured)", "fn f(ref { a }: { a: number }): number => a\nexport default component App() {\n

    {f({ a: 1 })}

    \n}\n", "PARSE"); +} + +// B2-2: `async` before an arrow +{ + const r = refused("onClick={async () => …} (h12)", 'export default component App() {\n source r := ""\n \n}\n', "PARSE", ["`async` is not written in .rx", "`() => { … }`"]); + void r; + refused("…with a parameter, `async (e) =>`", 'export default component App() {\n source r := ""\n { r := e.target.value }} />\n}\n', "PARSE", ["`async` is not written in .rx"]); + refused("…and `async e =>`", 'export default component App() {\n source r := ""\n { r := e.target.value }} />\n}\n', "PARSE", ["`async` is not written in .rx"]); + // the message's way, and the next ones on it (std's fetch, a statement's await, the handler's failure), pasted in turn + const first = 'export default component App() {\n source r := ""\n \n}\n'; + const r1 = both(file(first)); + const imp = /`(import \{ fetch \} from "@reactivescript\/std\/platform")`/.exec(msg(r1))?.[1]; + check("…written without the word: `fetch` prints std's import, the `await` inside an expression its statement", r1.agree && !!imp && /let v = await x\.text\(…\)/.test(msg(r1)), show(r1)); + const second = `${imp}\n` + first.replace("r := await x.text()", "let v = await x.text(); r := v"); + const r2 = both(file(second)); + check("…pasted: what is left is the handler's failure, and its message prints the `try` (no caller's)", r2.agree && JSON.stringify(codes(r2.crate)) === '["UNCAUGHT_ACTION_FAILURE"]' && /this handler is an action/.test(msg(r2)) && /`try \{ … \} catch \(e\) \{ error := e\.message \}`/.test(msg(r2)) && !/inferred here \(AC-1b/.test(msg(r2)), show(r2)); + const f = accepted("…the steps in that `try`", second.replace("{ const x = await fetch(\"data:text/plain,hi\"); let v = await x.text(); r := v }", "{ try { const x = await fetch(\"data:text/plain,hi\"); let v = await x.text(); r := v } catch (e) { r := e.message } }")); + await run("…and runs", f, 1, ["", "hi"]); +} + +// B2-3: `while` with a write +{ + const src = 'export default component App() {\n source n := 0\n \n}\n'; + refused("while (n < 3) { n := n + 1 } in a handler (h02)", src, "PARSE", ["`while` is not .rx", "`fn step(n: number): number => n < 3 ? step(n + 1) : n`", "`n := step(n)`"]); + const f = accepted("…the printed fn and write, pasted", 'fn step(n: number): number => n < 3 ? step(n + 1) : n\n' + src.replace("{ while (n < 3) { n := n + 1 } }", "{ n := step(n) }")); + await run("…and ends where the loop would have", f, 1, ["0", "3"]); + refused("…its own condition and step are printed (k > 1, k := k - 2)", 'export default component App() {\n source k := 9\n \n}\n', "PARSE", ["`fn step(k: number): number => k > 1 ? step(k - 2) : k`", "`k := step(k)`"]); + refused("…a loop on a line of its own", 'export default component App() {\n source n := 0\n \n}\n', "PARSE", ["`fn step(n: number): number => n < 3 ? step(n + 1) : n`"]); + refused("…a loop that reads another name gets the form, not a false fn", 'export default component App() {\n source n := 0\n source m := 3\n \n}\n', "PARSE", ["`while` is not .rx", "a fn that calls itself"]); +} + +// B2-4: `onCleanup(…)` in an effect +{ + const src = 'export default component App() {\n source n := 0\n source ticks := 0\n effect (n) { let t = setInterval(() => { ticks := v => v + 1 }, 20); onCleanup(() => clearInterval(t)) }\n \n}\n'; + refused("onCleanup(…) in an effect's apply block (h07)", src, "UNBOUND", ["write `return () => clearInterval(t)` as the block's last statement"]); + const f = accepted("…the printed `return`, pasted", src.replace("onCleanup(() => clearInterval(t))", "return () => clearInterval(t)")); + await run("…and runs", f, 2, ["0", "1", "2"]); + refused("…a function given by its name", 'export default component App() {\n source n := 0\n effect (n) { let stop = () => {}; onCleanup(stop) }\n

    {n}

    \n}\n', "UNBOUND", ["write `return stop`"]); + accepted("…a program that declares its own onCleanup is its own", 'fn onCleanup(x: number): number => x + 1\nexport default component App() {\n source n := 0\n source m := 0\n effect (n) { m := onCleanup($0) }\n

    {m}

    \n}\n'); +} + +// what else the study's habits printed that was no way through (h08): `throw new Error(…)` printed a `.js` factory beside the error class +{ + const src = 'export default component App() {\n source msg := ""\n action go(s: string) { try { if (s == "") { throw new Error("empty") }; msg := s } catch (e) { msg := "bad" } }\n \n}\n'; + const r = refused("throw new Error(…) (h08): the error class to declare, once", src, "UNBOUND", ["`error Failed(message: string) => message`"]); + check("…and no `.js` factory for `new Error`", !/made\.js/.test(msg(r)) && codes(r.crate).length === 1, show(r)); + const f = accepted("…the printed class, pasted", 'error Failed(message: string) => message\n' + src.replace('throw new Error("empty")', 'throw Failed("empty")')); + await run("…and runs", f, 1, ["", "bad"]); +} + +// (h15) a property of the page's own object, written with `=`: the message led with `document.title := …`, which is refused +{ + const src = 'export default component App() {\n source n := 0\n effect (n) { document.title = "n " + $0 }\n \n}\n'; + const r = refused("document.title = … in an effect (h15): the setter to write, with its own value", src, "ASSIGNMENT", ["`export const setTitle = (v) => { document.title = v }`", "`import { setTitle } from \"./page.js\"`", '`setTitle("n " + $0)`']); + check("…and no `document.title := …`", !/document\.title :=/.test(msg(r)), show(r)); + writeFileSync(path.join(dir, "page.js"), "export const setTitle = (v) => { document.title = v }\n"); + const f = accepted("…the printed helper, pasted", 'import { setTitle } from "./page.js"\n' + src.replace('document.title = "n " + $0', 'setTitle("n " + $0)')); + if (f) for (const production of [false, true]) { + const h = new Runner(dir, path.basename(f), undefined, { production }); const page = await h.open(await h.serve()); + await page.click(".b"); await new Promise(res => setTimeout(res, 150)); + check(`…and sets the title, ${production ? "production" : "development"}`, (await page.title()) === "n 1" && !h.problems.length, { title: await page.title(), problems: h.problems }); + await h.close(); + } + // re-check 15's c06 (2026-12-02): the helper as printed failed rx-tsc (TS7016, no declaration for ./page.js) — the message + // prints its \`.d.ts\` line too; and a template value was cut at its first \`}\` (\`setTitle(\`${laps.length)\`) + const tpl = src.replace('document.title = "n " + $0', "document.title = `${$0} laps`"); + writeFileSync(path.join(dir, "h15t.rx"), tpl); + const r2 = both(path.join(dir, "h15t.rx")), m2 = r2.crate.diagnostics[0]?.message ?? ""; + check("…a template value printed whole, and the `.d.ts` line, both checkers alike", r2.agree && (r2.ref.diagnostics[0]?.message ?? "").endsWith(m2.slice(m2.indexOf(" — "))) && m2.includes("`setTitle(`${$0} laps`)`") && m2.includes("`export declare const setTitle: (v: string) => void` in ./page.d.ts"), show(r2)); + const td = path.join(dir, "h15-tsc"); rmSync(td, { recursive: true, force: true }); mkdirSync(td, { recursive: true }); + const dts = /`(export declare const setTitle: [^`]*)`/.exec(m2)?.[1]; + writeFileSync(path.join(td, "page.js"), "export const setTitle = (v) => { document.title = v }\n"); writeFileSync(path.join(td, "page.d.ts"), `${dts}\n`); + writeFileSync(path.join(td, "main.rx"), 'import { setTitle } from "./page.js"\n' + tpl.replace("document.title = `${$0} laps`", "setTitle(`${$0} laps`)")); + writeFileSync(path.join(td, "tsconfig.json"), (await import("./pasted-cases.mjs")).TSCONFIG_TEXT); + const t = spawnSync(process.execPath, [path.join(repo, "tooling/rx-language-server/bin/tsc.js"), "-p", "."], { cwd: td, encoding: "utf8", timeout: 300000 }); + check("…the helper, its `.d.ts` line and the call pasted: rx-tsc clean (the README's tsconfig)", t.status === 0 && !/error/.test(`${t.stdout}${t.stderr}`), `${t.stdout}${t.stderr}`.slice(0, 600)); +} + +// (from round D2) a class made inline where its instance is not bound, `client={new QueryClient()}`: the message offered only +// `pure`, false of a client that keeps a cache — it leads with `instantiates` and the binding now +{ + writeFileSync(path.join(dir, "kit.js"), "export class QueryClient { constructor() { this.cache = new Map() } }\nexport const Provider = (p) => p.children\n"); + writeFileSync(path.join(dir, "kit.d.rx"), "export class QueryClient(config?: any): { cache: any }\nexport component Provider(props: { client: any; children: any })\n"); + const src = 'import { QueryClient, Provider } from "./kit.js"\nexport default component App() {\n

    x

    \n}\n'; + const r = refused("a class made inline in a prop, its row saying nothing: `instantiates` and the binding, first", src, "IO_IN_REACTIVE", ["`instantiates` at the end of its row, `export class QueryClient(…) … instantiates`", "`queryClient = new QueryClient(…)`"]); + check("…and `pure` only for a value computed from its arguments", /where it only computes a value from its arguments \(a date, a URL\)/.test(msg(r)), show(r)); + writeFileSync(path.join(dir, "kit.d.rx"), "export class QueryClient(config?: any): { cache: any } instantiates\nexport component Provider(props: { client: any; children: any })\n"); + const f = accepted("…the row and the binding, pasted", src.replace(" ", " queryClient = new QueryClient()\n ")); + await run("…and runs", f, 0, ["x"]); +} + +// (from round D2's e02) `import pure` over a row a draft read `instantiates` from the code (a hook): a false word, refused +{ + const nm = path.join(dir, "node_modules"); mkdirSync(path.join(nm, "hooky"), { recursive: true }); mkdirSync(path.join(nm, ".rx-types"), { recursive: true }); + writeFileSync(path.join(nm, "hooky/package.json"), JSON.stringify({ name: "hooky", version: "1.0.0", type: "module", main: "index.js" })); + writeFileSync(path.join(nm, "hooky/index.js"), 'import { createSignal } from "solid-js"\nexport const useLabel = () => { const [s] = createSignal("hi"); return s }\n'); + writeFileSync(path.join(nm, ".rx-types/hooky.d.rx"), "//@ generated hooky@1.0.0 (MO-8l, draft 27, types 0): drafted from hooky's TypeScript types\nexport fn useLabel(): ref string instantiates\n"); + const src = 'import pure { useLabel } from "hooky"\nexport default component App() {\n label = useLabel()\n

    {label}

    \n}\n'; + refused("`import pure` over a draft's `instantiates` row (a hook)", src, "IMPORT_ROW_MISMATCH", ['`import { useLabel } from "hooky"`']); + const f = accepted("…the import without the word, pasted", src.replace("import pure {", "import {")); + await run("…and runs", f, 0, ["hi"]); +} + +console.log(`\n${pass} passed, ${fail} failed`); +process.exit(fail ? 1 : 0); diff --git a/compiler/test/js-host.mjs b/compiler/test/js-host.mjs new file mode 100644 index 000000000..0960b4d5f --- /dev/null +++ b/compiler/test/js-host.mjs @@ -0,0 +1,276 @@ +// A compiled package under a JavaScript host (09 MO-13e), in Chromium and on the server: what the host's children print +// where the component reads them — by `props`, by a pattern, by a rest — and what a value prints beside them; a prop a +// `ref` closure reads is a snapshot (H-10: Solid's development build reports none); a name imported for its type alone is +// not imported when the module runs. A view a component shows (RG-4c), given by JavaScript: a function of one parameter, +// kept while what it is shown with changes; plain content and a thunk, where they are taken; one of another name; none. +// Needs what bench/run.mjs needs (the crate, the runtime's build, bench/.out/ws). node compiler/test/js-host.mjs +import { execFileSync, spawnSync } from "node:child_process"; +import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import path from "node:path"; +import { ws, repo, workspace } from "../../bench/harness.mjs"; +import { bundle } from "../../scripts/lib/bundle.mjs"; + +workspace(); +const dir = path.join(ws, "js-host"); rmSync(dir, { recursive: true, force: true }); mkdirSync(dir, { recursive: true }); +const rxc = process.env.RXC ?? path.join(repo, `compiler/target/${process.env.RX_PROFILE ?? "release"}/rxc`), req = createRequire(path.join(ws, "package.json")); +writeFileSync(path.join(dir, "types.js"), "export {};\n"); +writeFileSync(path.join(dir, "types.d.ts"), "export type T = { a: number };\nexport type N = { children: number };\n"); +writeFileSync(path.join(dir, "mid.js"), "export const Mid = p => globalThis.MID(p);\n"); +writeFileSync(path.join(dir, "mid.d.rx"), "export component Mid(props: { children?: View })\n"); +writeFileSync(path.join(dir, "kit.rx"), `import { T } from "./types.js" +import { Mid } from "./mid.js" +export component View1(props: { children: (s: { on: boolean }) => View }) { + source lit := false +

    { lit := !lit }}>

    +} +export component Mixed(props: { children?: View | ((s: { on: boolean }) => View); cell?: (s: { k: string }) => View }) { + source lit := false +

    { lit := !lit }}>{if props.cell { }}

    +} +export component Direct(props: { children?: View, n?: number }) { + {props.children} +} +export component Pattern({ children, n }: { children?: View, n?: number }) { + {children} +} +export component Rest(props: { children?: View, n?: number }) { + { n, ...rest } = props + {rest.children} +} +export component Value(props: { n?: number }) { + x: T = { a: 1 } + {props.n} {x.a} +} +export component Asked(props: { children?: View }) { + {if props.children { yes } else { no }} +} +export component Some(props: { children?: View }) { + {props.children != undefined ? "yes" : "no"} +} +export component Count(p: import("./types.js").N) { + {p.children ? "yes" : "no"} +} +export component Field(p: { label?: View }) { + +} +export component Inner(p: { children: View }) { + {p.children} +} +export component Card(p: { t?: string }) { + {p.t ?? "hi"} +} +export component Gives() { + given +} +export component Ref(props: { f: (e: Element) => void }) { +

    { props.f(e) }}>x

    +} +`); +for (const target of ["dom", "ssr"]) { + const app = JSON.parse(execFileSync(rxc, ["app", path.join(dir, "kit.rx"), "--lib", "--target", target], { encoding: "utf8", maxBuffer: 1 << 26 })); + if (!app.modules) { console.error(JSON.stringify(app).slice(0, 2000)); process.exit(1); } + for (const m of Object.values(app.modules)) writeFileSync(path.join(dir, `kit.${target}.mjs`), m.code); +} +let fail = 0; const check = (name, ok, got) => { if (!ok) fail++; console.log(`${ok ? "✓" : "✗"} ${name}${ok ? "" : `\n ${JSON.stringify(got)}`}`); }; +const CASES = [["none"], ["undefined", undefined, ""], ["null", null, ""], ["false", false, ""], ["true", true, ""], ["text", "a", "a"], ["a number", 0, "0"], ["a list of text", ["a", "b"], "ab"], ["text and a number", ["a", 1], "a1"], ["a function", "fn", "f"]]; +writeFileSync(path.join(dir, "cases.mjs"), `import { createComponent } from "solid-js"; +const CASES = ${JSON.stringify(CASES.map(([n, v]) => [n, v === undefined ? "undefined" : v]))}; +export const views = lib => ["Direct", "Pattern", "Rest"].flatMap(C => CASES.map(([n, v]) => () => createComponent(lib[C], n === "none" ? {} : { children: n === "undefined" ? undefined : n === "a function" ? () => "f" : v }))); +`); +const want = ["Direct", "Pattern", "Rest"].flatMap(() => CASES.map(([, , w]) => w ?? "")); +// (the scripts are Rolldown's, scripts/lib/bundle.mjs: a module's text, the folder it stands in, the conditions it is resolved with) +const build = async o => ({ outputFiles: [{ text: await bundle(ws, { dir: o.stdin.resolveDir, conditions: o.conditions, code: o.stdin.contents }) }] }); +const r = await build({ stdin: { resolveDir: dir, contents: `import kit from "./kit.dom.mjs"; import { views } from "./cases.mjs"; import { library } from "@reactivescript/runtime"; import { createSignal, createComponent } from "solid-js"; import { render } from "@solidjs/web"; +const lib = library(kit, "kit/kit"); window.shown = views(lib).map(v => { const at = document.createElement("div"); render(v, at); return at.textContent; }); +const at = document.createElement("div"); render(() => createComponent(lib.Value, {}), at); window.value = at.textContent; +const [g] = createSignal(1); window.seen = 0; render(() => createComponent(lib.Ref, { get f() { g(); return () => { window.seen++; }; } }), document.createElement("div"));` }, bundle: true, write: false, format: "esm", conditions: ["browser", "development"], logLevel: "error" }); +const views = await build({ stdin: { resolveDir: dir, contents: `import kit from "./kit.dom.mjs"; import { library } from "@reactivescript/runtime"; import { createSignal, createComponent, merge, flush } from "solid-js"; import { render } from "@solidjs/web"; +const lib = library(kit, "kit/kit"); let made = 0; const el = t => { made++; const b = document.createElement("b"); b.textContent = t; return b; }; +const b1 = s => { const b = el(""); const i = document.createElement("i"); b.append(i); Object.defineProperty(b, "s", { value: s }); return [b, () => s.on ? "on" : "off"]; }; +const at = () => { const d = document.createElement("div"); document.body.append(d); return d; }; const out = window.views = []; +const run = (C, props, n = 2) => { const d = at(); made = 0; const end = render(() => createComponent(lib[C], props), d); const seen = [d.textContent]; for (let i = 0; i < n; i++) { d.querySelector("p").click(); flush(); seen.push(d.textContent); } out.push([seen.join(" "), made]); end(); out[out.length - 1].push(d.textContent); }; +run("View1", { children: b1 }); run("View1", merge({}, { children: b1 })); run("Mixed", { children: b1 }); run("Mixed", { get children() { return el("plain"); } }); run("Mixed", { children: () => "thunk" }); run("Mixed", { children: ["a", 1, "b"] }); run("Mixed", {}); run("Mixed", { children: undefined, cell: s => s.k }); run("Mixed", { cell: s => [s.k, "!"], children: b1 }); run("View1", { children: (s = {}) => b1(s) }); run("View1", { children: (...a) => b1(a[0]) }); run("View1", { children: () => el("none") }); +const [f, set] = createSignal(() => b1); const d = at(); render(() => createComponent(lib.Mixed, { get children() { return f(); } }), d); const before = d.textContent; set(() => s => [() => s.on ? "ON" : "OFF"]); flush(); const mid = d.textContent; set("text"); flush(); out.push([before, mid, d.textContent]);` }, bundle: true, write: false, format: "esm", conditions: ["browser", "development"], logLevel: "error" }); +const browser = await req("playwright").chromium.launch(); const page = await browser.newPage(); const said = []; +page.on("console", m => { if (m.type() !== "log") said.push(m.text().split("\n")[0]); }); page.on("pageerror", e => said.push(e.message)); +await page.setContent("

    "); await page.addScriptTag({ type: "module", content: r.outputFiles[0].text }); await page.waitForTimeout(100); +const got = await page.evaluate(() => [window.shown, window.value, window.seen]); +check("children of a JavaScript host, in the browser", JSON.stringify(got[0]) === JSON.stringify(want), [got[0], want]); +check("a value prints as it did, beside a name imported for its type (`undefined` as nothing, as JSX has it: 11 `show`)", got[1] === " 1", got[1]); +check("a `ref` closure's read of a prop is a snapshot", got[2] === 1 && !said.some(s => /STRICT_READ/.test(s)), [got[2], said]); +{ + const page = await browser.newPage(); const said = []; page.on("console", m => { if (m.type() !== "log") said.push(m.text().split("\n")[0]); }); page.on("pageerror", e => said.push(e.message)); + await page.setContent("

    "); await page.addScriptTag({ type: "module", content: views.outputFiles[0].text }); await page.waitForTimeout(100); + const got = await page.evaluate(() => window.views); + const want = [["off on off", 1, ""], ["off on off", 1, ""], ["off on off", 1, ""], ["plain plain plain", 1, ""], ["thunk thunk thunk", 0, ""], ["a1b a1b a1b", 0, ""], [" ", 0, ""], ["c c c", 0, ""], ["c!off c!on c!off", 1, ""], ["off on off", 1, ""], ["off on off", 1, ""], ["none none none", 1, ""], ["off", "OFF", "text"]]; + check("a view given by a JavaScript host (RG-4c)", JSON.stringify(got) === JSON.stringify(want) && !said.length, [got, want, said]); +} +// RG-4c: whether a view was given, asked of what JavaScript gives. A value answers as JavaScript does (Solid's +// `props.children ? … : …`): undefined, null, false, 0, "" are nothing given, [] is; `!= undefined` asks only that. A getter +// (JSX content) is read, as Solid reads it, and what it answers is asked (so it is made once to answer: `made`); a host +// that would rather not offers `slot`, which is not made. Children whose type says a number are a number: ordinary truth, +// read. +const ASKED = `const count = () => { window.made = (window.made ?? 0) + 1; }; +const G = () => ({ get children() { count(); return "g"; } }); +const S = () => ({ get children() { return slot(() => { count(); return "s"; }); } }); +const GIVEN = [["none", {}], ["undefined", { children: undefined }], ["null", { children: null }], ["false", { children: false }], ["0", { children: 0 }], ["empty text", { children: "" }], ["[]", { children: [] }], ["text", { children: "t" }], ["a getter", G()], ["a slot", S()], ["a slot handed on", merge({ n: 1 }, S())]]; +export const asked = (lib, text) => [["Asked", "Some"].map(C => GIVEN.map(([, p]) => text(() => createComponent(lib[C], p))).join(" ")), [{ children: 0 }, { children: 1 }, { get children() { return 0; } }].map(p => text(() => createComponent(lib.Count, p))).join(" ")];`; +const wantAsked = [["no no no no no no yes yes yes yes yes", "no no yes yes yes yes yes yes yes yes yes"], "no yes no"]; // (`!= undefined` of `null`: yes — the language's `!=` is strict) +writeFileSync(path.join(dir, "asked.mjs"), `import { createComponent, merge } from "solid-js";\nimport { slot } from "@reactivescript/runtime";\nglobalThis.window ??= globalThis;\n${ASKED}\n`); +{ + const b = await build({ stdin: { resolveDir: dir, contents: `import kit from "./kit.dom.mjs"; import { asked } from "./asked.mjs"; import { library } from "@reactivescript/runtime"; import { render } from "@solidjs/web"; +const lib = library(kit, "kit/kit"); window.asked = asked(lib, v => { const at = document.createElement("div"); render(v, at); return at.textContent; });` }, bundle: true, write: false, format: "esm", conditions: ["browser", "production"], minify: true, define: { "process.env.NODE_ENV": '"production"' }, logLevel: "error" }); + const page = await browser.newPage(); const said = []; page.on("console", m => { if (m.type() !== "log") said.push(m.text().split("\n")[0]); }); page.on("pageerror", e => said.push(e.message)); + await page.setContent("

    "); await page.addScriptTag({ type: "module", content: b.outputFiles[0].text }); await page.waitForTimeout(100); + const got = await page.evaluate(() => [window.asked, window.made ?? 0]); + check("whether a view was given, asked of a JavaScript host (RG-4c): production, in the browser", JSON.stringify(got) === JSON.stringify([wantAsked, 2]) && !said.length, [got, wantAsked, said]); +} +await browser.close(); +{ + writeFileSync(path.join(dir, "asked-server.mjs"), `import kit from "./kit.ssr.mjs"; import { asked } from "./asked.mjs"; import { library } from "@reactivescript/runtime"; import { renderToString } from "@solidjs/web"; +const lib = library(kit, "kit/kit"); console.log(JSON.stringify([asked(lib, v => renderToString(v).replace(/|<[^>]*>/g, "")), globalThis.made ?? 0]));`); + const s = spawnSync(process.execPath, ["asked-server.mjs"], { cwd: dir, encoding: "utf8", timeout: 60000 }); + const got = s.status === 0 ? JSON.parse(s.stdout.trim().split("\n").pop()) : []; + check("whether a view was given, asked of a JavaScript host (RG-4c): on the server", JSON.stringify(got) === JSON.stringify([wantAsked, 2]), [got, s.stderr.slice(-600)]); +} +// RG-4c: what JavaScript keeps of what it read while it was asked. A view that is asked for is not made, and JavaScript +// between the one that gives and the one that asks may keep what it read then (`cached ??= props.children`, a getter that +// makes once): what it holds is the view's maker — a function, which Solid shows as it shows any child that is one — so +// what it shows later is the view, not the nothing an answer was made of. In the browser (both builds), on the server, +// and where the browser takes over what the server made. +const KEPT = `const C = createComponent, once = f => { let c, d = false; return () => d ? c : (d = true, c = f()); }; +const giv = (L, f) => () => { globalThis.MID = f; return C(L.Gives, {}); }; +export const kept = L => ({ + "a getter that makes a component once": () => { const o = once(() => C(L.Card, {})); return C(L.Field, { get label() { return o(); } }); }, + "icon ??= ": () => { let icon; return C(L.Field, { get label() { return icon ??= C(L.Card, { t: "hi" }); } }); }, + "this.k ??= props.children": giv(L, p => C(L.Field, { k: undefined, get label() { return this.k ??= p.children; } })), + "children read once": giv(L, p => { const o = once(() => p.children); return C(L.Field, { get label() { return o(); } }); }), + "a component with them, made once": giv(L, p => { const o = once(() => C(L.Inner, { get children() { return p.children; } })); return C(L.Field, { get label() { return o(); } }); }), + "children whose length is read": giv(L, p => C(L.Field, { get label() { const c = p.children; return Array.isArray(c) && c.length === 0 ? undefined : c; } })), + "children in a memo": giv(L, p => { const m = createMemo(() => p.children); return C(L.Field, { get label() { return m(); } }); }), + "children handed on": giv(L, p => C(L.Field, { get label() { return p.children; } })), +});`; +const wantKept = ["Yhi", "Yhi", "Ygiven", "Ygiven", "Ygiven", "Ygiven", "Ygiven", "Ygiven"]; +writeFileSync(path.join(dir, "kept.mjs"), `import { createComponent, createMemo } from "solid-js";\nglobalThis.window ??= globalThis;\n${KEPT}\n`); +{ + writeFileSync(path.join(dir, "kept-server.mjs"), `import kit from "./kit.ssr.mjs"; import { kept } from "./kept.mjs"; import { library } from "@reactivescript/runtime"; import { renderToString, generateHydrationScript } from "@solidjs/web"; +const lib = library(kit, "kit/kit"); console.log(JSON.stringify([generateHydrationScript(), Object.values(kept(lib)).map(v => renderToString(v))]));`); + const out = spawnSync(process.execPath, ["kept-server.mjs"], { cwd: dir, encoding: "utf8", timeout: 60000 }); + const [script, html] = out.status === 0 ? JSON.parse(out.stdout.trim().split("\n").pop()) : ["", []]; + check("what JavaScript kept of a view it read while asked (RG-4c): on the server", JSON.stringify(html.map(h => h.replace(/|<[^>]*>/g, ""))) === JSON.stringify(wantKept), [html, out.stderr.slice(-600)]); + const browser = await req("playwright").chromium.launch(); + for (const mode of ["development", "production"]) { + const r = await build({ stdin: { resolveDir: dir, contents: `import kit from "./kit.dom.mjs"; import { kept } from "./kept.mjs"; import { library } from "@reactivescript/runtime"; import { flush } from "solid-js"; import { render, hydrate } from "@solidjs/web"; +const lib = library(kit, "kit/kit"); window.kept = Object.values(kept(lib)).map(v => { const at = document.createElement("div"); render(v, at); flush(); return at.textContent; }); +const i = Number(document.body.dataset.i); if (i >= 0) { const at = document.getElementById("app"), was = at.querySelector("s"); hydrate(Object.values(kept(lib))[i], at); flush(); window.hydrated = [at.textContent, was === at.querySelector("s")]; }` }, bundle: true, write: false, format: "esm", conditions: ["browser", mode], define: { "process.env.NODE_ENV": JSON.stringify(mode) }, minify: mode === "production", logLevel: "error" }); + const open = async body => { const page = await browser.newPage(); const said = []; page.on("console", m => { if (m.type() !== "log") said.push(m.text().split("\n")[0]); }); page.on("pageerror", e => said.push(e.message)); await page.setContent(body); await page.addScriptTag({ type: "module", content: r.outputFiles[0].text }); await page.waitForTimeout(100); const got = await page.evaluate(() => [window.kept, window.hydrated]); await page.close(); return [got, said]; }; + const [[shown], said] = await open(`

    `); + check(`what JavaScript kept of a view it read while asked (RG-4c): ${mode}, in the browser`, JSON.stringify(shown) === JSON.stringify(wantKept) && !said.length, [shown, said]); + const taken = [], notes = []; + for (let i = 0; i < wantKept.length; i++) { const [[, h], said] = await open(`${script}
    ${html[i]}
    `); taken.push(h); notes.push(...said); } + check(`what JavaScript kept of a view it read while asked (RG-4c): ${mode}, taken over from the server`, JSON.stringify(taken) === JSON.stringify(wantKept.map(w => [w, true])) && !notes.length, [taken, notes]); + } + await browser.close(); +} +writeFileSync(path.join(dir, "server.mjs"), `import kit from "./kit.ssr.mjs"; import { views } from "./cases.mjs"; import { library } from "@reactivescript/runtime"; import { createComponent } from "solid-js"; import { renderToString } from "@solidjs/web"; +const lib = library(kit, "kit/kit"); const text = v => renderToString(v).replace(/|<[^>]*>/g, ""); +console.log(JSON.stringify([views(lib).map(text), text(() => createComponent(lib.Value, {}))]));`); +const s = spawnSync(process.execPath, ["server.mjs"], { cwd: dir, encoding: "utf8", timeout: 60000 }); +const [shown, value] = s.status === 0 ? JSON.parse(s.stdout.trim().split("\n").pop()) : []; +check("children of a JavaScript host, on the server", JSON.stringify(shown) === JSON.stringify(want) && value === " 1", [shown, want, value, s.stderr.slice(-600)]); +// a view given to a JavaScript component that provides (RG-7a): its context is for what is in it, in the browser, on the +// server and where the browser takes over what the server made +{ + writeFileSync(path.join(dir, "v.d.rx"), "export component V(props: { after: Component; children: (x: string) => View })\n"); + writeFileSync(path.join(dir, "v.js"), `import { children, createComponent } from "solid-js";\nexport const V = p => children(() => [p.children("a"), p.children("b"), createComponent(p.after, {})]);\n`); + writeFileSync(path.join(dir, "views.rx"), `import { V } from "./v.js" +context c: string = "o" +component R() { + {use c} +} +export component Two() { + source n := 1 +

    { n := v => v + 1 }}>{view (x) { + provide c = x + {n} + {if n > 1 { }} + }}

    +} +`); + for (const target of ["dom", "ssr"]) for (const m of Object.values(JSON.parse(execFileSync(rxc, ["app", path.join(dir, "views.rx"), "--lib", "--target", target], { encoding: "utf8" })).modules)) writeFileSync(path.join(dir, `views.${target}.mjs`), m.code); + writeFileSync(path.join(dir, "views-server.mjs"), `import kit from "./views.ssr.mjs"; import { library } from "@reactivescript/runtime"; import { createComponent } from "solid-js"; import { renderToString, generateHydrationScript } from "@solidjs/web"; +console.log(JSON.stringify([generateHydrationScript(), renderToString(() => createComponent(library(kit, "kit/views").Two, {}))]));`); + const out = spawnSync(process.execPath, ["views-server.mjs"], { cwd: dir, encoding: "utf8", timeout: 60000 }); + const [script, html] = out.status === 0 ? JSON.parse(out.stdout.trim().split("\n").pop()) : ["", ""]; + const browser = await req("playwright").chromium.launch(); + for (const mode of ["development", "production"]) for (const how of ["render", "hydrate"]) { + const r = await build({ stdin: { resolveDir: dir, contents: `import kit from "./views.dom.mjs"; import { library } from "@reactivescript/runtime"; import { createComponent, flush } from "solid-js"; import { render, hydrate } from "@solidjs/web"; +const at = document.getElementById("app"), first = at.querySelector("b"), seen = []; const end = ${how}(() => createComponent(library(kit, "kit/views").Two, {}), at); flush(); seen.push(at.textContent); +at.querySelector("p").click(); flush(); seen.push(at.textContent, ${how === "hydrate" ? `first === at.querySelector("b")` : "true"}); end(); window.seen = seen;` }, bundle: true, write: false, format: "esm", conditions: ["browser", mode], logLevel: "error" }); + const page = await browser.newPage(); const said = []; page.on("console", m => { if (m.type() !== "log") said.push(m.text().split("\n")[0]); }); page.on("pageerror", e => said.push(e.message)); + await page.setContent(`${script}
    ${how === "hydrate" ? html : ""}
    `); await page.addScriptTag({ type: "module", content: r.outputFiles[0].text }); await page.waitForTimeout(100); + const got = await page.evaluate(() => window.seen); + check(`a view that provides, given to JavaScript (RG-7a): ${how}, ${mode}`, JSON.stringify(got) === JSON.stringify(["a1b1o", "a2ab2bo", true]) && !said.length, [got, said, html, out.stderr.slice(-400)]); + await page.close(); + } + await browser.close(); +} +// rx-lib ships the modules a package imports for their types alone: with no row, with one, and where there are only types +{ + const pkg = path.join(dir, "pkg"); mkdirSync(path.join(pkg, "src"), { recursive: true }); + const put = (name, text) => writeFileSync(path.join(pkg, name), text); + put("package.json", JSON.stringify({ name: "kit", type: "module", peerDependencies: { "solid-js": "^2.0.0", "@solidjs/web": "^2.0.0", "@reactivescript/runtime": "*" } })); + put("src/bare.js", "export {};\n"); put("src/bare.d.ts", `import type { Deep } from "./deep.js";\nexport type Bare = { deep: Deep };\n`); + put("src/deep.d.ts", "export type Deep = number;\n"); + put("src/rows.js", "export {};\n"); put("src/rows.d.ts", "export type Row = { a: string };\n"); put("src/rows.d.rx", "export type Row = { a: string }\n"); + put("src/index.rx", `import { Bare } from "./bare.js"\nimport { Row } from "./rows.js"\nexport component A(props: { b: Bare, r: Row }) {\n {props.b.deep}{props.r.a}\n}\n`); + process.env.RXC = rxc; process.env.RX_TSC = path.join(repo, "tooling/rx-language-server/bin/tsc.js"); + const b = (await import("../lib.mjs")).build(pkg, { write: true }); + const missing = ["bare.d.ts", "bare.js", "deep.d.ts", "rows.d.ts", "rows.d.rx"].filter(x => !existsSync(path.join(pkg, "dist", x))); + check("rx-lib ships what a package imports for its types alone", b.ok && !missing.length, [b.problems, missing]); +} +// MO-10f (2026-11-28): a result read by its parts, whose `ref` part is a value to `.rx`, is the library's own object where it +// is handed whole to JavaScript — a JS fn's argument, inside a record given to one, a JS component's prop — and a method +// of it keeps its `this`, called on the name or read through the `.rx` view (`[picker][0].label()`). The view was handed +// over (`p.files is not a function`, found by the review of 25a35680) and `lazy` read a method off the object unbound +// (`n=undefined`). On the server and in the browser. +{ + writeFileSync(path.join(dir, "acc.js"), `import { createSignal } from "solid-js"; +class Picker { constructor() { const [f] = createSignal(["a.png"]); this.files = f; this.n = 5; } label() { return "n=" + this.n; } } +export function createPicker() { return new Picker(); } +export function describe(p) { return p.files().length + " via helper"; } +export function nested(o) { return o.p.files()[0]; } +export const Shown = props => () => props.p.files().join(","); +`); + writeFileSync(path.join(dir, "acc.d.rx"), `export fn createPicker(): { files: ref string[]; label: () => string } instantiates +export pure fn describe(p: { files: () => string[] }): string +export pure fn nested(o: { p: { files: () => string[] } }): string +export component Shown(props: { p: { files: () => string[] } }) +`); + writeFileSync(path.join(dir, "parts.rx"), `import { createPicker, describe, nested, Shown } from "./acc.js" +export component Parts() { + picker = createPicker() +

    {picker.files.length}|{describe(picker)}|{nested({ p: picker })}|{picker.label()}|{[picker][0].label()}|

    +} +`); + for (const target of ["dom", "ssr"]) for (const m of Object.values(JSON.parse(execFileSync(rxc, ["app", path.join(dir, "parts.rx"), "--lib", "--target", target], { encoding: "utf8" })).modules)) writeFileSync(path.join(dir, `parts.${target}.mjs`), m.code); + const want = "1|1 via helper|a.png|n=5|n=5|a.png"; + writeFileSync(path.join(dir, "parts-server.mjs"), `import kit from "./parts.ssr.mjs"; import { library } from "@reactivescript/runtime"; import { createComponent } from "solid-js"; import { renderToString } from "@solidjs/web"; +console.log(renderToString(() => createComponent(library(kit, "kit/parts").Parts, {})).replace(/|<[^>]*>/g, ""));`); + const out = spawnSync(process.execPath, ["parts-server.mjs"], { cwd: dir, encoding: "utf8", timeout: 60000 }); + check("a result read by its parts, handed whole to JavaScript (MO-10f): on the server", out.stdout.trim() === want, [out.stdout.trim(), out.stderr.slice(-600)]); + const browser = await req("playwright").chromium.launch(); + for (const mode of ["development", "production"]) { + const r = await build({ stdin: { resolveDir: dir, contents: `import kit from "./parts.dom.mjs"; import { library } from "@reactivescript/runtime"; import { createComponent, flush } from "solid-js"; import { render } from "@solidjs/web"; +const at = document.createElement("div"); render(() => createComponent(library(kit, "kit/parts").Parts, {}), at); flush(); window.parts = at.textContent;` }, bundle: true, write: false, format: "esm", conditions: ["browser", mode] }); + const page = await browser.newPage(); const said = []; page.on("console", m => { if (m.type() !== "log") said.push(m.text().split("\n")[0]); }); page.on("pageerror", e => said.push(e.message)); + await page.setContent("

    "); await page.addScriptTag({ type: "module", content: r.outputFiles[0].text }); await page.waitForTimeout(100); + const got = await page.evaluate(() => window.parts); + check(`a result read by its parts, handed whole to JavaScript (MO-10f): ${mode}, in the browser`, got === want && !said.length, [got, said]); + await page.close(); + } + await browser.close(); +} +console.log(fail ? `${fail} failed` : "ok"); +process.exit(fail ? 1 : 0); diff --git a/compiler/test/leaks.mjs b/compiler/test/leaks.mjs new file mode 100644 index 000000000..d418558d0 --- /dev/null +++ b/compiler/test/leaks.mjs @@ -0,0 +1,142 @@ +// What unmounted is collected (11 CP-4c: an app keeps no table of its bindings): a page opens and closes a part many +// times, and each value and element the part made, held through a WeakRef, is gone after a collection — for a component, +// a `for` row, an `if` branch, an instantiation, an effect, a context, an action, a question, a store, a package's +// component rendered by a JavaScript host. On the server, an app and what it made are gone once its stream has ended. +// Needs what bench/run.mjs needs (the crate, the runtime's build, bench/.out/ws). node compiler/test/leaks.mjs +import { execFileSync, spawnSync } from "node:child_process"; +import { mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import path from "node:path"; +import { ws, repo, workspace } from "../../bench/harness.mjs"; +import { bundle } from "../../scripts/lib/bundle.mjs"; + +workspace(); +const dir = path.join(ws, "leaks"); rmSync(dir, { recursive: true, force: true }); mkdirSync(dir, { recursive: true }); +const rxc = process.env.RXC ?? path.join(repo, `compiler/target/${process.env.RX_PROFILE ?? "release"}/rxc`); +const req = createRequire(path.join(ws, "package.json")); +writeFileSync(path.join(dir, "lib.d.rx"), `export pure fn make(kind: string): { text: string }\nexport fn keep(kind: string, x: any): void\nexport pure fn ask(kind: string): Promise<{ text: string }>\n`); +writeFileSync(path.join(dir, "lib.js"), `const made = globalThis.made ??= {}; +export const keep = (kind, x) => { (made[kind] ??= []).push(new WeakRef(x)); }; +export const make = kind => { const o = { text: kind, big: new Array(1000).fill(0) }; keep(kind, o); return o; }; +export const ask = kind => Promise.resolve().then(() => make(kind)); +`); +const part = `import { make, keep, ask } from "./lib.js" +context theme: { text: string } +fn useMade(ref on: boolean) { + inside = on ? make("instantiation") : make("instantiation off") + inside +} +component Leaf() { + t = use theme + {t.text} +} +component Shows(props: { rows: any[]; cell: (s: { row: any }) => View; children?: View | ((s: { on: boolean }) => View) }) { + source lit := false +
    { lit := !lit }}>{for r in props.rows { }}
    +} +export component Part() { + x = make("component") + source s := make("source") + source list := [make("store")] + q = await ask("question") catch (e) => ({ text: "failed" }) + source on := true + u = useMade(on) + rows = [make("row value"), make("row value")] + provide theme = make("context") + effect (s) { keep("effect input", $0) } + action save() { let m = make("action"); list := [m]; keep("action local", m) } +
    { keep("element", e) }} onClick={() => { save() }}> + {x.text} {s.text} {list.length} {u.text} + {for r in rows { y = make("row"); { keep("row element", e) }}>{r.text}{y.text} }} + {if on { z = make("branch");

    {z.text}

    }} + {loading fallback {

    wait

    } {

    {q.text}

    }} + + + {view cell (s) { c = make("named view"); { keep("named view element", e) }}>{s.row.text}{c.text} }} + {view (s) { v = make("view"); source held := make("view source"); { keep("view element", e) }}>{v.text}{held.text}{s.on ? "on" : "off"} }} + + {view cell () { }}{(use theme).text} +
    +} +`; +writeFileSync(path.join(dir, "part.rx"), part); +writeFileSync(path.join(dir, "main.rx"), `import { make } from "./lib.js" +import { Part } from "./part.rx" +context kind: { text: string } +export default component App() { + source open := false + + {if open { provide kind = make("branch context"); }} +} +`); +const compile = target => { + const app = JSON.parse(execFileSync(rxc, ["app", path.join(dir, "main.rx"), "--target", target], { encoding: "utf8", maxBuffer: 1 << 26 })); + if (!app.modules) { console.error(JSON.stringify(app).slice(0, 2000)); process.exit(1); } + for (const [p, m] of Object.entries(app.modules)) writeFileSync(path.join(dir, `${path.basename(p)}.${target}.mjs`), m.code.replace(/from "(\.\/[^"]+\.rx)"/g, `from "$1.${target}.mjs"`)); +}; +compile("dom"); compile("ssr"); +let fail = 0; const check = (name, ok, got) => { if (!ok) fail++; console.log(`${ok ? "✓" : "✗"} ${name}${ok ? "" : `\n ${JSON.stringify(got)}`}`); }; +const N = 20, KINDS = 19; +const alive = ([what, made]) => { + // the last part mounted may be held by the engine's own caches (an event's target): one is not a leak, N are + const kinds = Object.entries(made).filter(([, [of]]) => of >= N), kept = kinds.filter(([, [, left]]) => left > 2); + check(`${what}: ${N} mounted and unmounted, ${kinds.length} kinds of value made, all collected`, kinds.length >= KINDS && !kept.length, { kinds: kinds.map(([k]) => k), kept }); +}; + +const count = () => Object.fromEntries(Object.entries(globalThis.made).map(([k, rs]) => [k, [rs.length, rs.filter(r => r.deref()).length]])); +const pages = [ + ["an app", "production", `import main from "./main.rx.dom.mjs"; import { createApp } from "@reactivescript/runtime"; const app = createApp({ root: document.getElementById("app") }); app.mount(main(app));`], + ["an app, Solid's development build", "development", `import main from "./main.rx.dom.mjs"; import { createApp } from "@reactivescript/runtime"; const app = createApp({ root: document.getElementById("app") }); app.mount(main(app));`], + ["a package's component in a JavaScript host", "production", `import part from "./part.rx.dom.mjs"; import { library } from "@reactivescript/runtime"; import { createSignal, createComponent, Show } from "solid-js"; import { render } from "@solidjs/web"; +const { Part } = library(part, "kit/part"); const [open, setOpen] = createSignal(false); const t = document.createElement("button"); t.id = "t"; t.onclick = () => setOpen(o => !o); document.body.append(t); +render(() => createComponent(Show, { get when() { return open(); }, get children() { return createComponent(Part, {}); } }), document.getElementById("app"));`], +]; +const browser = await req("playwright").chromium.launch(); +for (const [what, mode, contents] of pages) { + const r = await bundle(ws, { code: contents, dir, conditions: ["browser", mode] }); + const page = await browser.newPage(); const errors = []; page.on("pageerror", e => errors.push(e.message)); + // What is let go must not wait for a timer: a development build's re-ask audit (09 MO-15d) held what each unmounted + // part's equations and calls rested on until its next pass (50 ms to 1 s later); on a fast machine a pass ran during + // the collections below and the test passed, on GitHub's it did not (370e6003 → this). So the page's timers of 50 ms + // or more never fire (the turns below are 5 ms), and the collections are made at once, the moment the last part is gone. + await page.addInitScript(() => { const st = setTimeout; globalThis.setTimeout = (f, ms, ...a) => (ms ?? 0) >= 50 ? 0 : st(f, ms, ...a); globalThis.setInterval = () => 0; }); + await page.setContent(`
    `); await page.addScriptTag({ type: "module", content: r }); + await page.evaluate(async n => { + const turn = () => new Promise(r => setTimeout(r, 5)); + for (let i = 0; i < n; i++) { document.getElementById("t").click(); await turn(); document.querySelector("section").click(); await turn(); document.getElementById("t").click(); await turn(); } + }, N); + const cdp = await page.context().newCDPSession(page); + for (let i = 0; i < 5; i++) await cdp.send("HeapProfiler.collectGarbage"); + if (errors.length) check(what, false, errors); else alive([what, await page.evaluate(count)]); + await page.close(); +} +// SF-2b: a server fn asked in reactive scope is one request per arguments while it stands, and no longer +{ + const r = await bundle(ws, { dir, conditions: ["browser", "production"], code: `import { createApp, serverRef } from "@reactivescript/runtime"; import { createRoot, createSignal, createMemo, createEffect, flush } from "solid-js"; +const app = createApp({ root: null }); let asked = 0; const load = serverRef(app, "load", async n => { asked++; return "r" + n; }); +window.run = async () => createRoot(async dispose => { const [n, set] = createSignal(0); const a = createMemo(() => load(n())), b = createMemo(() => load(n())); createEffect(() => [a(), b()], () => {}); + for (let i = 1; i <= 20; i++) { set(i); flush(); await new Promise(r => setTimeout(r, 5)); } const during = app.flights.size; dispose(); await new Promise(r => setTimeout(r, 5)); return [asked, during, app.flights.size]; });` }); + const page = await browser.newPage(); await page.setContent(""); await page.addScriptTag({ type: "module", content: r }); + const got = await page.evaluate(() => window.run()); + check("a server fn's answers: one request per arguments, kept while one asks", got[0] === 21 && got[1] === 1 && got[2] === 0, got); +} +await browser.close(); + +writeFileSync(path.join(dir, "server.mjs"), `import main from "./open.rx.ssr.mjs"; import { createApp } from "@reactivescript/runtime"; +const apps = []; let html = ""; +for (let i = 0; i < ${N}; i++) { const app = createApp({ request: new Request("http://x/") }); apps.push(new WeakRef(app)); html = ""; await new Promise(end => app.stream(main(app), { write: s => { html += s; }, end })); } +for (let i = 0; i < 5; i++) { await new Promise(r => setTimeout(r, 10)); gc(); } +globalThis.made.app = apps; +console.log(JSON.stringify([html, Object.fromEntries(Object.entries(globalThis.made).map(([k, rs]) => [k, [rs.length, rs.filter(r => r.deref()).length]]))])); +`); +writeFileSync(path.join(dir, "open.rx"), `import { Part } from "./part.rx"\nexport default component App() {\n \n}\n`); +{ + const app = JSON.parse(execFileSync(rxc, ["app", path.join(dir, "open.rx"), "--target", "ssr"], { encoding: "utf8", maxBuffer: 1 << 26 })); + for (const [p, m] of Object.entries(app.modules)) writeFileSync(path.join(dir, `${path.basename(p)}.ssr.mjs`), m.code.replace(/from "(\.\/[^"]+\.rx)"/g, `from "$1.ssr.mjs"`)); + const r = spawnSync(process.execPath, ["--expose-gc", "server.mjs"], { cwd: dir, encoding: "utf8", timeout: 60000 }); + const [html, made] = r.status === 0 ? JSON.parse(r.stdout.trim().split("\n").pop()) : ["", {}]; + const kinds = Object.entries(made), kept = kinds.filter(([, [, left]]) => left > 2); + check(`the server: ${N} requests, ${kinds.length} kinds of value made, all collected`, /question/.test(html) && kinds.length >= 9 && !kept.length, { err: r.stderr.slice(-800), kinds, kept }); +} +console.log(fail ? `${fail} failed` : "ok"); +process.exit(fail ? 1 : 0); diff --git a/compiler/test/lending.mjs b/compiler/test/lending.mjs new file mode 100644 index 000000000..cbc07b9b3 --- /dev/null +++ b/compiler/test/lending.mjs @@ -0,0 +1,260 @@ +// 02 W-1a, MO-10i (re-check 10's D, 2026-12-05): a value of the program's state reaches JavaScript as a plain value, by +// every way it can get there — not only the ways a review found. Re-check 10's R10-2: `k = new Keeper(peek(items))` under +// `instantiates` handed the library the store itself, and what the library pushed into it later was dropped in production +// (each earlier round had found one way: a call, a method, a list written around a source, a JS fn reached as a value…). +// Here every way is a family, and each is given the three values a review uses: `peek(items)` (the source's value), +// `sorted` (an equation over it, whose rows are the store's) and `{ rows: items }` (a record written around it): +// call `probe(V)` · new `new Probe(V)` · method `box.probe(V)` · field `probe({ data: V })` · list element `probe([V])` +// · spread `probe(...V)` · a `.rx` context's value given to a call · instantiates, a fn's and a class's, where the +// component is made (`k = keepFn(V)`, `k = new Keeper(V)`) — and the library's later push into what it kept. +// In both of Solid's builds JavaScript is given a plain value (`structuredClone` of it succeeds: a store's proxy is not +// one); a change it makes in place is, in a development build, the guard's error naming the callee ("… changed what it +// was given"), and in production the source is as it was. +// Two ways are a reader, not a value, and stay what Solid gives (decided 2026-12-05, spec/02 W-1a *By origin*): a prop of a +// JavaScript component (and so a library provider's `value`) and what a `.rx` closure answers when JavaScript calls it. +// A component reads its props where it renders them and again when they change, and a fresh copy at each read would +// break what compares identity and give up per-key tracking; here the case asserts what plain Solid does with the same +// store: the live value, and a change in place Solid's own STORE_WRITE_OUTSIDE_SETTER in development, dropped in production. +// R10 (lending, step 1, 2026-12-01): what JavaScript is handed is a copy of its own, so in production a change it makes +// in place is in its copy — the store's data, read by the next thing that reads it raw (a lend, a clone, a save), is +// what the view shows. On eef62e69 the helper was handed the store's own objects there, and the change landed in them, +// unseen: the last section holds the reviews' four programs to it. +// LEND_TOOLS=
    runs another checkout's compiler and runtime (its bench/harness.mjs and workspace) over the same +// programs: the positive control (9330f456 fails the instantiates family; eef62e69 fails R10's production half). +// Needs what bench/run.mjs needs. node compiler/test/lending.mjs +import { mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import path from "node:path"; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const TOOLS = process.env.LEND_TOOLS ? path.resolve(process.env.LEND_TOOLS) : path.resolve(here, "../.."); +const { ws, workspace, both, Runner } = await import(pathToFileURL(path.join(TOOLS, "bench/harness.mjs")).href); +if (!process.env.LEND_TOOLS) workspace(); +const dir = path.join(ws, "lending"); rmSync(dir, { recursive: true, force: true }); mkdirSync(dir, { recursive: true }); +writeFileSync(path.join(dir, "lib.d.rx"), [ + "export fn probe(...xs: any[]): string", + "export fn grow(x: any): void", + "export class Probe(x: any): { said: string }", + "export class Grow(x: any): { said: string }", + "export pure fn makeBox(): { probe: (x: any) => string; grow: (x: any) => void }", + "export fn keepFn(x: any): { said: string; add: () => number } instantiates", + "export class Keeper(x: any): { said: string; add: () => number } instantiates", + "export fn growFn(x: any): { said: string } instantiates", + "export class Growing(x: any): { said: string } instantiates", + "export fn ask(get: () => any): string", + "export fn askGrow(get: () => any): string", + "export component Show(props: { value: any })", + "export component GrowShow(props: { value: any })", + "export context lib", + "export component LibProvider(props: { value: any; children?: View }) provides(lib)", + "export component Reader() uses(lib)", + "export fn addTo(o: { list: string[] }): void", + "export fn reverseIt(xs: string[]): number", + "export fn tagRow(r: { tags: string[] }): number", + "export fn shape(x: any): string", + "", +].join("\n")); +writeFileSync(path.join(dir, "lib.js"), ` +import { createContext, useContext, untrack } from "solid-js"; +// "ok" where every value is plain (structuredClone clones it), else the error's name (a store's proxy: DataCloneError) +export const probe = (...xs) => { try { structuredClone(xs); return "ok"; } catch (e) { return e.name; } }; +// a change in place of the first list it finds: a row's field, and a push +const rows = x => { if (Array.isArray(x) && x.length && x[0] && typeof x[0] === "object" && !Array.isArray(x[0]) && "n" in x[0]) return x; if (x && typeof x === "object") for (const v of Object.values(x)) { const f = rows(v); if (f) return f; } return undefined; }; +const first = x => rows(x) ?? x; +export const grow = x => { const a = first(x); if (a?.[0] && typeof a[0] === "object") a[0].n = 99; a?.push?.({ n: 7 }); }; +export class Probe { constructor(x) { this.said = probe(x); } } +export class Grow { constructor(x) { grow(x); this.said = "grown"; } } +export const makeBox = () => ({ probe: x => probe(x), grow: x => grow(x) }); +// what a library keeps of what it is given, and grows later (Fuse's \`add\`) +export const keepFn = x => { const kept = first(x); return { said: probe(x), add: () => (kept.push({ n: 5 }), kept.length) }; }; +export class Keeper { constructor(x) { this.kept = first(x); this.said = probe(x); } add() { this.kept.push({ n: 5 }); return this.kept.length; } } +export const growFn = x => { grow(x); return { said: "grown" }; }; +export class Growing { constructor(x) { grow(x); this.said = "grown"; } } +export const ask = get => probe(get()); +export const askGrow = get => { grow(get()); return "grown"; }; +const box = (cls, text) => { const el = document.createElement("i"); el.className = cls; el.textContent = text; return el; }; +export const Show = props => box("pv", probe(untrack(() => props.value))); +export const GrowShow = props => { grow(untrack(() => props.value)); return box("pv", "grown"); }; +const Lib = createContext(); +export const lib = Lib; +export const LibProvider = props => Lib({ get value() { return props.value; }, get children() { return props.children; } }); +export const Reader = () => box("cv", probe(useContext(Lib))); +// R10: helpers that change what they are given, and what the next lend holds +export const addTo = o => { o.list.push("x"); }; +export const reverseIt = xs => { xs.reverse(); return xs.length; }; +export const tagRow = r => { r.tags.push("x"); return r.tags.length; }; +export const shape = x => JSON.stringify(x); +`); +let pass = 0, fail = 0; +const results = []; +const check = (name, ok, got) => { ok ? pass++ : fail++; results.push({ name, ok }); console.log(`${ok ? "✓" : "✗"} ${name}${ok ? "" : `\n ${String(typeof got === "string" ? got : JSON.stringify(got)).slice(0, 900)}`}`); return ok; }; +const head = 'import { probe, grow, Probe, Grow, makeBox, keepFn, Keeper, growFn, Growing, ask, askGrow, Show, GrowShow, LibProvider, Reader, addTo, reverseIt, tagRow, shape } from "./lib.js"\n'; +let seq = 0; +const file = src => { const f = path.join(dir, `l${++seq}.rx`); writeFileSync(f, head + src); return f; }; +const show = r => `crate: ${r.crate.diagnostics.map(d => `${d.code}@${d.line}`).join(",") || "accepted"} / ref: ${r.ref.diagnostics.map(d => `${d.code}@${d.line}`).join(",") || "accepted"}`; +const accepted = (name, src) => { const f = file(src); const r = both(f); const ok = r.agree && !r.crate.diagnostics.length && !r.ref.diagnostics.length; if (!ok) check(`accepted: ${name}`, false, `${show(r)} ${r.crate.diagnostics.map(d => d.message).join(" | ").slice(0, 500)}`); return ok ? path.basename(f) : null; }; +const sleep = ms => new Promise(res => setTimeout(res, ms)); +const STATE = ` source items: { n: number }[] := [{ n: 3 }, { n: 1 }]\n sorted = items.toSorted((a, b) => a.n - b.n)\n`; +const VALUES = { peek: "peek(items)", equation: "sorted", record: "{ rows: items }" }; +const VIEW = `

    {items.map((i) => i.n).join(",")}

    `; +const GUARD = /changed what it was given/, STORE_WARN = /STORE_WRITE_OUTSIDE_SETTER/; + +// ---------------------------------------------------------------- what a handler hands JavaScript, now +// each way: [id, what is read, what changes it] (`V` the value; a spread is of a list) +const NOW = [ + ["call", "probe(V)", "grow(V)"], + ["new", "new Probe(V).said", "new Grow(V)"], + ["method", "box.probe(V)", "box.grow(V)"], + ["field", "probe({ data: V })", "grow({ data: V })"], + ["list", "probe([V])", "grow([V])"], + ["spread", "probe(...V)", null], + ["context", "probe(c)", "grow(c)"], +]; +{ + const kid = `component Kid() {\n c = use given\n source out := ""\n ${NOW.flatMap(([id, read, change]) => [``, ...(change ? [``] : [])]).filter(s => s.includes('"k-context"') || s.includes('"kg-context"')).join("")}{out}\n}\n`; + for (const [vk, v] of Object.entries(VALUES)) { + const ways = NOW.filter(([id]) => id !== "context" && !(id === "spread" && vk === "record")); + const src = `context given: any\n${kid}export default component App() {\n${STATE} box = makeBox()\n source out := ""\n provide given = ${v}\n
    \n${ways.map(([id, read, change]) => ` \n${change ? ` \n` : ""}`).join("")} \n

    {out}

    \n ${VIEW}\n
    \n}\n`; + const entry = accepted(`what a handler hands JavaScript (${vk})`, src); if (!entry) continue; + for (const production of [false, true]) { + const h = new Runner(dir, entry, undefined, { production }); + try { + const page = await h.open(await h.serve()); await sleep(200); + for (const [id] of ways) { await page.click(`.r-${id}`); await sleep(60); } + await page.click(".k-context"); await sleep(60); + const said = `${await h.text(page, ".o")} ${await h.text(page, ".ko")}`; + for (const [id] of [...ways, ["context"]]) check(`${id}, ${vk}: a plain value (${production ? "production" : "development"})`, new RegExp(`(^| )${id}:ok( |$)`).test(said), said); + const n0 = h.problems.length; + const grows = [...ways.filter(([, , g]) => g).map(([id]) => `.g-${id}`), ".kg-context"]; + if (production) for (const g of grows) { await page.click(g); await sleep(80); } + const after = h.problems.slice(n0), v1 = await h.text(page, ".v"); + if (production) check(`each change in place (${grows.length}), ${vk}: in production the source is as it was`, v1 === "3,1" && !after.length, { v1, after }); + else { + // (each change is clicked alone, so the error it draws is its own) + for (const g of grows) { const m = h.problems.length; await page.click(g); await sleep(80); const mine = h.problems.slice(m); check(`${g.replace(/^\.k?g-/, "")}, ${vk}: a change in place is the guard's error in development`, mine.length === 1 && GUARD.test(mine[0]) && (await h.text(page, ".v")) === "3,1", { mine: mine.map(p => p.slice(0, 200)) }); } + } + } catch (e) { check(`what a handler hands JavaScript (${vk}, ${production ? "production" : "development"}) runs`, false, String(e.stack ?? e)); } + await h.close().catch(() => {}); + } + } +} + +// ---------------------------------------------------------------- what is made where the component is made (RG-6) +// (bound where the component is made, a value is given as it is there: a reactive one is `peek`'s, SNAPSHOT_ARGUMENT) +const ONCE = { peek: "peek(items)", equation: "peek(sorted)", record: "peek({ rows: items })" }; +for (const [vk, v] of Object.entries(ONCE)) { + for (const [what, made] of [["fn", `keepFn(${v})`], ["class", `new Keeper(${v})`]]) { + const src = `export default component App() {\n${STATE} source said := 0\n k = ${made}\n
    \n

    {k.said}

    \n \n

    {said}

    \n \n ${VIEW}\n
    \n}\n`; + const entry = accepted(`instantiates, a ${what}'s (${vk})`, src); if (!entry) continue; + for (const production of [false, true]) { + const h = new Runner(dir, entry, undefined, { production }); + try { + const page = await h.open(await h.serve()); await sleep(250); + const said = await h.text(page, ".o"); + check(`instantiates (${what}), ${vk}: a plain value (${production ? "production" : "development"})`, said === "ok", said); + await page.click(".add"); await sleep(100); await page.click(".add"); await sleep(100); + const s = await h.text(page, ".s"), v1 = await h.text(page, ".v"); + await page.click(".more"); await sleep(100); + const v2 = await h.text(page, ".v"); + // (it kept a list of 2 rows and pushes one on each call: 3, then 4 — and none of them is the store's, which a + // write of the program's shows: 3,1,4) + check(`instantiates (${what}), ${vk}: what the library keeps grows when it pushes, and the source does not (${production ? "production" : "development"})`, s === "4" && v1 === "3,1" && v2 === "3,1,4" && !h.problems.length, { s, v1, v2, problems: h.problems.slice(0, 2) }); + } catch (e) { check(`instantiates (${what}, ${vk}, ${production ? "production" : "development"}) runs`, false, String(e.stack ?? e)); } + await h.close().catch(() => {}); + } + } + for (const [what, line] of [["fn", `g = growFn(${v})`], ["class", `g = new Growing(${v})`]]) { + const entry2 = accepted(`instantiates (${what}) that changes what it is given (${vk})`, `export default component App() {\n${STATE} ${line}\n
    ${VIEW}
    \n}\n`); if (!entry2) continue; + for (const production of [false, true]) { + const h = new Runner(dir, entry2, undefined, { production }); + try { + const page = await h.open(await h.serve()); await sleep(250); + const v1 = await h.text(page, "div").catch(() => ""); + if (production) check(`instantiates (${what}), ${vk}: a change in place leaves the source as it was (production)`, v1 === "3,1" && !h.problems.some(p => STORE_WARN.test(p)), { v1, problems: h.problems.slice(0, 2) }); + else check(`instantiates (${what}), ${vk}: a change in place is the guard's error (development)`, h.problems.some(p => GUARD.test(p)) && !h.problems.some(p => STORE_WARN.test(p)), h.problems.slice(0, 3)); + } catch (e) { check(`instantiates (${what}, ${vk}) runs`, false, String(e.stack ?? e)); } + await h.close().catch(() => {}); + } + } +} + +// ---------------------------------------------------------------- readers: what Solid gives (decided, see the head) +{ + const src = `export default component App() {\n${STATE} source said := ""\n
    \n \n \n \n

    {said}

    \n \n ${VIEW}\n
    \n}\n`; + const entry = accepted("a prop of a JavaScript component, a library provider's value, a closure's answer", src); + if (entry) for (const production of [false, true]) { + const h = new Runner(dir, entry, undefined, { production }); + try { + const page = await h.open(await h.serve()); await sleep(250); + await page.click(".ask"); await sleep(80); + const got = { prop: await h.text(page, ".pv"), ctx: await h.text(page, ".cv"), ask: await h.text(page, ".s") }; + // (a provider reads its value once, where it is made — Solid's context is no reader: given a source, Solid's + // development build says so, STRICT_READ_UNTRACKED, as it does of \`\` in plain Solid) + check(`a prop, a provider's value, a closure's answer: the store as Solid gives it (${production ? "production" : "development"})`, got.prop === "DataCloneError" && got.ctx === "DataCloneError" && got.ask === "DataCloneError" && h.problems.every(p => /STRICT_READ_UNTRACKED\] Reactive value read directly in /.test(p)), { got, problems: h.problems.slice(0, 2) }); + } catch (e) { check(`readers (${production ? "production" : "development"}) run`, false, String(e.stack ?? e)); } + await h.close().catch(() => {}); + } + const entry2 = accepted("a JavaScript component that changes its prop in place", `export default component App() {\n${STATE}
    ${VIEW}
    \n}\n`); + if (entry2) for (const production of [false, true]) { + const h = new Runner(dir, entry2, undefined, { production }); + try { + const page = await h.open(await h.serve()); await sleep(250); + const v1 = await h.text(page, ".v"); + check(`…its change is Solid's own refusal, as in plain Solid: ${production ? "dropped in production" : "STORE_WRITE_OUTSIDE_SETTER in development"}`, v1 === "3,1" && (production ? !h.problems.length : h.problems.some(p => STORE_WARN.test(p))), { v1, problems: h.problems.slice(0, 2) }); + } catch (e) { check(`a component that changes its prop (${production ? "production" : "development"}) runs`, false, String(e.stack ?? e)); } + await h.close().catch(() => {}); + } +} + +// ---------------------------------------------------------------- R10: a change in place stays the callee's +// The sixth review's N6-4 (r6 g05, g07, L2) and known-limits R5's second half, in one program: a JS fn that pushes into, +// reverses or edits what it is lent — a list in a record written at the call, a child's prop, the rows of a list's own +// method, a local that names a row. `raw` reads what the next lend is handed: the store's own data. +{ + const src = `component Child(props: { items: string[] }) { + source n := 0 + {n} +} +export default component App() { + source todos: string[] := ["a"] + source names: string[] := ["a", "b", "c"] + source rows: { id: number; tags: string[] }[] := [{ id: 1, tags: ["a"] }] + source said := "" + source data := "" +
    +

    {todos.join(",")} | {names.join(",")} | {rows[0].tags.join(",")}

    + + + + + +

    {said}

    {data}

    +
    +} +`; + const entry = accepted("R10: helpers that change what they are lent (a record's list, a prop, a list's rows, a local)", src); + const VIEW0 = "a | a,b,c | a", RAW0 = '{"todos":["a"],"names":["a","b","c"],"rows":[{"id":1,"tags":["a"]}]}', CHANGES = [".add", ".rev", ".each", ".local", ".local"]; + if (entry) for (const production of [false, true]) { + const h = new Runner(dir, entry, undefined, { production }); + try { + const page = await h.open(await h.serve()); await sleep(200); + const mine = []; + for (const c of CHANGES) { const m = h.problems.length; await page.click(c); await sleep(80); mine.push(h.problems.slice(m)); } + await page.click(".raw"); await sleep(80); + const got = { view: await h.text(page, ".v"), raw: await h.text(page, ".d"), said: await h.text(page, ".s"), child: await h.text(page, ".c") }; + if (production) { + // each helper changed a copy of its own (reverseIt answered its length; tagRow saw its own push, 2 each time — on + // eef62e69 the pushes piled up in the store's row: 3, 4), nothing is said, and the store's data is what the view shows + check("R10 (production): each change in place is the callee's own — the view and the store's data, read raw, are as they were", got.view === VIEW0 && got.raw === RAW0 && got.said === "2 2" && got.child === "3" && !h.problems.length, { got, problems: h.problems.slice(0, 2) }); + } else { + check("R10 (development): each change in place is the guard's error, naming the callee", mine.every(m => m.length === 1 && GUARD.test(m[0])) && /addTo\(…\)/.test(mine[0][0]) && /reverseIt\(…\)/.test(mine[1][0]) && /tagRow\(…\)/.test(mine[2][0]) && /tagRow\(…\)/.test(mine[3][0]), mine.map(m => m.map(p => p.slice(0, 160)))); + check("R10 (development): …and the view and the store's data are as they were", got.view === VIEW0 && got.raw === RAW0 && got.said === "" && got.child === "0", got); + } + } catch (e) { check(`R10 (${production ? "production" : "development"}) runs`, false, String(e.stack ?? e)); } + await h.close().catch(() => {}); + } +} + +rmSync(dir, { recursive: true, force: true }); +console.log(`\n${pass} passed, ${fail} failed${process.env.LEND_TOOLS ? ` (tools: ${TOOLS})` : ""}`); +process.exit(fail ? 1 : 0); diff --git a/compiler/test/lib.mjs b/compiler/test/lib.mjs new file mode 100644 index 000000000..b58034ce8 --- /dev/null +++ b/compiler/test/lib.mjs @@ -0,0 +1,105 @@ +// The library build (spec/09 MO-13e): `rx-lib` over a small package written in .rx — what it writes, the marker on the +// signatures it ships, the `exports` it holds the package.json to, and that an .rx app compiled against the installed +// package imports the factory by the package's name. bench/tasks/rx-package runs such a package for real (an .rx app +// and a .tsx app, in Chromium and on the server); this needs only the crate. +// Usage: node compiler/test/lib.mjs (after `cargo build --release` in compiler/, or `npm run build` for the Node-API build) +import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { spawnSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const repo = path.resolve(here, "../.."); +const rxc = process.env.RXC || path.join(repo, `compiler/target/${process.env.RX_PROFILE ?? "release"}/rxc`); +if (existsSync(rxc)) process.env.RXC = rxc; // else the Node-API build +const { build, exportsOf, foreignKeys } = await import("../lib.mjs"); + +let fail = 0; +const check = (name, ok, got) => { if (!ok) fail++; console.log(`${ok ? "✓" : "✗"} ${name}${ok ? "" : ` — ${typeof got === "string" ? got : JSON.stringify(got)}`.slice(0, 900)}`); }; + +const dir = mkdtempSync(path.join(tmpdir(), "rx-lib-")); +const pkg = path.join(dir, "pkg"); +cpSync(path.join(repo, "bench/tasks/rx-package/src/package"), pkg, { recursive: true }); +const dist = f => path.join(pkg, "dist", f); +const read = f => readFileSync(dist(f), "utf8"); + +// 1. the layout +let r = build(pkg, { types: false }); +check("the package builds", r.ok, r.problems); +const must = ["index.js", "index.server.js", "index.dom.js", "index.ssr.js", "index.dom.js.map", "index.d.rx", "index.d.ts", "theme.js", "theme.server.js", "theme.dom.js", "theme.ssr.js", "theme.d.rx", "theme.d.ts", "rates.js", "rates.d.ts"]; +check("each module: a browser and a server build, what an import resolves to on each side, its signature, its types", must.every(f => existsSync(dist(f))), must.filter(f => !existsSync(dist(f)))); +check("the signature is marked, and is the compiler's print", /^\/\/@ signature index\.rx /.test(read("index.d.rx")) && /^export source rate: pending fails\(Error \| Offline\) = …$/m.test(read("index.d.rx")) && /uses\(\.\/theme\.rx#theme\)/.test(read("index.d.rx")), read("index.d.rx")); +check("a dependency's factory is its own compiled module, on each side", /from "\.\/theme\.dom\.js"/.test(read("index.dom.js")) && /from "\.\/theme\.ssr\.js"/.test(read("index.ssr.js")) && /from "\.\/rates\.js"/.test(read("index.dom.js")), read("index.dom.js").split("\n").filter(l => /^import .*from "\./.test(l))); +check("the browser build is hydratable DOM code and the server build writes strings", /getNextElement/.test(read("index.dom.js")) && /ssrHydrationKey/.test(read("index.ssr.js")) && !/ssrHydrationKey/.test(read("index.dom.js")), "targets"); +check("what an import resolves to: the factory as __rx, and each export bound by the runtime's library()", /import __rx from "\.\/index\.dom\.js";/.test(read("index.js")) && /import __rx from "\.\/index\.ssr\.js";/.test(read("index.server.js")) && /export \{ __rx \};/.test(read("index.js")) && ["Offline", "code", "rate", "pick", "useLabel", "Badge", "Rate"].every(n => read("index.js").includes(`export const ${n} = __lib.${n};`)) && !/theme/.test(read("index.js")), read("index.js")); +check("the module is named in the call, for the root JavaScript instantiates it in: the same id on both sides (MO-13h)", /__library\(__rx, "@bench\/rates\/index", \{"useLabel":\[0\]\}, false\);/.test(read("index.js")) && /__library\(__rx, "@bench\/rates\/index", \{"useLabel":\[0\]\}, false\);/.test(read("index.server.js")) && /__library\(__rx, "@bench\/rates\/theme"\);/.test(read("theme.js")), read("index.js")); +check("a context and a type are .rx's: not values of the JS module", !/export const theme\b/.test(read("theme.js")) && /export const ThemeProvider = /.test(read("theme.js")) && /export type \{ Theme \}/.test(read("theme.d.ts")), read("theme.js")); +check("the .d.ts says what JavaScript gets: a source is an accessor, a `ref` parameter one too, an error class tests instances", /export declare const rate: \(\) => typeof __m\.rate;/.test(read("index.d.ts")) && /useLabel: \(\.\.\.args: __Refs, \[true\]>\) => __Accessor>;/.test(read("index.d.ts")) && /\[Symbol\.hasInstance\]\(e: unknown\): e is __m\.Offline/.test(read("index.d.ts")), read("index.d.ts")); +// MO-13i: what a fn answers, handed out in parts +{ + const dts = read("pager.d.ts"); + check("a fn's parts in the .d.ts: an accessor for what is read, the action's type, the value's, a tuple's items", /export declare const createPager: .* => \{ "page": __Accessor\["page"\]>; "quote": __Accessor<[^;]*>; "set": ReturnType\["set"\]; "first": ReturnType\["first"\]; "edges": \{ "start": __Accessor<[^;]*>; "end": __Accessor<[^;]*> \}; "label": [^_]*typeof __m\.createPager>\["label"\] \};/.test(dts) && /export declare const createPages: .* => \[__Accessor\[0\]>, ReturnType\[1\]\];/.test(dts), dts); + check("a module that holds no state says so to the runtime, and one that does not, not (MO-13g)", /"@bench\/rates\/pager", \{"createPager":\[0\],"createPages":\[0\]\}, true\);/.test(read("pager.js")) && /import \{ primitives as __library \}/.test(read("pager.server.js")) && /import \{ library as __library \}/.test(read("theme.js")), [read("pager.js"), read("theme.js")]); + check("a runtime that hands out no parts is refused where the app links the package: the factory imports `result` by name, and one that hands out none does not (11 CP-4b)", /^import \{[^}\n]*\bresult as rt\$result\b[^}\n]*\} from "@reactivescript\/runtime";$/m.test(read("pager.dom.js")) && !/rt\$result/.test(read("index.dom.js")), read("pager.dom.js").slice(0, 400)); + check("every module the package ships is stamped with the format a runtime instantiates (11 CP-4b)", ["pager.dom.js", "index.dom.js", "pager.ssr.js"].every(f => /^module\.__rxFormat = 3;$/m.test(read(f))), read("pager.dom.js").slice(-200)); +} +check("the source map carries the .rx", JSON.parse(read("index.dom.js.map")).sourcesContent?.[0]?.includes("export source rate"), "sourcesContent"); +check("exportsOf reads a printed signature's rows", JSON.stringify(exportsOf("//@ signature x.rx\nexport type T\nexport context c: T\nexport source a := …\nexport b: pending\nexport pure fn f(ref a: number, b) instantiates\nexport pure fn u() rejects(Error) instantiates uses(./t.rx#c)\nexport pure fn cb(f: (x: number) => void, ref n: number): pending fails(Error) { 1: io } instantiates\nexport pure fn fails2(a: string): pending fails(A | B)\nexport pure fn g(a)\nexport server fn s(a)\nexport action go\nexport error E(code)\nexport component C(props: {})\n")) === JSON.stringify([["T", "type"], ["c", "context"], ["a", "accessor"], ["b", "accessor"], ["f", "primitive", [true, false]], ["u", "primitive", []], ["cb", "primitive", [false, true]], ["fails2", "fn", [false]], ["g", "fn", [false]], ["s", "server"], ["go", "action"], ["E", "error"], ["C", "component"]]), exportsOf("export pure fn g(a)\n")); +check("an optional parameter is a parameter (E-9a): its mark is no part of what the runtime is told", JSON.stringify(exportsOf("//@ signature x.rx\nexport pure fn f(ref a: number, b?: { x?: number }, c?) instantiates\nexport pure fn g(a, b?: () => void)")) === JSON.stringify([["f", "primitive", [true, false, false]], ["g", "fn", [false, false]]]), "exportsOf"); +check("a generic fn's row is read past its type parameters (07 §2)", JSON.stringify(exportsOf("//@ signature x.rx\nexport pure fn f U[], U = Array>>(ref a: T, b) instantiates\nexport pure fn g(a: T)")) === JSON.stringify([["f", "primitive", [true, false], " U[], U = Array>>"], ["g", "fn", [false], ""]]), "exportsOf"); + +check("a generic component's and a generic type's rows are read past their type parameters (07 §2)", JSON.stringify(exportsOf("//@ signature x.rx\nexport type Item = { v: T; label: U }\nexport component List(props: { items; children: view { item: T } value(item) }) shape(roots ul)")) === JSON.stringify([["Item", "type"], ["List", "component"]]), JSON.stringify(exportsOf("//@ signature x.rx\nexport type Item = { v: T; label: U }\nexport component List(props: { items }) shape(roots ul)"))); +// 2. the exports map is held to what was built +const json = JSON.parse(readFileSync(path.join(pkg, "package.json"), "utf8")); +writeFileSync(path.join(pkg, "package.json"), JSON.stringify({ ...json, exports: { ".": "./dist/index.js" }, peerDependencies: {} })); +r = build(pkg, { types: false }); +check("a package.json whose exports do not name the builds is refused, with the map", !r.ok && r.problems.some(p => /"exports"/.test(p) && /index\.server\.js/.test(p)) && r.problems.some(p => /peerDependencies/.test(p) && /@reactivescript\/runtime/.test(p)), r.problems); +r = build(pkg, { types: false, write: true }); +const written = JSON.parse(readFileSync(path.join(pkg, "package.json"), "utf8")); +check("--write writes it: Solid's conditions, the server build for node, deno and worker, the browser build otherwise", r.ok && JSON.stringify(written.exports["."]) === JSON.stringify({ types: "./dist/index.d.ts", worker: "./dist/index.server.js", browser: "./dist/index.js", deno: "./dist/index.server.js", node: "./dist/index.server.js", default: "./dist/index.js" }) && written.exports["./theme"]?.browser === "./dist/theme.js" && written.peerDependencies["solid-js"] === "^2.0.0", written); +check("and the next build agrees with it", build(pkg, { types: false }).ok, "second build"); + +// 3. what a package cannot carry, and what the checker refuses, is said +writeFileSync(path.join(pkg, "src/extra.rx"), "export server fn save(id: number) { return id }\n"); +r = build(pkg, { types: false, entries: ["src/index.rx", "src/theme.rx", "src/extra.rx"] }); +check("an exported server fn is refused (MO-13f)", !r.ok && r.problems.some(p => /server fn save/.test(p)), r.problems); +writeFileSync(path.join(pkg, "src/extra.rx"), "export component Bad() {\n source n := 1\n

    {n := 2}

    \n}\n"); +r = build(pkg, { types: false, entries: ["src/extra.rx"] }); +check("a module the checker refuses is not built", !r.ok && r.problems.length > 0, r.problems); +// a module's scoped styles are linked by what the browser's import resolves to, and by nothing on the server +writeFileSync(path.join(pkg, "src/extra.rx"), "export component Tag() {\n new\n \n}\n"); +r = build(pkg, { types: false, entries: ["src/index.rx", "src/theme.rx", "src/extra.rx"], write: true }); +check("a module's stylesheet is written, and imported by the browser's entry alone (07 CSS-4)", r.ok && existsSync(dist("extra.css")) && /^import "\.\/extra\.css";$/m.test(read("extra.js")) && !/extra\.css/.test(read("extra.server.js")) && !/\.css/.test(read("index.js")), r.ok ? read("extra.js") : r.problems); +check("a signature that names a context through node_modules is found (MO-13b): another package's, by where it was installed", JSON.stringify(foreignKeys("//@ signature a.rx\nexport component A() uses(./theme.rx#theme, ../node_modules/b/dist/index.rx#mode)\nexport component B() provides(../../node_modules/@s/c/dist/x.rx#c)")) === JSON.stringify(["../node_modules/b/dist/index.rx#mode", "../../node_modules/@s/c/dist/x.rx#c"]) && foreignKeys(read("index.d.rx")).length === 0, foreignKeys(read("index.d.rx"))); +// MO-13b, MO-11u: a key that leaves what the package ships — its own declaration of another library, beside its sources +{ + const { leavingKeys } = await import("../lib.mjs"); + const sig = "//@ signature index.rx\nexport action save\nexport renders ../rx-types/solid-sonner.d.rx#Toaster from toast:7\nexport component A() uses(./theme.rx#theme) hosts(../rx-types/kit.d.rx#Host catches(./errors.rx#Lost))"; + check("a signature that names a host or a context outside the package's root is found: an app has another declaration of that library, under another key", JSON.stringify(leavingKeys(sig, "/pkg/src/index.rx", "/pkg/src")) === JSON.stringify(["../rx-types/solid-sonner.d.rx#Toaster", "../rx-types/kit.d.rx#Host"]), JSON.stringify(leavingKeys(sig, "/pkg/src/index.rx", "/pkg/src"))); + check("...and one under the root is the package's own", leavingKeys(sig, "/pkg/src/index.rx", "/pkg").length === 0); +} +writeFileSync(path.join(pkg, "package.json"), JSON.stringify(written)); +rmSync(path.join(pkg, "src/extra.rx")); +check("the package builds again", build(pkg, { types: false }).ok, "third build"); + +// 4. an .rx app against the installed package: checked by the shipped signature, compiled to import its factory +const app = path.join(dir, "app"); +mkdirSync(path.join(app, "node_modules/@bench/rates"), { recursive: true }); +cpSync(path.join(pkg, "package.json"), path.join(app, "node_modules/@bench/rates/package.json")); +cpSync(path.join(pkg, "dist"), path.join(app, "node_modules/@bench/rates/dist"), { recursive: true }); +cpSync(path.join(repo, "bench/tasks/rx-package/src/main.rx"), path.join(app, "main.rx")); +const compile = (target) => { const x = spawnSync(rxc, ["app", path.join(app, "main.rx"), "--target", target], { encoding: "utf8", maxBuffer: 1 << 27 }); try { return JSON.parse(x.stdout); } catch { return { error: x.stderr || x.stdout }; } }; +if (existsSync(rxc)) { + const out = compile("dom"); const code = Object.values(out.modules ?? {})[0]?.code ?? ""; + check("the app compiles against the package's .d.rx alone", !!out.modules && !out.diagnostics, out); + check("its import of the package is the factory, by the package's name (MO-13c)", /import \{ __rx as (__m\d+) \} from "@bench\/rates";/.test(code) && /import \{ __rx as (__m\d+) \} from "@bench\/rates\/theme";/.test(code) && /rt\$module\(__app, (__m\d+), \1\)/.test(code), code.split("\n").filter(l => /@bench|rt\$module/.test(l))); + check("the modules read are the package's own, nothing drafted", (out.asked ?? []).some(f => f.endsWith("node_modules/@bench/rates/dist/index.d.rx")) && Object.keys(out.modules).length === 1, out.asked); + writeFileSync(path.join(app, "main.rx"), readFileSync(path.join(app, "main.rx"), "utf8").replace("
    ", "
    ")); + const bad = compile("dom"); + check("a mistake across the package boundary is refused where it is written", (bad.diagnostics ?? []).some(d => d.code === "CONTEXT_NOT_FOUND"), bad.diagnostics ?? bad); +} else console.log("- no rxc binary: the app's compile is bench/tasks/rx-package's"); + +rmSync(dir, { recursive: true, force: true }); +console.log(fail ? `\n${fail} failed` : "\nlib: all passed"); +process.exit(fail ? 1 : 0); diff --git a/compiler/test/loops.mjs b/compiler/test/loops.mjs new file mode 100644 index 000000000..8f6cabbcc --- /dev/null +++ b/compiler/test/loops.mjs @@ -0,0 +1,248 @@ +// 02 C-3c (2026-12-01): the effect-run breaker. Nine programs the reviews wrote — each accepted by both checkers (C-3 +// reads what a module's text shows), each an effect whose apply changes its own input through something C-3 does not +// follow (spec/archive/known-limits-2026-11-29.md: R2 a handler prop and the view's own handler, R3 another module's +// action, R7 a setter JavaScript made and a query client, R11 a dispatch in a helper or an action, R12 a popover's +// `beforetoggle`, and a `handler` word that states what is not so). On eef62e69 every one hangs the tab in Solid's +// production build (the navigation does not reach "load" in 30 s, or the click never returns) and one hangs its +// development build too, with no message. Here each must, in both builds: open, say `EFFECT_LOOP [C-3c]` with the +// effect's module, line and inputs — once when it is stopped and once when the run it is owed loops again — leave the +// page answering, and never reach Solid's own "Potential Infinite Loop Detected" (100,000 flushes later). +// Beside them, what must stay as it is: a countdown that writes its input from a timer, a popover kept in step both ways +// (it converges), an effect run exactly the limit's times in one turn (nothing said), and one run 5,000 times in one turn +// by a burst that is no loop — it is told once, is not stopped, and ends on its last value. +// LOOP_TOOLS=
    runs another checkout's compiler and runtime (its bench/harness.mjs and workspace) over the same +// programs: the positive control (eef62e69 fails every loop, and the burst's count). +// Needs what bench/run.mjs needs. node compiler/test/loops.mjs [filter] +import { mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import path from "node:path"; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const TOOLS = process.env.LOOP_TOOLS ? path.resolve(process.env.LOOP_TOOLS) : path.resolve(here, "../.."); +const { ws, workspace, both, withDrafts, Runner } = await import(pathToFileURL(path.join(TOOLS, "bench/harness.mjs")).href); +if (!process.env.LOOP_TOOLS) workspace(); +const root = path.join(ws, "loops"); rmSync(root, { recursive: true, force: true }); mkdirSync(root, { recursive: true }); +const filter = process.argv[2]; +let pass = 0, fail = 0; +const check = (name, ok, got) => { ok ? pass++ : fail++; console.log(`${ok ? "✓" : "✗"} ${name}${ok ? "" : `\n ${String(typeof got === "string" ? got : JSON.stringify(got)).slice(0, 900)}`}`); return ok; }; +const sleep = ms => new Promise(res => setTimeout(res, ms)); +const show = r => `crate: ${r.crate.diagnostics.map(d => `${d.code}@${d.line}`).join(",") || "accepted"} / ref: ${r.ref.diagnostics.map(d => `${d.code}@${d.line}`).join(",") || "accepted"}`; +/** A program in a folder of its own: its files written, both checkers asked. */ +const stage = (name, files) => { + const dir = path.join(root, name); mkdirSync(dir, { recursive: true }); + for (const [f, text] of Object.entries(files)) { mkdirSync(path.dirname(path.join(dir, f)), { recursive: true }); writeFileSync(path.join(dir, f), text); } + const r = both(withDrafts(path.join(dir, "main.rx"))); + return check(`${name}: accepted by both checkers`, r.agree && !r.crate.diagnostics.length && !r.ref.diagnostics.length, `${show(r)} ${r.crate.diagnostics.map(d => d.message).join(" | ").slice(0, 500)}`) ? dir : null; +}; +/** The page's text, or what stood in the way (a tab that does not answer in 3 s is a hang). */ +const text = async (h, page, sel = ".out") => { try { return await Promise.race([h.text(page, sel), sleep(3000).then(() => "")]); } catch (e) { return `ERR ${String(e.message).slice(0, 120)}`; } }; + +// what the probes share: an event made, a listener as @reactivescript/std's `on` declares it, a timer +const EV = { + "ev.js": `export const mkEvent = (t) => new Event(t, { bubbles: true }) +export const emit = (el, type) => { el.dispatchEvent(new Event(type)) } +export function on(target, type, f, options) { target.addEventListener(type, f, options); return () => target.removeEventListener(type, f, options) } +export function after(ms, f) { const id = setTimeout(() => f(), ms); return () => clearTimeout(id) } +`, + "ev.d.rx": `export fn mkEvent(t: string): Event +export fn emit(el: EventTarget, type: string): void +export client fn on(target: EventTarget, type: string, f: listener(target, type) (e: E) => void, options?: boolean | AddEventListenerOptions): () => void +export fn after(ms: number, f: handler () => void): () => void +`, +}; +// [name, the known limit, files, the effect as the error names it, steps, the view when the page rests] +const LOOPS = [ + ["R2-prop-cycle", "R2: a child's effect on a prop calls the handler prop that writes the parent's source", { "main.rx": `component Clamp(props: { value: number; onChange: (v: number) => void }) { + effect (props.value) { props.onChange($0 + 1) } + {props.value} +} +export default component App() { + source n := 0 +
    { n := v }} />
    +} +` }, "main.rx:2, effect (props.value)", [], "2000"], + ["R2-click", "R2: an effect clicks a button whose own handler writes the effect's input", { "main.rx": `export default component App() { + source n := 0 + source btn: HTMLButtonElement | null := null + effect (n, btn) { if ($1 != null) { $1.click() } } +
    +} +` }, "main.rx:4, effect (n, btn)", [], "2000"], + ["R3-imported-action", "R3: an effect on another .rx module's source calls that module's action", { "counter.rx": `export source count := 0 +export action bump() { count := count + 1 } +`, "main.rx": `import { count, bump } from "./counter.rx" +export default component App() { + effect (count) { bump() } +
    {count}
    +} +` }, "main.rx:3, effect (count)", [], "2000"], + ["R7-js-signal", "R7: a signal JavaScript made, its setter called by an effect on its value", { "sig.js": `import { createSignal } from "solid-js" +export const makeCounter = () => createSignal(0) +`, "sig.d.rx": `export pure fn makeCounter(): [ref number, io (...args: Parameters>) => ReturnType>] +`, "main.rx": `import { makeCounter } from "./sig.js" +export default component App() { + [count, setCount] = makeCounter() + effect (count) { setCount($0 + 1) } +
    {count}
    +} +` }, "main.rx:4, effect (count)", [], "2000"], + ["R7-setquerydata", "R7: an effect on a query's data writes that query's data through the client", { "api.js": `import { QueryClient } from "@tanstack/solid-query" +export const queryClient = new QueryClient() +export const fetchN = () => Promise.resolve(1) +`, "api.d.ts": `export declare const queryClient: import("@tanstack/solid-query").QueryClient +export declare function fetchN(): Promise +`, "rx-types/@tanstack/solid-query.d.rx": `extend fn useQueryClient instantiates +`, "main.rx": `import { QueryClientProvider, useQuery, useQueryClient } from "@tanstack/solid-query" +import { queryClient, fetchN } from "./api.js" +component N() { + q = useQuery({ queryKey: ["n"], queryFn: fetchN }) + qc = useQueryClient() + effect (q.data) { qc.setQueryData(["n"], ($0 ?? 0) + 1) } +

    {q.data}

    +} +export default component App() { +
    {errored fallback(e) {

    {e.message}

    } { {loading fallback {

    …

    } { }} }}
    +} +` }, "main.rx:6, effect (q.data)", [], "2001"], + ["R11-js-dispatch", "R11: a listener the apply adds, its event dispatched by a JS helper in the same apply", { ...EV, "main.rx": `import { emit } from "./ev.js" +export default component App() { + source n := 0 + source el: HTMLElement | null := null + effect (n, el) { + if ($1 != null) { + let ac = new AbortController() + $1.addEventListener("ping", () => { n := n + 1 }, { signal: ac.signal }) + emit($1, "ping") + return () => { ac.abort() } + } + } +
    { el := e }}>{n}
    +} +` }, "main.rx:5, effect (n, el)", [], "2000"], + ["R11-action-fire", "R11: the event dispatched inside an action of the module the apply calls", { ...EV, "main.rx": `import { on, mkEvent } from "./ev.js" +export default component App() { + source n := 0 + source el: HTMLElement | null := null + action fire() { if (el != null) { el.dispatchEvent(mkEvent("ping")) } } + effect (n, el) { + if ($1 != null) { + let off = on($1, "ping", () => { n := n + 1 }) + fire() + return off + } + } +
    { el := e }}>{n}
    +} +` }, "main.rx:6, effect (n, el)", [], "2000"], + ["R12-popover-count", "R12: a popover's beforetoggle, run by the view's own handler, counts", { "main.rx": `export default component App() { + source open := false + source n := 0 + source el: HTMLElement | null := null + effect (open, n, el) { if ($2 != null) { if ($0) { $2.togglePopover() } } } +
    + +
    { el := e }} onBeforeToggle={() => { n := n + 1 }}>pop
    +

    {n}

    +
    +} +` }, "main.rx:5, effect (open, n, el)", [".t", ".t", ".t"], "tpop2000"], + ["W-false-handler", "a word that states what is not so: `handler` on a callback a microtask delivers (R8's remainder)", { "util.js": `export const nextTick = (f) => { Promise.resolve().then(f) } +`, "util.d.rx": `export fn nextTick(f: handler () => void): void +`, "main.rx": `import { nextTick } from "./util.js" +export default component App() { + source n := 0 + effect (n) { nextTick(() => { n := n + 1 }) } +
    {n}
    +} +` }, "main.rx:4, effect (n)", [], "2000"], +]; +const STOPPED = /EFFECT_LOOP \[C-3c\] .*: its apply ran 1000 times before the page got a turn/, FEEDS = /EFFECT_LOOP \[C-3c\] .*: its apply ran 1000 times again in the turn after it was stopped/, SOLID = /Potential Infinite Loop/; +const esc = s => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + +for (const [name, what, files, place, clicks, rest] of LOOPS) { + if (filter && !name.includes(filter)) continue; + const dir = stage(name, files); if (!dir) continue; + for (const production of [false, true]) { + const build = production ? "production" : "development", h = new Runner(dir, "main.rx", undefined, { production }); + try { + const page = await h.open(await h.serve()); await sleep(500); + for (const c of clicks) { try { await page.click(c, { timeout: 3000 }); } catch (e) { h.problems.push(`click ${c}: ${String(e.message).split("\n")[0]}`); } await sleep(300); } + const seen = await text(h, page), named = new RegExp(`EFFECT_LOOP \\[C-3c\\] \\S*${esc(place)}: `); + check(`${name} (${build}): the page opens, answers, and rests at ${rest} — ${what}`, seen === rest, { seen, problems: h.problems.map(p => p.slice(0, 160)) }); + check(`${name} (${build}): EFFECT_LOOP names the effect (${place}), once where it is stopped and once where the run it was owed loops again`, h.problems.length === 2 && STOPPED.test(h.problems[0]) && FEEDS.test(h.problems[1]) && h.problems.every(p => named.test(p)) && !h.problems.some(p => SOLID.test(p)), h.problems); + // a development build says what the input went from and to; a production build names it only (its value is the user's data) + check(`${name} (${build}): ${production ? "the inputs are named, their values are not said" : "the input that moved is said with its values"}`, STOPPED.test(h.problems[0] ?? "") && /\(\d+ → \d+\)/.test(h.problems[0]) === !production, h.problems.map(p => p.slice(0, 280))); + } catch (e) { check(`${name} (${build}): runs`, false, String(e.message ?? e).split("\n").slice(0, 3).join(" ")); } + await h.close().catch(() => {}); + } +} + +// ---------------------------------------------------------------- what is no loop +const CONTROLS = [ + ["ctl-countdown", "a countdown that writes its own input from a timer: 5 → 0, nothing said", { ...EV, "main.rx": `import { after } from "./ev.js" +export default component App() { + source left := 5 + effect (left) { if ($0 > 0) { return after(50, () => { left := left - 1 }) } } +
    {left}
    +} +` }, async (h, page) => { await sleep(500); return [await text(h, page)]; }, ["0"]], + ["ctl-popover-controlled", "a popover kept in step both ways (its beforetoggle writes what follows from the event): it converges, nothing said", { "main.rx": `export default component App() { + source open := false + source el: HTMLElement | null := null + effect (open, el) { if ($1 != null) { if ($0) { $1.showPopover() } else { $1.hidePopover() } } } +
    + +
    { el := e }} onBeforeToggle={(e: ToggleEvent) => { open := e.newState == "open" }}>pop
    +

    {open ? "open" : "closed"}

    +
    +} +` }, async (h, page) => { const seen = [await text(h, page)]; for (let i = 0; i < 3; i++) { await page.click(".t", { timeout: 3000 }); await sleep(200); seen.push(await text(h, page)); } return seen; }, ["tpopclosed", "tpopopen", "tpopclosed", "tpopopen"]], +]; +for (const [name, what, files, drive, want] of CONTROLS) { + if (filter && !name.includes(filter)) continue; + const dir = stage(name, files); if (!dir) continue; + for (const production of [false, true]) { + const h = new Runner(dir, "main.rx", undefined, { production }); + try { + const page = await h.open(await h.serve()); await sleep(300); + const seen = await drive(h, page); + check(`${name} (${production ? "production" : "development"}): ${what}`, JSON.stringify(seen) === JSON.stringify(want) && !h.problems.length, { seen, problems: h.problems }); + } catch (e) { check(`${name} (${production ? "production" : "development"}): runs`, false, String(e.message ?? e).split("\n").slice(0, 3).join(" ")); } + await h.close().catch(() => {}); + } +} +// an effect that writes nothing of its own input, run by a burst of microtasks (each a write and a flush of its own: a +// parser handing over rows it already has) — as many times as the limit in one turn, and five times as many +// (re-check 15, AC-1n: a library callback given in a handler writes functionally — the plain write is LATE_CALLBACK_WRITE) +if (!filter || "ctl-burst".includes(filter)) { + const dir = stage("ctl-burst", { "burst.js": `export const burst = (n, f) => { let p = Promise.resolve(); for (let i = 0; i < n; i++) p = p.then(() => f(i + 1)) } +export const record = (v) => { (window.__seen ??= []).push(v) } +`, "burst.d.rx": `export fn burst(n: number, f: handler (i: number) => void): void +export fn record(v: number): void +`, "main.rx": `import { burst, record } from "./burst.js" +export default component App() { + source n := 0 + effect (n) { record($0) } +
    {n}
    +} +` }); + if (dir) for (const production of [false, true]) { + const build = production ? "production" : "development", h = new Runner(dir, "main.rx", undefined, { production }); + try { + const page = await h.open(await h.serve()); await sleep(300); + const runs = () => page.evaluate(() => `${window.__seen.length} runs, last ${window.__seen.at(-1)}`); + await page.click(".k"); await sleep(300); + check(`ctl-burst (${build}): 1,000 runs in one turn are the limit's, and all are made — nothing said`, (await text(h, page)) === "kgo1000" && (await runs()) === "1001 runs, last 1000" && !h.problems.length, { seen: await text(h, page), runs: await runs(), problems: h.problems }); + await page.click(".go"); await sleep(400); + // the mount's run, the first burst's 1,000, then 1,000 of the second's, and the one it is owed: on its last value + check(`ctl-burst (${build}): 5,000 runs in one turn — the effect is told once, is not stopped, and ends on its last value`, (await text(h, page)) === "kgo6000" && (await runs()) === "2002 runs, last 6000" && h.problems.length === 1 && STOPPED.test(h.problems[0]) && /main\.rx:4, effect \(n\)/.test(h.problems[0]), { seen: await text(h, page), runs: await runs(), problems: h.problems }); + await page.click(".k"); await sleep(300); + check(`ctl-burst (${build}): …and it runs as before in the turns after`, (await text(h, page)) === "kgo1000" && (await runs()) === "3002 runs, last 1000" && h.problems.length === 1, { seen: await text(h, page), runs: await runs(), problems: h.problems }); + } catch (e) { check(`ctl-burst (${build}): runs`, false, String(e.message ?? e).split("\n").slice(0, 3).join(" ")); } + await h.close().catch(() => {}); + } +} + +rmSync(root, { recursive: true, force: true }); +console.log(`\n${pass} passed, ${fail} failed${process.env.LOOP_TOOLS ? ` (tools: ${TOOLS})` : ""}`); +process.exit(fail ? 1 : 0); diff --git a/compiler/test/names.mjs b/compiler/test/names.mjs new file mode 100644 index 000000000..0ef37c8ea --- /dev/null +++ b/compiler/test/names.mjs @@ -0,0 +1,171 @@ +// 09 MO-1d, 11 CP-4: a name is its binding's. Every function of the language (compiler/src/names.rs), under every kind of +// binding: both checkers agree, the interpreter and the compiled program give what the binding gives (never what the +// language's function of that name does), a JS import is in the compiled module and in the TSX projection. And a word that +// begins an expression (`peek`, `latest`) is not called where the module binds it; and nothing but names.rs and names.ts lists the functions. +// CP-4c: `fetch` and `fail` unimported, wherever a name can stand: the scenario prelude's in a conformance build, UNBOUND in +// an app; and a compiled app whose imported `fetch` makes its request. +// Needs the runtime's build and the crate's (rxc, the Node-API build). node --experimental-strip-types compiler/test/names.mjs +import { execFileSync, spawnSync } from "node:child_process"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import { tmpdir } from "node:os"; +import { fileURLToPath } from "node:url"; +import path from "node:path"; +import { HARNESS, NAMES } from "../../ref/src/names.ts"; +import { loadModules } from "../../ref/src/modules.ts"; +import { checkModules } from "../../ref/src/check.ts"; +import { Runtime } from "../../ref/src/runtime.ts"; + +const here = path.dirname(fileURLToPath(import.meta.url)), root = path.resolve(here, "../.."); +const { app: compile } = createRequire(import.meta.url)("../index.js"); +const rxc = path.join(root, `compiler/target/${process.env.RX_PROFILE ?? "release"}/rxc`); +const tmp = mkdtempSync(path.join(tmpdir(), "rx-names-")); mkdirSync(path.join(tmp, "node_modules/@reactivescript"), { recursive: true }); +symlinkSync(path.join(root, "runtime"), path.join(tmp, "node_modules/@reactivescript/runtime")); +for (const d of ["solid-js", "@solidjs", "seroval", "seroval-plugins"]) symlinkSync(path.join(root, "runtime/node_modules", d), path.join(tmp, "node_modules", d)); +const write = (f, s) => { mkdirSync(path.dirname(path.join(tmp, f)), { recursive: true }); writeFileSync(path.join(tmp, f), s); }; +let fail = 0; const bad = (what, why) => { fail++; console.log(`✗ ${what}: ${why}`); }; + +const names = [...NAMES.keys()], OWN = "x => \"own\" + x"; +const js = `export const own = ${OWN};\n${names.map(n => `export { own as ${n} };`).join("\n")}\n`; +write("lib.js", js); write("decl.js", js); write("dflt.js", `export default ${OWN};\n`); write("prelude.js", js); +write("decl.d.rx", names.map(n => `export pure fn ${n}(x: any): string\n`).join("")); +write("node_modules/own/package.json", `{"name":"own","type":"module","exports":"./index.js"}`); write("node_modules/own/index.js", js); +write("own.rx", names.map(n => `export fn ${n}(x: number): string => \`own\${x}\`\n`).join("")); + +const app = (body, head = "") => `${head}export default component App() {\n${body}\n}\n`; +const imp = h => n => app(`

    {${n}(5)}

    `, h(n) + "\n"); +/** Each kind's program. `js`: its import, which the compiled module and the projection must have. `codes`: what both checkers say. */ +const KINDS = { + "import pure": { p: imp(n => `import pure { ${n} } from "./lib.js"`), js: "./lib.js" }, + "import pure { own as n }": { p: imp(n => `import pure { own as ${n} } from "./lib.js"`), js: "./lib.js" }, + "import pure { n as own }": { p: n => app(`

    {own(5)}

    `, `import pure { ${n} as own } from "./lib.js"\n`), js: "./lib.js" }, + "a declared import": { p: imp(n => `import { ${n} } from "./decl.js"`), js: "./decl.js" }, + "a default import": { p: imp(n => `import pure ${n} from "./dflt.js"`), js: "./dflt.js" }, + "a package's": { p: imp(n => `import pure { ${n} } from "own"`), js: "own" }, + "a file named prelude": { p: imp(n => `import pure { ${n} } from "./prelude"`), js: "./prelude", run: false }, + "a plain import, called in a view": { p: imp(n => `import { ${n} } from "./lib.js"`), codes: ["IO_IN_REACTIVE"] }, + "a plain import, called in a handler": { p: n => app(`

    { ${n}(() => 5) }}>own5

    `, `import { ${n} } from "./lib.js"\n`), js: "./lib.js" }, + "a plain import, called in a closure's closure": { p: n => app(`

    { [1].forEach((x) => { ${n}(x) }) }}>own5

    `, `import { ${n} } from "./lib.js"\n`), js: "./lib.js" }, + "a server import": { p: n => app(`

    { go() }}>own5

    `, `import server { ${n} } from "./lib.js"\nserver fn go() { ${n}(5) }\n`), js: "./lib.js" }, + "an .rx import": { p: imp(n => `import { ${n} } from "./own.rx"`) }, + "an .rx import { n as own }": { p: n => app(`

    {own(5)}

    `, `import { ${n} as own } from "./own.rx"\n`) }, + "a fn": { p: n => app(`

    {${n}(5)}

    `, `fn ${n}(x: number): string => \`own\${x}\`\n`) }, + "a fn of a component": { p: n => app(` fn ${n}(x: number): string => \`own\${x}\`\n

    {${n}(5)}

    `) }, + "an equation": { p: n => app(` ${n} = (x) => \`own\${x}\`\n

    {${n}(5)}

    `) }, + "a source": { p: n => app(` source ${n} := "own5"\n

    {${n}}

    `) }, + "a fn's parameter": { p: n => app(`

    {f(x => \`own\${x}\`)}

    `, `fn f(${n}: (x: number) => string): string => ${n}(5)\n`) }, + "a closure's parameter": { p: n => app(` f = (${n}) => ${n}(5)\n

    {f(x => \`own\${x}\`)}

    `) }, + "a component's props": { p: n => app(` \`own\${x}\`} />`, `component C(${n}: { f: (x: number) => string }) {\n

    {${n}.f(5)}

    \n}\n`) }, + "a prop, destructured": { p: n => app(` \`own\${x}\`} />`, `component C(props: { ${n}: (x: number) => string }) {\n { ${n} } = props\n

    {${n}(5)}

    \n}\n`) }, + "a loop's variable": { p: n => app(`

    {for ${n} in ["own5"] { {${n}} }}

    `) }, + "a local": { p: n => app(`

    { let ${n} = (x) => x; ${n}(5) }}>own5

    `) }, + "a local of a server fn": { p: n => app(` a = await go()\n errored fallback(e) {

    e

    } {

    {a}

    }`, `server fn go(): Promise { let ${n} = (x: number) => \`own\${x}\`; return ${n}(5) }\n`), run: false }, + "an action": { p: n => app(` action ${n}(x: number) { }\n

    { ${n}(5) }}>own5

    `) }, + "an action's parameter": { p: n => app(` action f(${n}: (x: number) => void) { ${n}(5) }\n

    { f((x) => { }) }}>own5

    `) }, + "a caught error": { p: n => app(`

    { try { go() } catch (${n}) { b := ${n}.message } }}>own5

    `, `import { own as go } from "./lib.js"\nsource b := ""\n`) }, + "a row keyed, rebuilt": { p: n => app(` xs = ${n}([1], (x) => ({ t: "own5" }))\n

    {for x in xs { {x.t} }}

    `, `fn ${n}(a: number[], f: (x: number) => { t: string }): { t: string }[] => a.length > 0 ? KEPT : []\nKEPT: { t: string }[] = [{ t: "own5" }]\n`) }, +}; +const read = over => p => over[p] ?? (existsSync(p) && p.startsWith(tmp) ? (() => { try { return readFileSync(p, "utf8"); } catch { return undefined; } })() : undefined); +const tests = []; +for (const [kind, k] of Object.entries(KINDS)) for (const n of names) { + const what = `${n}, ${kind}`, id = `t${tests.length}`, file = path.join(tmp, `${id}.rx`), src = k.p(n); + writeFileSync(file, src); + let set, ref; + try { set = loadModules(file, read({})); ref = checkModules(set).diags.map(d => d.code); } catch (e) { ref = [`throws ${e.message}`]; } + const r = spawnSync(rxc, ["check", "--json", file], { encoding: "utf8" }); let crate; + try { crate = JSON.parse(r.stdout).diagnostics.map(d => d.code); } catch { crate = [`${r.stdout}${r.stderr}`]; } + if (String(ref) !== String(crate)) bad(what, `ref says ${ref}, the crate ${crate}`); + if (String(ref) !== String(k.codes ?? [])) bad(what, `expected [${k.codes ?? ""}], got [${ref}]`); + if (k.codes || ref.length) continue; + const out = JSON.parse(compile(file, "ssr")); if (!out.modules) { bad(what, JSON.stringify(out).slice(0, 300)); continue; } + const code = out.modules[file].code; + const helper = n.startsWith("on") || n === "until" ? new RegExp(`rt\\$${n}\\(`) : new RegExp(`__B\\.${n}\\b`); + if (helper.test(code)) bad(what, `compiled to the language's ${n}`); + if (k.js && !new RegExp(`import (\\w+ from )?.*"${k.js.replace(/\./g, "\\.")}"`).test(code)) bad(what, "the import was dropped"); + const tsx = JSON.parse(execFileSync(rxc, ["project", file], { encoding: "utf8" })).files?.find(f => f.rx === file)?.code ?? ""; + if (k.js && !tsx.includes(`from "${k.js}"`)) bad(what, "the import is not in the projection"); + if (new RegExp(`import \\{[^}]*\\b${n}\\b[^}]*\\} from "[^"]*__prelude`).test(tsx.split("\n")[0]) && /import|package|^a fn$/.test(kind)) bad(what, "the projection takes the prelude's"); + if (!k.js) { // the interpreter has no JS + try { const rt = new Runtime(loadModules(file, read({}))); const f = JSON.stringify(rt.step([])); if (k.run !== false && !f.includes("own5")) bad(what, `interpreted: ${f.slice(0, 200)}`); } catch (e) { if (!/not in the scenario prelude/.test(e.message)) bad(what, `interpreted: ${e.message}`); } + } + if (k.run === false) continue; + for (const [f, m] of Object.entries(out.modules)) writeFileSync(f === file ? path.join(tmp, `${id}.mjs`) : f.replace(/\.rx$/, ".rx.mjs"), m.code.replace(/(from ")([^"]*)\.rx(\?[^"]*)?"/g, (_, a, b) => `${a}${b.startsWith("/") ? b : path.join(tmp, b)}.rx.mjs"`)); + tests.push([what, id]); +} +// the compiled programs, each rendered by the server build +write("run.mjs", `import { createApp } from "@reactivescript/runtime"; +for (const [what, id] of ${JSON.stringify(tests)}) { + let html = ""; + try { const main = (await import("./" + id + ".mjs")).default; const app = createApp(); await new Promise(end => app.stream(main(app), { write: s => { html += s; }, end })); } catch (e) { html = String(e); } + if (!html.replace(//g, "").includes("own5")) console.log(what + "\\t" + html.slice(0, 200).replace(/\\n/g, " ")); +}\n`); +const ran = spawnSync(process.execPath, ["run.mjs"], { cwd: tmp, encoding: "utf8" }); +for (const l of (ran.stdout + (ran.status ? ran.stderr : "")).split("\n").filter(Boolean)) bad(l.split("\t")[0], `compiled: ${l.split("\t")[1]}`); + +// CP-4c: the harness's names, bound by nothing. Each place: refused in an app by both checkers and by every command that takes a +// file, with the same words; in a conformance build (the mark on the load) neither checker says UNBOUND, and both say the same. +const PLACES = { + "a view": p => app(`

    {${p}("/x")}

    `), "an equation": p => app(` a = ${p}("/x")\n

    {a}

    `), + "an awaited equation": p => app(` a = await ${p}("/x")\n errored fallback(e) {

    e

    } {

    {a}

    }`), + "a question": p => app(` source a = await ${p}("/x")\n errored fallback(e) {

    e

    } {

    {a}

    }`), + "a handler": p => app(`

    { ${p}("/x") }}>x

    `), "a handler's closure": p => app(`

    { [1].forEach((x) => { ${p}("/x") }) }}>x

    `), + "an effect": p => app(` source a := 1\n effect (a) { ${p}("/x") }\n

    {a}

    `), + "an action": p => app(` action go() { await ${p}("/x") catch (e) => null }\n

    { go() }}>x

    `), + "a server fn": p => app(`

    { go() }}>x

    `, `server fn go() { ${p}("/x") }\n`), + "a fn": p => app(`

    {f()}

    `, `fn f() { ${p}("/x") }\n`), "a fn nothing calls": p => app(`

    x

    `, `fn f() { ${p}("/x") }\n`), "an exported fn": p => `export fn f() { ${p}("/x") }\n`, + "a closure": p => app(` f = () => ${p}("/x")\n

    {f()}

    `), "a value": p => app(` f = ${p}\n

    {f("/x")}

    `), "a value in a record": p => app(` f = { go: ${p} }\n

    {f.go("/x")}

    `), + "an argument": p => app(`

    {map(["/x"], ${p})}

    `), "a prop": p => app(` `, `component C(props: { f: any }) {\n

    {props.f("/x")}

    \n}\n`), + "a branch another binding is in": p => app(`

    {map([1], (${p}) => ${p})}{${p}("/x")}

    `), +}; +const run1 = (...a) => spawnSync(rxc, a, { encoding: "utf8" }); +for (const [place, program] of Object.entries(PLACES)) for (const n of HARNESS.keys()) { + const what = `${n} unimported, ${place}`, file = path.join(tmp, "harness.rx"), src = program(n); writeFileSync(file, src); + const ref = checkModules(loadModules(file, read({}))).diags, want = `${n} is not declared here${HARNESS.get(n)}`; + const says = { ref: ref.map(d => `${d.code} ${d.msg}`), check: JSON.parse(run1("check", "--json", file).stdout).diagnostics.map(d => `${d.code} ${d.message}`), app: (JSON.parse(compile(file, "dom")).diagnostics ?? []).map(d => `${d.code} ${d.msg}`), lib: (JSON.parse(run1("app", file, "--lib").stdout).diagnostics ?? []).map(d => `${d.code} ${d.msg}`), + editor: (JSON.parse(spawnSync(rxc, ["serve"], { input: JSON.stringify({ id: 1, method: "analyze", params: { file, overlays: {} } }) + "\n", encoding: "utf8" }).stdout).result.diagnostics).map(d => `${d.code} ${d.message}`) }; + for (const [who, got] of Object.entries(says)) { if (!got.includes(`UNBOUND ${want}`)) bad(what, `${who}: ${JSON.stringify(got)}`); if (String(got) !== String(says.ref)) bad(what, `${who} says ${got}, ref ${says.ref}`); } + if (run1("compile", file, "--out", path.join(tmp, "out")).status === 0) bad(what, "rxc compile compiled it"); + const held = checkModules(loadModules(file, read({}), true)).diags.map(d => d.code); + const [c] = JSON.parse(spawnSync(rxc, ["conform"], { input: JSON.stringify([{ id: 0, entry: file, files: { [file]: src }, conformance: true }]), encoding: "utf8" }).stdout); + if (String(held) !== String(c.diags.map(d => d.code)) || held.includes("UNBOUND")) bad(what, `a conformance build: ref says ${held}, the crate ${c.diags.map(d => d.code)}`); + if (!held.length) { const [l] = JSON.parse(spawnSync(rxc, ["lower"], { input: JSON.stringify([{ id: 0, entry: file, files: { [file]: src }, conformance: true }]), encoding: "utf8", maxBuffer: 1 << 26 }).stdout); if (!JSON.stringify(l).includes(`__B.${n}`)) bad(what, "a conformance build lost the prelude's"); } +} +// the prelude of an app has neither, beside what is the language's +{ const file = path.join(tmp, "nopre/main.rx"); write("nopre/main.rx", app(`

    {len([1])}

    { fetch("/x") }}>x`, `import { len } from "./prelude"\nimport { fetch } from "./prelude"\n`).replace("import { len }", "import pure { len }")); + const m = JSON.parse(compile(file, "ssr")); if (!/import \{ fetch as \w+\$fetch \} from "\.\/prelude"/.test(m.modules?.[file]?.code ?? "") || /__B\.fetch/.test(m.modules[file].code)) bad("import { fetch } from ./prelude, in an app", JSON.stringify(m).slice(0, 400)); } +// an .rx module of the program, and a package's +for (const n of HARNESS.keys()) { write("mod.rx", `export fn go() { ${n}("/x") }\n`); const file = path.join(tmp, "usemod.rx"); write("usemod.rx", app(`

    {go()}

    `, `import { go } from "./mod.rx"\n`)); + const ref = checkModules(loadModules(file, read({}))).diags.map(d => d.code), crate = JSON.parse(run1("check", "--json", file).stdout).diagnostics.map(d => d.code); + if (String(ref) !== String(crate) || !ref.includes("UNBOUND")) bad(`${n} in a module of the program`, `${ref} / ${crate}`); } +// a compiled app's imported `fetch`, and its own `fail` +{ const file = path.join(tmp, "net.rx"); + write("net.js", `export const fetch = async u => (await globalThis.fetch(globalThis.__at + u)).text();\n`); + write("net.rx", app(` a = await fetch("/hello")\n errored fallback(e) {

    {e.message}

    } { loading fallback {

    …

    } {

    {a} {fail("b")}

    } }`, `import pure { fetch } from "./net.js"\nfn fail(x: string): string => \`own\${x}\`\n`)); + const m = JSON.parse(compile(file, "ssr")); if (!m.modules) bad("an app's imported fetch", JSON.stringify(m)); else { + write("net.mjs", m.modules[file].code); + write("netrun.mjs", `import { createServer } from "node:http"; import { createApp } from "@reactivescript/runtime"; +const asked = []; const s = createServer((q, r) => { asked.push(q.url); r.end("world"); }); await new Promise(r => s.listen(0, r)); globalThis.__at = "http://localhost:" + s.address().port; +let html = ""; const main = (await import("./net.mjs")).default; const a = createApp(); await new Promise(end => a.stream(main(a), { write: x => { html += x; }, end })); s.close(); +console.log(JSON.stringify({ asked, html })); process.exit(0);\n`); + const r = spawnSync(process.execPath, ["netrun.mjs"], { cwd: tmp, encoding: "utf8", timeout: 30000 }); let o; try { o = JSON.parse(r.stdout.trim().split("\n").pop()); } catch { o = { asked: [], html: r.stdout + r.stderr }; } + if (o.asked[0] !== "/hello" || !/world/.test(o.html) || !/ownb/.test(o.html)) bad("an app's imported fetch", JSON.stringify(o).slice(0, 400)); } } + +// a word that begins an expression +for (const w of ["peek", "latest", "throw", "await"]) for (const [src, ok] of [[`import pure { ${w} } from "./lib.js"`], [`import pure { own as ${w} } from "./lib.js"`], [`import pure ${w} from "./dflt.js"`], [`fn ${w}(x: number): number => x`], [`fn f(${w}: number): number => ${w}(1)`], [`import pure { ${w} as x } from "./lib.js"`, true], [`fn ${w}(x: number): number => x`, true, "

    a

    "], [`fn f(${w}: number): number => 1`, true, "

    a

    "], [`export fn ${w}(x: number): number => x`, true, "

    a

    "]]) { + const file = path.join(tmp, "w.rx"); writeFileSync(file, app(` ${src.includes(" as x ") ? "

    a

    " : ok ? "

    a

    " : `

    {${w}(1)}

    `}`, src + "\n")); + let ref = ""; try { loadModules(file, read({})); } catch (e) { ref = e.message; } + const crate = JSON.parse(spawnSync(rxc, ["check", "--json", file], { encoding: "utf8" }).stdout).diagnostics.map(d => d.message).join(" "); + for (const [who, said] of [["ref", ref], ["the crate", crate]]) if (said.includes("is the form") === !!ok) bad(src, `${who} says "${said}"`); +} + +// one list: a comparison of a name with one of the functions', outside names.rs and names.ts, is a place that does not ask by scope +for (const dir of ["compiler/src", "ref/src", "ref/compile", "ref/oracle", "ref/types"]) for (const f of readdirSync(path.join(root, dir))) { + if (/^names\./.test(f) || !/\.(rs|ts)$/.test(f)) continue; + readFileSync(path.join(root, dir, f), "utf8").split("\n").forEach((l, i) => { + const s = l.replace(/const DRAFT_CALLBACKS.*|const ARRAY_.*/, "").replace(/\/\/.*/, ""); + if (/"len",\s*"str"|(name|\bn|fname)(\.as_str\(\))? ?={2,3} ?"(len|str|filter|sum|fail|fetch|every|indexOf|log|until)"/.test(s)) bad(`${dir}/${f}:${i + 1}`, l.trim().slice(0, 120)); + }); +} +rmSync(tmp, { recursive: true, force: true }); +console.log(fail ? `${fail} failed` : `✓ ${names.length} names × ${Object.keys(KINDS).length} kinds of binding: each is its binding's (${tests.length} programs run compiled); ${HARNESS.size} of the harness × ${Object.keys(PLACES).length} places, in an app and in a conformance build`); +process.exit(fail ? 1 : 0); diff --git a/compiler/test/node.mjs b/compiler/test/node.mjs index 15984a052..66c05293f 100644 --- a/compiler/test/node.mjs +++ b/compiler/test/node.mjs @@ -1,9 +1,10 @@ // The Node-API build loads on this platform and compiles a program for every target: what CI checks on each binary -// before it is published. Usage: node test/node.mjs (after `npm run build`) +// before it is published. Then the Vite front end's cache over it (vite.mjs). +// Usage: node test/node.mjs (after `npm run build`) import { createRequire } from "node:module"; -import { fileURLToPath } from "node:url"; +import { fileURLToPath, pathToFileURL } from "node:url"; import path from "node:path"; -import { mkdtempSync, writeFileSync } from "node:fs"; +import { mkdtempSync, renameSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; const { app } = createRequire(import.meta.url)("../index.js"); @@ -36,4 +37,55 @@ const code = Object.values(rel.modules ?? {}).map(m => m.code).join("\n"); const relOk = !rel.error && !rel.diagnostics && /from "\.\/util\.js"/.test(code) && !/from "\.\/api"/.test(code); if (!relOk) fail++; console.log(`${relOk ? "✓" : "✗"} a relative JS import stays an ES import${relOk ? "" : `: ${JSON.stringify(rel).slice(0, 300)}`}`); +// W-6, MO-10i: a draft's updater evaluates its place once — the object, then the key — so a key with an effect is +// computed once, and the old value is read from the element the new one is written to; run here on a plain draft +writeFileSync(path.join(dir, "store.js"), "export const createStore = init => { const s = init; return [s, f => { f(s); }]; };\nlet i = 0;\nexport const next = () => i++;\n"); +writeFileSync(path.join(dir, "store.d.rx"), "export pure fn createStore(init: T): [T, (update: (draft state: T) => T | void) => void]\nexport fn next(): number\n"); +writeFileSync(path.join(dir, "draft.rx"), [ + 'import { createStore, next } from "./store.js"', + 'export default component App() {', + ' [todos, setTodos] = createStore<{ items: number[] }>({ items: [10, 20, 30] })', + ' ', + '}', +].join("\n")); +const dr = JSON.parse(app(path.join(dir, "draft.rx"), "dom", null, true)); +const dcode = Object.values(dr.modules ?? {}).map(m => m.code).join("\n"); +const calls = (dcode.match(/next\(\)/g) ?? []).length; +const place = /const __o\$d = [^;]+\["items"\];\s*const __k\$d = [^;]*next\(\);\s*__o\$d\[__k\$d\] = \(/.test(dcode); +const dOk = !dr.error && !dr.diagnostics && calls === 1 && place; +if (!dOk) fail++; +console.log(`${dOk ? "✓" : "✗"} a draft updater's key is computed once (${calls} call${calls === 1 ? "" : "s"} of next)${dOk ? "" : `: ${(dr.error ?? JSON.stringify(dr.diagnostics) ?? dcode).slice(0, 900)}`}`); +// and the same statement, as JavaScript runs it: one element read and written +{ + const body = dcode.match(/\{\s*const __o\$d[\s\S]*?__o\$d\[__k\$d\]\);\s*\}/)?.[0]; + let calls2 = 0; const d = { items: [10, 20, 30] }; + const run = body && new Function("v$d", "next", body.replace(/\b[\w$]+\.next\(\)|\bv\$next\(\)|\bnext\(\)/g, "next()")); + try { run?.(d, () => calls2++); } catch (e) { console.log(String(e)); } + const ran = !!run && calls2 === 1 && JSON.stringify(d.items) === "[11,20,30]"; + if (!ran) fail++; + console.log(`${ran ? "✓" : "✗"} ...run: one call, items ${JSON.stringify(d.items)}${ran ? "" : ` (${body ?? "no block"})`}`); +} +// the Vite front end (vite.mjs) does not keep a failed build: a program that failed on an import compiles once the import +// is back (#84). The diagnostic names the importer and a rename keeps the file's mtime, so nothing it stamped changes +const { default: rx } = await import(pathToFileURL(fileURLToPath(new URL("../vite.mjs", import.meta.url))).href); +const root = mkdtempSync(path.join(tmpdir(), "rx-recover-")); +const main = path.join(root, "main.rx"), part = path.join(root, "part.rx"), away = path.join(root, "part.away"); +writeFileSync(main, 'import { Part } from "./part.rx"\n\nexport default component App() {\n \n}\n'); +writeFileSync(part, 'export component Part(props: { label: string }) {\n {props.label}\n}\n'); +const ctx = (id, moduleId) => ({ id, moduleId, root, solid: { generate: "dom" }, addWatchFile() {} }); +const entry = front => front.compile("", ctx(main, main)).code, dep = front => front.compile("", ctx(part, `${part}?rx-dep`)).code; +const lost = compile => { try { compile(); } catch (e) { return /main\.rx:\d+(:\d+)?: error MODULE_NOT_FOUND/.test(e.message); } return false; }; +let recovered; +try { + const warm = rx(), want = { entry: entry(warm), dep: dep(warm) }; + renameSync(part, away); const failed = lost(() => entry(warm)); renameSync(away, part); + if (!failed) throw new Error("a missing import is not MODULE_NOT_FOUND at its importer"); + if (entry(warm) !== want.entry || dep(warm) !== want.dep) throw new Error("the program compiled after its import came back differs from the first"); + // and a program whose first compile failed, then asked for by its dependency (the cold path) + const cold = rx(); + renameSync(part, away); lost(() => entry(cold)); renameSync(away, part); + if (dep(cold) !== want.dep) throw new Error("the dependency of a program that had failed differs from the first"); +} catch (e) { recovered = e.message.split("\n")[0]; } +if (recovered) fail++; +console.log(`${recovered ? "✗" : "✓"} the Vite front end compiles a program again once its missing import is back${recovered ? `: ${recovered}` : ""}`); process.exit(fail ? 1 : 0); diff --git a/compiler/test/paste-apply.mjs b/compiler/test/paste-apply.mjs new file mode 100644 index 000000000..afda60035 --- /dev/null +++ b/compiler/test/paste-apply.mjs @@ -0,0 +1,242 @@ +// The appliers of a printed spelling (compiler/test/pasted.mjs's, 2026-12-03; shared since 2026-12-04 with +// compiler/test/corpus.mjs, the property over the declaration corpus): each takes a message (`m.code`, `m.msg`, `m.file`, +// `m.line`) and a project's folder, and applies the spelling the message prints — the text in its backticks, in the file +// it names — or throws where the message prints none of that kind. Nothing here writes a spelling of its own. +import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { spawnSync } from "node:child_process"; +import path from "node:path"; + +/** The message's spellings: the text in each pair of backticks, in order. */ +export const ticks = msg => [...msg.matchAll(/`([^`]+)`/g)].map(m => m[1]); +export function appliers({ repo, ws }) { + const read = (d, f) => readFileSync(path.join(d, f), "utf8"); + const write = (d, f, s) => { mkdirSync(path.dirname(path.join(d, f)), { recursive: true }); writeFileSync(path.join(d, f), s); }; + const append = (d, f, line) => write(d, f, (existsSync(path.join(d, f)) ? read(d, f) : "") + line + "\n"); + const lines = (d, f = "main.rx") => read(d, f).split("\n"); + const setLines = (d, xs, f = "main.rx") => write(d, f, xs.join("\n")); + const declareJs = path.join(repo, "tooling/rx-language-server/bin/declare.js"); + /** The file a message names for a spelling: the last `in .d.rx` (a row's), or the one after `written in`. */ + const named = (msg, re) => { const all = [...msg.matchAll(re)].map(m => m[1].replace(/[,.;:)]+$/, "")); if (!all.length) throw new Error(`no file named (${re})`); return all.at(-1); }; + const ROWFILE = /\b(?:written )?in ((?:\.\/|rx-types\/)[^\s`,;()]+?\.d\.rx)\b/g; + const tick = (msg, re, what) => { const t = ticks(msg).find(x => re.test(x)); if (!t) throw new Error(`no ${what} in its backticks`); return t; }; + const APPLY = { + /** `import pure { a as b } from "m"` / `import pure X from "m"`: in place of the name in the import that names it */ + import(m, d) { + const t = tick(m.msg, /^import pure /, "`import pure …`"), from = /from ("[^"]+")$/.exec(t)[1], def = /^import pure ([\w$]+) from /.exec(t)?.[1]; + const spec = def ? undefined : /^import pure \{ (.+) \} from /.exec(t)[1], alias = def ?? spec.split(" as ").pop(); + const f = m.file, xs = lines(d, f), at = xs.findIndex(l => !l.startsWith("import pure") && l.startsWith("import ") && l.endsWith(` from ${from}`) && new RegExp(`(^import |[{,]\\s*)(?:[\\w$]+ as )?${alias}\\b`).test(l)); + if (at < 0) throw new Error(`no import of ${alias} from ${from}`); + // (a default beside named exports, `import dayjs, { Dayjs } from "dayjs"`: the default goes pure, the named stay) + if (def) { const named = /^import\s+[\w$]+\s*,\s*(\{[^}]*\})\s*from /.exec(xs[at])?.[1]; xs.splice(at, 1, t, ...(named ? [`import ${named} from ${from}`] : [])); } + else { + const names = /\{(.*)\}/.exec(xs[at])[1].split(",").map(x => x.trim()).filter(x => x && x.split(" as ").pop() !== alias); + const pure = xs.findIndex(l => l.startsWith("import pure {") && l.endsWith(` from ${from}`)); + if (pure >= 0) xs[pure] = xs[pure].replace(/\s*\}/, `, ${spec} }`); + if (names.length) xs[at] = `import { ${names.join(", ")} } from ${from}`; else xs.splice(at, 1); + if (pure < 0) xs.splice(Math.max(0, at), 0, t); + } + setLines(d, xs, f); + }, + /** `extend …` in rx-types/.d.rx: a row added over the draft */ + extend(m, d) { append(d, named(m.msg, /in (rx-types\/[^\s`,;()]+?\.d\.rx)/g), tick(m.msg, /^extend (?!.*\binstantiates$)/, "`extend …` row")); }, + "extend-instantiates"(m, d) { append(d, named(m.msg, /in (rx-types\/[^\s`,;()]+?\.d\.rx)/g), tick(m.msg, /^extend .*\binstantiates$/, "`extend … instantiates` row")); }, + /** a word put in the `extend` row the project's declaration has already (`extend pure fn f`, `… instantiates`) */ + "extend-word"(m, d) { + const f = named(m.msg, /in (rx-types\/[^\s`,;()]+?\.d\.rx)/g), inst = ticks(m.msg).find(x => /^extend .*\(…\) instantiates$/.test(x)), pure = ticks(m.msg).find(x => /^extend pure (?:fn|class) [\w$.]+$/.test(x)); + const t = inst ?? pure; if (!t) throw new Error("no word for the `extend` row in its backticks"); + const [, kind, name] = /^extend (?:pure )?(fn|class) ([\w$.]+)/.exec(t), xs = lines(d, f), k = xs.findIndex(l => new RegExp(`^extend (?:pure )?${kind} ${name.replace(/[.$]/g, "\\$&")}\\b`).test(l)); + if (k < 0) throw new Error(`${f} has no \`extend ${kind} ${name}\` row`); + xs[k] = inst ? `${xs[k]} instantiates` : xs[k].replace(/^extend /, "extend pure "); setLines(d, xs, f); + }, + /** `(cb: handler)` after `extend fn name`, in the project's `extend` row: its parameters' words, written there */ + /** re-check 15 (C2): "replace its `extend` row in rx-types/.d.rx with ``" — the export's one row, merged */ + "extend-replace"(m, d) { + const x = /replace its `extend` row in (rx-types\/[^\s`]+?\.d\.rx) with `([^`]+)`/.exec(m.msg); if (!x) throw new Error("no `replace its extend row … with` printed"); + const [, f, row] = x, [, kind, name] = /^extend (?:(?:pure|reads|server) )*(fn|class|component) ([\w$.]+)/.exec(row) ?? []; + if (!kind) throw new Error(`not an extend row: ${row}`); + const xs = lines(d, f), k = xs.findIndex(l => new RegExp(`^extend (?:(?:pure|reads|server) )*${kind} ${name.replace(/[.$]/g, "\\$&")}(?![\\w$.])`).test(l)); + if (k < 0) throw new Error(`${f} has no \`extend ${kind} ${name}\` row`); + xs[k] = row; setLines(d, xs, f); + }, + "extend-params"(m, d) { + const p = tick(m.msg, /^\(.*\)$/, "`(… : handler)`"), [, kind, name] = /\(…\)` after `extend (fn|class) ([\w$.]+)`|`\(.*\)` after `extend (fn|class) ([\w$.]+)`/.exec(m.msg)?.slice(2) ?? []; + const f = named(m.msg, /in (rx-types\/[^\s`,;()]+?\.d\.rx)/g), xs = lines(d, f); + if (!kind) throw new Error("no `after extend …` row named"); + const k = xs.findIndex(l => new RegExp(`^extend (?:pure )?${kind} ${name.replace(/[.$]/g, "\\$&")}(?![\\w$(])`).test(l)); + if (k < 0) throw new Error(`${f} has no \`extend ${kind} ${name}\` row without parameters`); + xs[k] = xs[k].replace(new RegExp(`^(extend (?:pure )?${kind} ${name.replace(/[.$]/g, "\\$&")})`), `$1${p}`); setLines(d, xs, f); + }, + /** `export class C(…) … instantiates` (R9-1): the row in , ended with the word */ + "row-instantiates"(m, d) { + const t = tick(m.msg, /^export (?:(?:server|client) )?(?:fn|class) [\w$.]+\(…\) … instantiates$/, "`export … (…) … instantiates`"), [, side = "", kind, name] = /^export ((?:server|client) )?(fn|class) ([\w$.]+)/.exec(t), f = named(m.msg, ROWFILE); + const xs = lines(d, f), k = xs.findIndex(l => new RegExp(`^export ${side}(?:pure |reads )?${kind} ${name.replace(/[.$]/g, "\\$&")}\\b`).test(l)); + if (k < 0) throw new Error(`${f} has no row \`export ${kind} ${name}\``); + xs[k] = `${xs[k]} instantiates`; setLines(d, xs, f); + }, + /** R9-3: the helper that makes the closure a closure answers — its module, its rows, its import — bound for each value a + * closure of that shape reads (`() => { let t = x; return () => { x := t } }`), and its name written where the closure is */ + helper(m, d) { + const js = tick(m.msg, /^export const [\w$]+ = /, "helper"), name = /^export const ([\w$]+)/.exec(js)[1]; + const row = tick(m.msg, new RegExp(`^export pure fn ${name}<`), "helper's row"), dts = tick(m.msg, new RegExp(`^export declare const ${name}:`), "helper's .d.ts"), imp = tick(m.msg, new RegExp(`^import \\{ ${name} \\}`), "helper's import"), bind = tick(m.msg, new RegExp(`^[\\w$]+ = ${name}\\(x, `), "the binding"); + const base = /from "(\.\/[^"]+)\.js"$/.exec(imp)[1]; + write(d, `${base}.js`, js + "\n"); write(d, `${base}.d.rx`, row + "\n"); write(d, `${base}.d.ts`, dts + "\n"); + let src = read(d, m.file), k = 0; const binds = []; + // (the statement that holds the first closure: the bindings go before it, at its indentation) + const first = src.search(/\(\) => \{ let ([\w$]+) = ([\w$]+); return \(\) => \{ \2 := \1 \} \}/); if (first < 0) throw new Error("no closure of the shape the message names"); + let stmt = src.slice(0, first).split("\n").length - 1; const ls0 = src.split("\n"); while (stmt > 0 && /^(\s*)/.exec(ls0[stmt])[1].length > 2) stmt--; + src = src.replace(/\(\) => \{ let ([\w$]+) = ([\w$]+); return \(\) => \{ \2 := \1 \} \}/g, (_, t, x) => { const u = `${bind.split(" = ")[0]}${k++ || ""}`; binds.push(bind.replace(/^[\w$]+/, u).replaceAll("x", x)); return u; }); + if (!binds.length) throw new Error("no closure of the shape the message names"); + const xs = src.split("\n"), pad = /^(\s*)/.exec(xs[stmt])[1], last = xs.map(l => /^import /.test(l)).lastIndexOf(true); + xs.splice(stmt, 0, ...binds.map(b => `${pad}${b}`)); xs.splice(last + 1, 0, imp); + write(d, m.file, xs.join("\n")); + }, + /** `export pure fn name` written in : the row's own word changed where it is */ + row(m, d) { + const t = tick(m.msg, /^export (?:(?:server|client) )?pure (?:fn|class) [\w$.]+$/, "`export pure fn …`"), [, side = "", kind, name] = /^export ((?:server|client) )?pure (fn|class) ([\w$.]+)$/.exec(t), f = named(m.msg, ROWFILE); + const src = read(d, f), re = new RegExp(`^export ${side}(${kind}) ${name.replace(/[.$]/g, "\\$&")}\\b`, "m"); + if (!re.test(src)) throw new Error(`${f} has no row \`export ${side}${kind} ${name}\``); + write(d, f, src.replace(re, `export ${side}pure $1 ${name}`)); + }, + /** `npx rx-declare --out `, as printed; where it cannot draft, what it says is the next message */ + command(m, d, st) { + const [, spec, out] = /^npx rx-declare (\S+) --out (\S+)$/.exec(tick(m.msg, /^npx rx-declare /, "`npx rx-declare …` command")); + const r = spawnSync(process.execPath, [declareJs, spec, "--out", out], { cwd: d, encoding: "utf8" }); + st.declared = { status: r.status, stderr: r.stderr, out }; + }, + /** what rx-declare said where it could not draft: the rows it prints, written by hand in the file it names */ + hand(m, d, st) { + const said = st.declared?.stderr ?? ""; if (!st.declared || st.declared.status === 0) throw new Error("rx-declare drafted: no rows to write by hand"); + const f = named(said, /write (\S+?\.d\.rx) by hand/g), rows = ticks(said).filter(x => /^export (?:fn|class) [\w$]+\(/.test(x)); + if (!rows.length) throw new Error(`rx-declare printed no rows: ${said}`); + write(d, f, rows.join("\n") + "\n"); + return "keep"; // (the step is the command's: no message of the program's is pasted) + }, + /** `name: handler T` (a parameter, a field, an index signature `[key: string]`) in the row, in : the word put there */ + member(m, d) { + // (2026-12-04: "write `handler` after `onIdle?:` in the record of options, in f's row, in " — the place, as the + // row writes it: inside that parameter of that row, whatever the row's layout) + const place = /write `handler` after `([^`]+)` in (?:the record of ([\w$]+), in )?([\w$.]+)'s row/.exec(m.msg); + if (place) { + const [, head, pn, fn] = place, f = named(m.msg, ROWFILE), src = read(d, f), esc = x => x.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + const row = new RegExp(`^export (?:pure |reads )?(?:server |client )?(?:fn|class|component) ${esc(fn)}\\b`, "m").exec(src); if (!row) throw new Error(`${f} has no row of ${fn}`); + let i = row.index + row[0].length, depth = 0; + for (; i < src.length; i++) { const c = src[i]; if (c === "<") depth++; else if (c === ">" && src[i - 1] !== "=") depth--; else if (c === "(" && depth === 0) break; } + let j = i + 1; for (let k = 1; j < src.length && k; j++) { const c = src[j]; if ("([{".includes(c)) k++; else if (")]}".includes(c)) k--; if (!k) break; } + // the parameter that holds it: from its name (`ref opts`, `__0?`) to the next comma at its depth + let lo = i + 1, hi = j; + if (pn) { + const at = new RegExp(`(^|[\\s(,])(?:ref |draft )?(?:\\.\\.\\.)?${esc(pn)}\\??\\s*:`).exec(src.slice(i + 1, j)); if (!at) throw new Error(`${fn}'s row has no parameter ${pn}`); + lo = i + 1 + at.index; let k = 0; for (hi = lo; hi < j; hi++) { const c = src[hi]; if ("([{<".includes(c)) k++; else if (")]}".includes(c) || (c === ">" && src[hi - 1] !== "=")) k--; else if (c === "," && k === 0 && hi > lo + at[0].length) break; } + } + const re = new RegExp(`(^|[\\s{;,(])(${esc(head)})\\s*`), hit = re.exec(src.slice(lo, hi)); if (!hit) throw new Error(`${fn}'s row has no \`${head}\` there`); + const ins = lo + hit.index + hit[0].length; + write(d, f, `${src.slice(0, ins)}${/\s$/.test(hit[0]) ? "" : " "}handler ${src.slice(ins)}`.replace(/handler +/, "handler ")); + return; + } + const t = tick(m.msg, /^(?:\[[^\]]*\]|[\w$]+\??): handler /, "`… : handler …`"), f = named(m.msg, ROWFILE), was = t.replace(/: handler /, ": "); + const src = read(d, f); if (!src.includes(was)) throw new Error(`${f} has no \`${was}\``); + write(d, f, src.replace(was, t)); + }, + /** `callback: handler (…) => …`, before `...args` in the row, in : a parameter written at its place */ + before(m, d) { + const t = tick(m.msg, /(?:^|, )callback: handler /, "`callback: handler …`"), at = /before `([^`]+)` in /.exec(m.msg)?.[1], f = named(m.msg, ROWFILE); + const fn = /before `[^`]+` in ([\w$.]+)'s row/.exec(m.msg)?.[1]; if (!at || !fn) throw new Error("no `before …` place in a row"); + const xs = lines(d, f), k = xs.findIndex(l => new RegExp(`^export (?:pure |reads )?(?:fn|class) ${fn.replace(/[.$]/g, "\\$&")}[<(]`).test(l) && l.includes(`${at}:`)); + if (k < 0) throw new Error(`${f} has no row of ${fn} with ${at}`); + xs[k] = xs[k].replace(`${at}:`, `${t}, ${at}:`); setLines(d, xs, f); + }, + /** the factory a `new` the language does not make is written in: the module, its row, the import, the call */ + /** 10 SV-7f (2026-12-02): the platform's name from std — the import it prints, after the module's last import */ + std(m, d) { + const imp = tick(m.msg, /^import \{ [\w$]+ \} from "@reactivescript\/std\/platform"$/, "std's import"); + const xs = lines(d, m.file), last = xs.map(l => /^import /.test(l)).lastIndexOf(true); xs.splice(last + 1, 0, imp); setLines(d, xs, m.file); + }, + factory(m, d) { + const js = tick(m.msg, /^export const [\w$]+ = /, "factory"), mk = /^export const ([\w$]+)/.exec(js)[1]; + const row = tick(m.msg, new RegExp(`^export fn ${mk}\\(`), "factory's row"), imp = tick(m.msg, new RegExp(`^import \\{ ${mk} \\}`), "factory's import"); + const jsFile = named(m.msg, /in (\.\/[^\s`,;()]+?\.js)\b/g), rowFile = named(m.msg, ROWFILE), [, cls] = /^new ([\w$.]+)\(…\)/.exec(m.msg); + append(d, jsFile, js); append(d, rowFile, row); + const xs = lines(d, m.file), last = xs.map(l => /^import /.test(l)).lastIndexOf(true); xs.splice(last + 1, 0, imp); + setLines(d, xs.map(l => l.replaceAll(`new ${cls}(`, `${mk}(`)), m.file); + }, + /** ST-1, R10-1 (2026-12-05): a property set JavaScript's way — the helper's module and its `.d.ts` (each in the file the + * message names), its import, and the write the message is about (`video.volume := …`, on its line) replaced by the + * call it prints */ + setter(m, d) { + const js = tick(m.msg, /^export const set[\w$]* = \(/, "setter"), fn = /^export const ([\w$]+)/.exec(js)[1]; + const dts = tick(m.msg, new RegExp(`^export declare function ${fn}\\(`), "setter's .d.ts"), imp = tick(m.msg, new RegExp(`^import \\{ ${fn} \\} from `), "setter's import"), call = tick(m.msg, new RegExp(`^${fn}\\(`), "the call"); + const jsFile = named(m.msg, /in (\.\/[^\s`,;()]+?\.js)\b/g), dtsFile = named(m.msg, /in (\.\/[^\s`,;()]+?\.d\.ts)\b/g); + if (!existsSync(path.join(d, jsFile)) || !read(d, jsFile).includes(`export const ${fn} =`)) append(d, jsFile, js); + if (!existsSync(path.join(d, dtsFile)) || !read(d, dtsFile).includes(`function ${fn}(`)) append(d, dtsFile, dts); + // (the write is the message's head, `a.b := …:`, or — a local's, an effect's input's — the helper's own path, `o.volume`, + // on the first argument of its call) + const jpath = /\) => \{ o((?:\.[\w$]+)+) = v \}/.exec(js)?.[1], first = /^[\w$]+\(([\w$]+)/.exec(call)?.[1]; + replaceWrite(m, d, call, jpath && first ? `${first}${jpath}` : undefined); + const xs = lines(d, m.file); + if (!xs.some(l => l === imp)) { const last = xs.map(l => /^import /.test(l)).lastIndexOf(true); xs.splice(last + 1, 0, imp); setLines(d, xs, m.file); } + }, + /** ST-1, R10-1: the write the message is about replaced by the whole write it prints (`user := { ...user, name: v }`) */ + whole(m, d) { + const name = /^([\w$]+)[.[]/.exec(m.msg)?.[1]; if (!name) throw new Error("no write named"); + replaceWrite(m, d, tick(m.msg, new RegExp(`^${name.replace(/\$/g, "\\$")} := `), "whole write")); + }, + /** INSTANTIATION_NOT_BOUND (re-check 10's B): `x = f(…)` — the call, bound to the name the spelling gives where the + * component is made (before the statement it is in), and read by that name where it was */ + bind(m, d) { + const t = tick(m.msg, /^[\w$]+ = (new )?[\w$.]+\(…\)$/, "`x = f(…)`"), [, name, nw = "", fn] = /^([\w$]+) = (new )?([\w$.]+)\(…\)$/.exec(t); + const xs = lines(d, m.file), l = xs[m.line - 1] ?? "", at = l.indexOf(`${nw}${fn}(`); + if (at < 0) throw new Error(`line ${m.line} has no \`${nw}${fn}(\``); + const end = callEnd(l, at + nw.length + fn.length); + const call = l.slice(at, end), pad = /^(\s*)/.exec(l)[1]; + xs[m.line - 1] = l.slice(0, at) + name + l.slice(end); + xs.splice(m.line - 1, 0, `${pad}${name} = ${call}`); + setLines(d, xs, m.file); + }, + /** SNAPSHOT_ARGUMENT (re-check 10's B): "pass peek(…)" — the argument that reads the value it names, given its snapshot */ + peek(m, d) { + if (!/pass peek\(…\)/.test(m.msg)) throw new Error("no `peek(…)` to pass"); + const [, fn, reads] = /^([\w$.]+)\(…\): the argument for value parameter [\w$]+ reads ([\w$]+)/.exec(m.msg) ?? []; + if (!fn) throw new Error("no argument named"); + const xs = lines(d, m.file), l = xs[m.line - 1] ?? "", at = l.search(new RegExp(`(new )?${fn.replace(/[.$]/g, "\\$&")}\\(`)); + if (at < 0) throw new Error(`line ${m.line} has no call of ${fn}`); + const open = l.indexOf("(", at), end = callEnd(l, open); + const args = splitArgs(l.slice(open + 1, end - 1)), k = args.findIndex(a => new RegExp(`(^|[^\\w$.])${reads}(?![\\w$])`).test(a.text)); + if (k < 0) throw new Error(`no argument of ${fn} reads ${reads}`); + const a = args[k], from = open + 1 + a.start, to = open + 1 + a.end; + xs[m.line - 1] = `${l.slice(0, from)}peek(${l.slice(from, to)})${l.slice(to)}`; + setLines(d, xs, m.file); + }, + }; + /** Where a call that opens at `open` (its `(`, or the name before it) ends: after its `)`. */ + function callEnd(l, from) { + let i = l.indexOf("(", from), depth = 0, q = null; + for (; i < l.length; i++) { const c = l[i]; if (q) { if (c === "\\") i++; else if (c === q) q = null; continue; } if (c === '"' || c === "'" || c === "`") q = c; else if ("([{".includes(c)) depth++; else if (")]}".includes(c)) { depth--; if (!depth) return i + 1; } } + throw new Error("the call does not end on its line"); + } + /** The arguments of a call's text (inside its parentheses), each with where it is. */ + function splitArgs(text) { + const out = []; let depth = 0, q = null, start = 0; + for (let i = 0; i <= text.length; i++) { const c = text[i]; if (q) { if (c === "\\") i++; else if (c === q) q = null; continue; } if (c === '"' || c === "'" || c === "`") q = c; else if (c && "([{".includes(c)) depth++; else if (c && ")]}".includes(c)) depth--; else if ((c === "," && !depth) || i === text.length) { const raw = text.slice(start, i), lead = raw.length - raw.trimStart().length; out.push({ text: raw.trim(), start: start + lead, end: start + lead + raw.trim().length }); start = i + 1; } } + return out; + } + /** The write a message begins with (`a.b := …:`), on the message's line: the statement, up to where its value ends + * (`;`, a closing brace or the line's end at its own depth), replaced by `by`. */ + function replaceWrite(m, d, by, at0) { + const head = /^((?:[\w$]+)(?:\.[\w$]+|\[[^\]]*\])+) := …:/.exec(m.msg)?.[1] ?? at0; if (!head) throw new Error("no path write named"); + const xs = lines(d, m.file), l = xs[m.line - 1] ?? "", at = l.indexOf(`${head} := `); + if (at < 0) throw new Error(`line ${m.line} has no \`${head} := \``); + let i = at + head.length + 4, depth = 0, q = null; + for (; i < l.length; i++) { + const c = l[i]; + if (q) { if (c === "\\") i++; else if (c === q) q = null; continue; } + if (c === '"' || c === "'" || c === "`") q = c; + else if ("([{".includes(c)) depth++; + else if (")]}".includes(c)) { if (!depth) break; depth--; } + else if (c === ";" && !depth) break; + } + xs[m.line - 1] = l.slice(0, at) + by + l.slice(i).replace(/^(?=\})/, " "); + setLines(d, xs, m.file); + } + + return { APPLY, read, write, append, lines, setLines, named, tick }; +} diff --git a/compiler/test/pasted-cases.mjs b/compiler/test/pasted-cases.mjs new file mode 100644 index 000000000..fa116094d --- /dev/null +++ b/compiler/test/pasted-cases.mjs @@ -0,0 +1,267 @@ +// 99 (2026-12-03, re-check 8's C2): "every refusal prints a fix that works when pasted", as a property of the tool and not +// of the apps a review met. Two halves: +// - `inventory()`: every diagnostic code whose message prints a spelling (a backticked piece of a program, a row, an +// import, a command), read off the sources of both checkers and of rx-tsc and rx-declare — the codes this file owes a +// case to; +// - `CASES`: minimal programs, none of them a review's app, each refused with one code in one of its variants, and the +// way its spelling is pasted — the text in the message's backticks, never one written here — applied as the message +// says where, until the program is accepted by rx-tsc and both checkers (some are then run in Chromium too). +// The declarations' codes are met in each place a callee's row can be: a parameter, an options field, an index +// signature, a class's constructor; a local module with a draft and without one; a package with types (rx-tsc's +// generated draft) and without. compiler/test/pasted.mjs runs them, and fails where a code that prints a spelling has +// no case and is not in OPEN, the codes this file has not met yet (each with why): a ratchet, as scripts/structure.json. +import { readFileSync, readdirSync } from "node:fs"; +import path from "node:path"; + +// ---------------------------------------------------------------- the inventory +const SOURCES = { + crate: ["compiler/src/check.rs", "compiler/src/modules.rs", "compiler/src/parse.rs", "compiler/src/overlay.rs", "compiler/src/awaits.rs", "compiler/src/origins.rs", "compiler/src/infer.rs", "compiler/src/extends.rs", "compiler/src/project.rs", "compiler/src/app.rs"], + ref: ["ref/src/check.ts", "ref/src/modules.ts", "ref/src/parse.ts", "ref/src/overlay.ts", "ref/src/infer.ts"], + tools: dir => readdirSync(dir).filter(f => f.endsWith(".js")).map(f => path.join("tooling/rx-language-server/src", f)).concat(["tooling/rx-language-server/bin/tsc.js", "tooling/rx-language-server/bin/declare.js"]), +}; +/** A backticked piece of a message that is something to write: code, a row, an import, a command (not a name alone). */ +const spelling = t => /[({=:<\[]|^(import|export|extend|npx|peek|latest|action|source|effect|try|let|fn|pure|handler|await|guess|errored|loading|use|provide|context|error|component)\b/.test(t) && !/^[A-Z][A-Z_0-9]+$/.test(t); +/** Each code a message is made for, the side that makes it, and whether a message of it prints a spelling. A code is one + * guide/diagnostics.md or spec/99-diagnostics.md documents, met as a string in the sources of a side; whether it prints a + * spelling is read off the text after each place it is met (a heuristic, said as one: the list is what this file owes a + * case to, and a code it lists wrongly is listed OPEN with why). */ +export function inventory(repo) { + const known = new Set([...readFileSync(path.join(repo, "guide/diagnostics.md"), "utf8").matchAll(/^### ([A-Z][A-Z0-9_]+)$/gm)].map(m => m[1]) + .concat([...readFileSync(path.join(repo, "spec/99-diagnostics.md"), "utf8").matchAll(/`([A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+)`/g)].map(m => m[1]))); + const out = new Map(); + const files = [...SOURCES.crate.map(f => ["crate", f]), ...SOURCES.ref.map(f => ["ref", f]), ...SOURCES.tools(path.join(repo, "tooling/rx-language-server/src")).map(f => ["rx-tsc", f])]; + for (const [side, f] of files) { + let s; try { s = readFileSync(path.join(repo, f), "utf8"); } catch { continue; } + for (const m of s.matchAll(/"([A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+|PARSE|UNBOUND|CYCLE)"/g)) { + const code = m[1]; if (!known.has(code)) continue; + const near = s.slice(m.index, m.index + 3000).split("\n").slice(0, 6).join(" "); + const o = out.get(code) ?? { code, sides: new Set(), spells: false }; + o.sides.add(side); + if ([...near.matchAll(/\\?`([^`\\]{3,})\\?`/g)].some(x => spelling(x[1]))) o.spells = true; + out.set(code, o); + } + } + return [...out.values()].sort((a, b) => a.code.localeCompare(b.code)).map(o => ({ ...o, sides: [...o.sides].sort() })); +} + +// ---------------------------------------------------------------- what a case is made of +const TSCONFIG = JSON.stringify({ compilerOptions: { jsx: "preserve", jsxImportSource: "@solidjs/web", strict: true, noImplicitAny: true, target: "ES2022", module: "ESNext", moduleResolution: "Bundler", allowImportingTsExtensions: true, noEmit: true, skipLibCheck: true, lib: ["ES2024", "DOM", "DOM.Iterable"], types: [] }, include: ["**/*.rx", "**/*.d.ts"], exclude: ["node_modules", "dist", ".build"] }, null, 2); +/** A package installed for the case: its code, and its TypeScript types where it ships them (`types: undefined`: none). */ +const pkg = (name, js, types, more = {}) => ({ + [`node_modules/${name}/package.json`]: JSON.stringify({ name, version: "1.0.0", type: "module", exports: { ".": { ...(types !== undefined ? { types: "./index.d.ts" } : {}), default: "./index.js" } }, ...more }), + [`node_modules/${name}/index.js`]: js, + ...(types !== undefined ? { [`node_modules/${name}/index.d.ts`]: types } : {}), +}); +// a bus whose callbacks are kept and called by another export: nothing in the code shows when, so no word is read +const BUS_JS = `const subs = new Set()\nexport const listen = (cb) => { subs.add(cb); return () => { subs.delete(cb) } }\nexport const fire = () => { for (const f of subs) f() }\nexport const watch = (opts) => { subs.add(opts.onFire); return () => { subs.delete(opts.onFire) } }\nexport const bind = (map) => { const fs = Object.values(map); for (const f of fs) subs.add(f); return () => { for (const f of fs) subs.delete(f) } }\nexport class Watcher { constructor(opts) { this.f = opts.onFire; subs.add(this.f) } stop() { subs.delete(this.f) } }\n`; +const BUS_DTS = `export declare function listen(cb: () => void): () => void\nexport declare function fire(): void\nexport declare function watch(opts: { onFire: () => void }): () => void\nexport type KeyMap = { [key: string]: (e: string) => void }\nexport declare function bind(map: KeyMap): () => void\nexport declare class Watcher { constructor(opts: { onFire: () => void }); stop(): void }\n`; +// what computes — a scorer, a fuzzy index — that nothing in the code shows to only compute (it writes a module's counter) +const CALC_JS = `let calls = 0\nexport const score = (s) => { calls++; return s.length * 2 }\nexport const makeThing = (n) => ({ n, calls })\nexport default class Index { constructor(xs) { calls++; this.xs = [...xs] } find(q) { return this.xs.filter(x => x.includes(q)) } }\nexport class Engine { constructor(k) { calls++; this.k = k } run(x) { return x * this.k } }\n`; +const CALC_DTS = `export declare function score(s: string): number\nexport declare function makeThing(n: number): { n: number; calls: number }\nexport default class Index { constructor(xs: string[]); find(q: string): string[] }\nexport declare class Engine { constructor(k: number); run(x: number): number }\n`; +// M-1 (re-check 11): a class's static method in an equation (luxon's `DateTime.fromISO`, decimal.js's `Decimal.max`) — a +// class with a row in its draft, and one with a private constructor, which the draft gives no row (luxon's DateTime): the +// message printed `export pure fn X.(…)`, which no row file can hold +const STATIC_JS = `let calls = 0\nexport class Stamp { static parse(s) { calls++; return s + "!" } constructor(s) { this.s = s } }\nexport class Moment { static of(s) { calls++; return "m:" + s } constructor() { this.t = calls } }\n`; +const STATIC_DTS = `export declare class Stamp { constructor(s: string); static parse(s: string): string }\nexport declare class Moment { private constructor(); static of(s: string): string }\n`; +/** @reactivescript/std as an install has it (10 SV-7f): its package and its modules, rows beside each */ +const STD = (() => { const std = new URL("../../std/", import.meta.url), out = { "node_modules/@reactivescript/std/package.json": readFileSync(new URL("package.json", std), "utf8") }; for (const f of readdirSync(new URL("src/", std))) out[`node_modules/@reactivescript/std/src/${f}`] = readFileSync(new URL(`src/${f}`, std), "utf8"); return out; })(); +const app = body => `export default component App() {\n${body}\n}\n`; +// R9-2 (2026-12-04, re-check 9's d07): a class generic in its callback, which rx-declare drafts by its place +// (`...args: ConstructorParameters<…>`), whose callback runs later (a debouncer); and a fn given a list of callbacks +const LATER_JS = `const subs = new Set()\nexport class Debouncer { constructor(fn, opts) { this.fn = fn; this.wait = opts.wait } maybeExecute(...a) { clearTimeout(this.t); this.t = setTimeout(() => this.fn(...a), this.wait) } }\nexport const keepAll = (fns) => { for (const f of fns) subs.add(f); return () => { for (const f of fns) subs.delete(f) } }\nexport const fire = () => { for (const f of subs) f() }\n`; +const LATER_DTS = `export declare class Debouncer any> { constructor(fn: TFn, opts: { wait: number }); maybeExecute(...args: Parameters): void }\nexport declare function keepAll(fns: (() => void)[]): () => void\nexport declare function fire(): void\n`; + +// the effect that subscribes while open, and whose callback closes it: a loop unless the callback runs later (C-3) +const LOOP = (call, imp = `import { listen, fire, watch, bind, Watcher } from "kit"`) => `${imp}\n${app(` source open := true\n source n := 0\n effect (open) {\n if ($0) {\n let off = ${call}\n return () => { off() }\n }\n }\n
    {open ? "open" : "shut"} {n}
    `)}`; + +/** The declaration family: each refused at its first pass, and pasted until accepted. `take`: which of the spellings a + * message offers is pasted (a message may print two ways through, each of which is tested by a case of its own). */ +export const CASES = [ + // ---- IO_IN_REACTIVE: a call of JavaScript in a view or an equation + { name: "io/package-with-types/import-pure", code: "IO_IN_REACTIVE", take: ["import"], files: { ...pkg("kit", CALC_JS, CALC_DTS), "main.rx": `import { score } from "kit"\n${app(` source s := "ab"\n x = score(s)\n

    {x}

    `)}` }, want: /^4$/ }, + { name: "io/package-with-types/extend-pure", code: "IO_IN_REACTIVE", take: ["extend"], files: { ...pkg("kit", CALC_JS, CALC_DTS), "main.rx": `import { score } from "kit"\n${app(` source s := "ab"\n x = score(s)\n

    {x}

    `)}` } }, + { name: "io/package-with-types/aliased", code: "IO_IN_REACTIVE", take: ["import"], files: { ...pkg("kit", CALC_JS, CALC_DTS), "main.rx": `import { score as rank, makeThing } from "kit"\n${app(` source s := "abc"\n x = rank(s)\n

    {x}

    `)}` }, want: /^6$/ }, + { name: "io/package-without-types", code: "IO_IN_REACTIVE", take: ["command", "hand", "row"], files: { ...pkg("kit", CALC_JS), "main.rx": `import { score } from "kit"\n${app(` source s := "ab"\n x = score(s)\n

    {x}

    `)}` }, want: /^4$/ }, + { name: "io/local-module-without-draft", code: "IO_IN_REACTIVE", take: ["command", "row"], files: { "calc.js": CALC_JS, "calc.d.ts": CALC_DTS, "main.rx": `import { score } from "./calc.js"\n${app(` source s := "ab"\n x = score(s)\n

    {x}

    `)}` }, want: /^4$/ }, + { name: "io/local-module-with-draft", code: "IO_IN_REACTIVE", take: ["row"], files: { "calc.js": CALC_JS, "calc.d.ts": CALC_DTS, "calc.d.rx": "export fn score(s: string): number\n", "main.rx": `import { score } from "./calc.js"\n${app(` source s := "ab"\n x = score(s)\n

    {x}

    `)}` }, want: /^4$/ }, + { name: "io/package-own-declaration", code: "IO_IN_REACTIVE", take: ["extend"], files: { ...pkg("kit", CALC_JS, CALC_DTS), "node_modules/kit/index.d.rx": "export fn score(s: string): number\nexport fn makeThing(n: number): { n: number; calls: number }\n", "main.rx": `import { score } from "kit"\n${app(` source s := "ab"\n x = score(s)\n

    {x}

    `)}` } }, + { name: "io/class-default-import", code: "IO_IN_REACTIVE", take: ["import"], files: { ...pkg("kit", CALC_JS, CALC_DTS), "main.rx": `import Index from "kit"\n${app(` source xs := ["apple", "pear"]\n source q := "p"\n idx = new Index(xs)\n hits = idx.find(q)\n

    {hits.join(",")}

    `)}` }, want: /^apple,pear$/ }, + { name: "io/class-named/extend-pure", code: "IO_IN_REACTIVE", take: ["extend"], files: { ...pkg("kit", CALC_JS, CALC_DTS), "main.rx": `import { Engine } from "kit"\n${app(` source k := 3\n e = new Engine(k)\n y = e.run(2)\n

    {y}

    `)}` } }, + { name: "io/class-static/import-pure", code: "IO_IN_REACTIVE", take: ["import"], files: { ...pkg("kit", STATIC_JS, STATIC_DTS), "main.rx": `import { Stamp } from "kit"\n${app(` source s := "ab"\n x = Stamp.parse(s)\n

    {x}

    `)}` }, want: /^ab!$/ }, + { name: "io/class-static/extend-pure", code: "IO_IN_REACTIVE", take: ["extend"], files: { ...pkg("kit", STATIC_JS, STATIC_DTS), "main.rx": `import { Stamp } from "kit"\n${app(` source s := "ab"\n x = Stamp.parse(s)\n

    {x}

    `)}` }, want: /^ab!$/ }, + { name: "io/class-static/no-row", code: "IO_IN_REACTIVE", take: ["import"], files: { ...pkg("kit", STATIC_JS, STATIC_DTS), "main.rx": `import { Moment } from "kit"\n${app(` source s := "ab"\n x = Moment.of(s)\n

    {x}

    `)}` }, want: /^m:ab$/ }, + { name: "io/bound-makes-state/instantiates", code: "IO_IN_REACTIVE", take: ["extend-instantiates"], files: { ...pkg("kit", CALC_JS, CALC_DTS), "main.rx": `import { makeThing } from "kit"\n${app(` t = makeThing(2)\n

    { console.log(t.n) }}>{t.n}

    `)}` } }, + // R9-1 (2026-12-04, re-check 9): a class whose instance lives with the component, `extend class C instantiates` (the + // io message's first spelling for a class, and the guide's ReactiveMap): constructed, `new` — it was called as a function, + // and the mount threw "Class constructor Engine cannot be invoked without 'new'"; run, in both builds + { name: "io/class-instantiates/draft", code: "IO_IN_REACTIVE", take: ["extend-instantiates"], files: { ...pkg("kit", CALC_JS, CALC_DTS), "main.rx": `import { Engine } from "kit"\n${app(` source n := 0\n e = new Engine(3)\n
    {n}
    `)}` }, steps: [{ click: ".run" }], want: /^6run$/ }, + { name: "io/class-instantiates/own-row", code: "IO_IN_REACTIVE", take: ["row-instantiates"], files: { "calc.js": CALC_JS, "calc.d.ts": CALC_DTS, "calc.d.rx": "export class Engine(k: number): { run: (x: number) => number }\n", "main.rx": `import { Engine } from "./calc.js"\n${app(` source n := 0\n e = new Engine(3)\n
    {n}
    `)}` }, steps: [{ click: ".run" }], want: /^6run$/ }, + { name: "io/class-instantiates/default-import", code: "IO_IN_REACTIVE", take: ["extend-instantiates"], files: { ...pkg("kit", CALC_JS, CALC_DTS), "main.rx": `import Index from "kit"\n${app(` source q := "p"\n source hits := ""\n idx = new Index(["apple", "pear", "fig"])\n
    {hits}
    `)}` }, steps: [{ click: ".find" }], want: /^apple,pearfind$/ }, + { name: "io/in-fn-body", code: "IO_IN_FN", take: ["import"], files: { ...pkg("kit", CALC_JS, CALC_DTS), "main.rx": `import { score } from "kit"\nfn twice(s: string) => score(s) * 2\n${app(` source s := "ab"\n x = twice(s)\n

    {x}

    `)}` }, want: /^8$/ }, + // ---- EFFECT_WRITES_OWN_SOURCE: a callback that writes the effect's input, which only the word `handler` says runs later + { name: "handler/parameter", code: "EFFECT_WRITES_OWN_SOURCE", take: ["extend"], files: { ...pkg("kit", BUS_JS, BUS_DTS), "main.rx": LOOP(`listen(() => { open := false })`) }, steps: [{ click: ".fire" }], want: /shut/ }, + { name: "handler/options-field", code: "EFFECT_WRITES_OWN_SOURCE", take: ["extend"], files: { ...pkg("kit", BUS_JS, BUS_DTS), "main.rx": LOOP(`watch({ onFire: () => { open := false } })`) }, steps: [{ click: ".fire" }], want: /shut/ }, + { name: "handler/index-signature", code: "EFFECT_WRITES_OWN_SOURCE", take: ["extend"], files: { ...pkg("kit", BUS_JS, BUS_DTS), "main.rx": LOOP(`bind({ Escape: (e: string) => { open := false } })`) }, steps: [{ click: ".fire" }], want: /shut/ }, + { name: "handler/index-signature-own-row", code: "EFFECT_WRITES_OWN_SOURCE", take: ["member"], files: { ...pkg("kit", BUS_JS, BUS_DTS), "rx-types/kit.d.rx": "export fn fire(): void\nexport fn bind(map: { [key: string]: (e: string) => void }): () => void\n", "main.rx": LOOP(`bind({ Escape: (e: string) => { open := false } })`, `import { fire, bind } from "kit"`) }, steps: [{ click: ".fire" }], want: /shut/ }, + { name: "handler/class-constructor", code: "EFFECT_WRITES_OWN_SOURCE", take: ["extend"], files: { ...pkg("kit", BUS_JS, BUS_DTS), "main.rx": `import { fire, Watcher } from "kit"\n${app(` source open := true\n effect (open) {\n if ($0) {\n let w = new Watcher({ onFire: () => { open := false } })\n return () => { w.stop() }\n }\n }\n
    {open ? "open" : "shut"}
    `)}` }, steps: [{ click: ".fire" }], want: /shut/ }, + { name: "handler/local-module-with-draft", code: "EFFECT_WRITES_OWN_SOURCE", take: ["member"], files: { "bus.js": BUS_JS, "bus.d.ts": BUS_DTS, "bus.d.rx": "export fn listen(cb: () => void): () => void\nexport fn fire(): void\n", "main.rx": LOOP(`listen(() => { open := false })`, `import { listen, fire } from "./bus.js"`) }, steps: [{ click: ".fire" }], want: /shut/ }, + { name: "handler/local-module-without-draft", code: "EFFECT_WRITES_OWN_SOURCE", take: ["command", "member"], files: { "bus.js": BUS_JS, "bus.d.ts": BUS_DTS, "main.rx": LOOP(`listen(() => { open := false })`, `import { listen, fire } from "./bus.js"`) }, steps: [{ click: ".fire" }], want: /shut/ }, + { name: "handler/package-without-types", code: "EFFECT_WRITES_OWN_SOURCE", take: ["command", "hand", "before"], files: { ...pkg("kit", BUS_JS), "main.rx": LOOP(`listen(() => { open := false })`, `import { listen, fire } from "kit"`) }, steps: [{ click: ".fire" }], want: /shut/ }, + // ---- REACTIVE_WRITE_IN_OWNED_SCOPE: a closure that writes, given where the component is made + { name: "owned/parameter", code: "REACTIVE_WRITE_IN_OWNED_SCOPE", take: ["extend", "extend-replace"], files: { ...pkg("kit", BUS_JS, BUS_DTS), "main.rx": `import { listen, fire } from "kit"\n${app(` source n := 0\n off = listen(() => { n := n + 1 })\n
    {n}
    `)}` }, steps: [{ click: ".fire" }], want: /^1fire$/ }, + { name: "owned/options-field", code: "REACTIVE_WRITE_IN_OWNED_SCOPE", take: ["extend", "extend-replace"], files: { ...pkg("kit", BUS_JS, BUS_DTS), "main.rx": `import { watch, fire } from "kit"\n${app(` source n := 0\n off = watch({ onFire: () => { n := n + 1 } })\n
    {n}
    `)}` }, steps: [{ click: ".fire" }], want: /^1fire$/ }, + // R9-2 (2026-12-04, re-check 9's d07, d06): a class drafted by its place, whose row's parameter is the rest (`...args: + // handler`, written as the row writes it: it was PARSE), and a list of callbacks (the parameter's word, `fns: handler`: it + // printed `{ 0: handler }`, no row's text) + { name: "owned/class-by-place", code: "REACTIVE_WRITE_IN_OWNED_SCOPE", take: ["extend", "extend-replace"], files: { ...pkg("kit", LATER_JS, LATER_DTS), "main.rx": `import { Debouncer } from "kit"\n${app(` source applied := ""\n d = new Debouncer((q: string) => { applied := q }, { wait: 20 })\n
    {applied}
    `)}` }, steps: [{ click: ".go", then: 300 }], want: /^xgo$/ }, + { name: "owned/class-by-place/instantiates", code: "REACTIVE_WRITE_IN_OWNED_SCOPE", take: ["extend-instantiates", "extend-replace"], files: { ...pkg("kit", LATER_JS, LATER_DTS), "main.rx": `import { Debouncer } from "kit"\n${app(` source applied := ""\n source runs := 0\n d = new Debouncer((q: string) => { applied := q; runs := runs + 1 }, { wait: 20 })\n
    {applied} {runs}
    `)}` }, steps: [{ click: ".go", then: 300 }], want: /^y 1go$/ }, + { name: "owned/list-of-callbacks", code: "REACTIVE_WRITE_IN_OWNED_SCOPE", take: ["extend", "extend-replace"], files: { ...pkg("kit", LATER_JS, LATER_DTS), "main.rx": `import { keepAll, fire } from "kit"\n${app(` source a := 0\n source b := 0\n off = keepAll([() => { a := a + 1 }, () => { b := b + 10 }])\n
    {a} {b}
    `)}` }, steps: [{ click: ".fire" }], want: /^1 10fire$/ }, + // R9-3 (2026-12-04, re-check 9's d06e8): an action called in an expression closure given to a JS fn — the parameter's + // word (ACTION_CALLED_IN_OWNED_SCOPE printed nothing to write) + { name: "action/closure-given", code: "ACTION_CALLED_IN_OWNED_SCOPE", take: ["extend", "extend-replace"], files: { ...pkg("kit", BUS_JS, BUS_DTS), "main.rx": `import { listen, fire } from "kit"\n${app(` source n := 0\n action bump() { n := n + 1 }\n off = listen(() => bump())\n
    {n}
    `)}` }, steps: [{ click: ".fire" }], want: /^1fire$/ }, + // R9-3 (2026-12-04, re-check 9's d06): @solid-primitives/history's README, a closure that answers a closure that writes — + // no row word says that of what a callback answers; the message prints the helper that makes it (the draft keeps the + // list, `Many>`: the array form was TS2345) + { name: "owned/accessor-answers-callback", code: "REACTIVE_WRITE_IN_OWNED_SCOPE", take: ["helper"], files: { "main.rx": `import { createUndoHistory } from "@solid-primitives/history"\n${app(` source title := "a"\n source color := "black"\n history = createUndoHistory([\n () => { let t = title; return () => { title := t } },\n () => { let c = color; return () => { color := c } }\n ])\n
    {title} {color} {history.canUndo ? "undo" : "none"}
    `)}` }, steps: [{ click: ".t" }, { click: ".c" }, { click: ".undo" }, { click: ".undo" }], want: /^a black none/ }, + // ---- IMPORT_ROW_MISMATCH: `pure` at the import of a row that says io + { name: "row-mismatch/local-module", code: "IMPORT_ROW_MISMATCH", take: ["row"], files: { "calc.js": CALC_JS, "calc.d.ts": CALC_DTS, "calc.d.rx": "export fn score(s: string): number\n", "main.rx": `import pure { score } from "./calc.js"\n${app(` source s := "ab"\n x = score(s)\n

    {x}

    `)}` }, want: /^4$/ }, + // ---- UNBOUND: `new` of what no import gives — the factory the message prints, then its own declaration + // (2026-12-02, round D1: a class of the platform's is std's, by its own name — 10 SV-7f; made where an effect runs) + { name: "unbound/new-of-a-global", code: "UNBOUND", take: ["std"], files: { ...STD, "main.rx": app(` source n := 0\n effect () { let seen = new Set(["a", "b", "a"]); n := seen.size }\n

    {n}

    `) }, want: /^2$/ }, +]; + +export const TSCONFIG_TEXT = TSCONFIG; +/** The guide's programs are written without types on a parameter (`fn twice(x) => …`): TypeScript's `noImplicitAny` is off + * for them, which says nothing of what a paste does. */ +export const TSCONFIG_GUIDE = TSCONFIG.replace('"noImplicitAny": true', '"noImplicitAny": false'); + +/** The codes that print a spelling and have no case here yet, each with why: what is left of the property to show. */ +export const OPEN = new Map([ + ["PENDING_NEVER", "the statement it prints (`affects x`) goes where the message says in words — the first statement of the action it names, with its line: compiler/test/callbacks.mjs pastes it there and runs it in both builds"], + ["TWO_ASYNC_WRITERS", "the one action it prints takes what tells the two places apart, which is the program's (an argument, which value): `action loadX(which: string) { … }` is a form, and compiler/test/async-writers.mjs writes and runs it"], + ["ROW_NARROWER_THAN_INFERRED", "the row's words a value has (`pending`, `fails(E)`) are said one a message, and which the program means to discharge where it is read is its own"], + ["UNGUARDED_SNAPSHOT", "a value that has none yet on its first load is shown under a `loading` region the program's view places: the message says which, in words"], + ["ARGUMENT_COUNT", "a mistake the checker refuses, whose fix is the program's intent (which name, which value, which region): the message says what to change in words, and no one spelling is the fix"], + ["ASYNC_OUTSIDE_LOADING_BOUNDARY", "its guide program is two modules; a case is still to write: the `loading` region it prints is placed by the view's own structure"], + ["ASYNC_STORE_SETTER", "a mistake the checker refuses, whose fix is the program's intent (which name, which value, which region): the message says what to change in words, and no one spelling is the fix"], + ["ASYNC_WATERFALL", "no guide program; the `let [a, b] = await all([…])` it prints needs a case of two loads"], + ["CLIENT_IN_SERVER", "a server/client split (12 SF-5) the guide shows across modules; a case is still to write"], + ["CLIENT_NOT_AWAITED", "as CLIENT_IN_SERVER"], + ["CLIENT_QUESTION_UNHELD", "as CLIENT_IN_SERVER"], + ["COMPONENT_AS_VALUE", "a mistake the checker refuses, whose fix is the program's intent (which name, which value, which region): the message says what to change in words, and no one spelling is the fix"], + ["CONTENT_MODEL", "the browser's HTML parser's rule: the message says which element moves, in words"], + ["CONTEXT_NOT_FOUND", "a mistake the checker refuses, whose fix is the program's intent (which name, which value, which region): the message says what to change in words, and no one spelling is the fix (where the provision goes)"], + ["CYCLE", "a mistake the checker refuses, whose fix is the program's intent (which name, which value, which region): the message says what to change in words, and no one spelling is the fix"], + ["DEAD_TYPED_BOUNDARY", "a mistake the checker refuses, whose fix is the program's intent (which name, which value, which region): the message says what to change in words, and no one spelling is the fix"], + ["DECLARATION_MISMATCH", "rx-tsc: TypeScript's reason for a row the module's types do not hold — the row is the person's to correct; TypeScript names the part"], + ["DECLARATION_VERSION", "rx-tsc: the pin and the installed version disagree — re-run the command it prints (`rx-declare`), which a case of two installs would show"], + ["DISPOSER_DROPPED", "a mistake the checker refuses, whose fix is the program's intent (which name, which value, which region): the message says what to change in words, and no one spelling is the fix"], + ["DRAFT_ESCAPES", "a mistake the checker refuses, whose fix is the program's intent (which name, which value, which region): the message says what to change in words, and no one spelling is the fix"], + ["DRAFT_WRITE_OUTSIDE_DRAFT", "a mistake the checker refuses, whose fix is the program's intent (which name, which value, which region): the message says what to change in words, and no one spelling is the fix"], + ["DUPLICATE_DECLARATION", "a mistake the checker refuses, whose fix is the program's intent (which name, which value, which region): the message says what to change in words, and no one spelling is the fix"], + ["DUPLICATE_KEY", "a mistake the checker refuses, whose fix is the program's intent (which name, which value, which region): the message says what to change in words, and no one spelling is the fix"], + ["DUPLICATE_WIRE_ID", "server wire ids (SV-5): multi-module, a case is still to write"], + ["EFFECT_RELAY_TEAR", "a mistake the checker refuses, whose fix is the program's intent (which name, which value, which region): the message says what to change in words, and no one spelling is the fix (state derived through an apply)"], + ["ENTRY_NAMED_IMPORT", "rx-tsc, a host's entry: a case of a router's host is still to write"], + ["GUESS_AFTER_AWAIT", "a case is still to write (the guess moved before the `await` it prints)"], + ["GUESS_ON_DEFERRED", "a mistake the checker refuses, whose fix is the program's intent (which name, which value, which region): the message says what to change in words, and no one spelling is the fix"], + ["GUESS_WHILE_LOADING", "the `disabled={pending? x}` it prints needs the element the program means; a case is still to write"], + ["HOST_VIEW_STALE", "rx-tsc, a host declaration out of date: the command it prints (`rx-declare --host --sync`) is the way through; a case of a router's tree is still to write"], + ["INVALID_AFFECTS_TARGET", "a mistake the checker refuses, whose fix is the program's intent (which name, which value, which region): the message says what to change in words, and no one spelling is the fix"], + ["INVALID_REFRESH_TARGET", "a mistake the checker refuses, whose fix is the program's intent (which name, which value, which region): the message says what to change in words, and no one spelling is the fix"], + ["MISSING_AWAIT", "a mistake the checker refuses, whose fix is the program's intent (which name, which value, which region): the message says what to change in words, and no one spelling is the fix"], + ["MODULE_CYCLE", "a mistake the checker refuses, whose fix is the program's intent (which name, which value, which region): the message says what to change in words, and no one spelling is the fix"], + ["MODULE_NOT_FOUND", "a mistake the checker refuses, whose fix is the program's intent (which name, which value, which region): the message says what to change in words, and no one spelling is the fix (which file)"], + ["NESTED_NOT_RENDERED", "a factory's placement word (MO-11i) on a library's component; a case of a JS factory is still to write"], + ["NOT_AN_ERROR_CLASS", "the guide's program reads a value that fails with Error under a boundary typed `Missing`: declaring Missing (the spelling printed) leaves UNHANDLED_FAILURE, which the program's own intent settles"], + ["NOT_A_CONTEXT", "a mistake the checker refuses, whose fix is the program's intent (which name, which value, which region): the message says what to change in words, and no one spelling is the fix"], + ["NOT_EXPORTED", "a name the declaration lacks: the row to add is the person's (what the export is)"], + ["PRE_OF_NON_REACTIVE", "a mistake the checker refuses, whose fix is the program's intent (which name, which value, which region): the message says what to change in words, and no one spelling is the fix"], + ["PROBE_BESIDE_HELD_READ", "a mistake the checker refuses, whose fix is the program's intent (which name, which value, which region): the message says what to change in words, and no one spelling is the fix"], + ["REF_PART_CALLED", "its guide program is two modules; a case is still to write"], + ["REGION_ESCAPE", "a mistake the checker refuses, whose fix is the program's intent (which name, which value, which region): the message says what to change in words, and no one spelling is the fix"], + ["RESULT_AS_VALUE", "a mistake the checker refuses, whose fix is the program's intent (which name, which value, which region): the message says what to change in words, and no one spelling is the fix (which field is meant)"], + ["SERVER_CAPTURE", "a mistake the checker refuses, whose fix is the program's intent (which name, which value, which region): the message says what to change in words, and no one spelling is the fix"], + ["SERVER_ONLY", "as CLIENT_IN_SERVER"], + ["SERVER_WRITE", "a mistake the checker refuses, whose fix is the program's intent (which name, which value, which region): the message says what to change in words, and no one spelling is the fix"], + ["SETTLED_CLEANUP_UNOWNED", "a mistake the checker refuses, whose fix is the program's intent (which name, which value, which region): the message says what to change in words, and no one spelling is the fix"], + ["SHADOWED_IMPORT", "its guide program is two modules; the `import { x as … }` it prints needs the new name, the person's"], + ["SNAPSHOT_IN_EFFECT", "advice, not a refusal: nothing is refused to paste over"], + ["KEPT_ROW", "advice, not a refusal: nothing is refused to paste over (compiler/test/aliasing.mjs pastes the declarations and writes it prints, holds it silent and accepted by rx-tsc, and runs it in both builds)"], + ["UNSEEN_WRITE", "advice, not a refusal: nothing is refused to paste over (compiler/test/told.mjs pastes the `onFlush` spelling and holds it silent)"], + ["SOURCE_CONTEXT", "the provision written as actions is the program's design: the message prints its shape"], + ["STALE_CAPTURE", "a mistake the checker refuses, whose fix is the program's intent (which name, which value, which region): the message says what to change in words, and no one spelling is the fix (which plain argument the action takes)"], + ["STYLE_PLACEMENT", "a mistake the checker refuses, whose fix is the program's intent (which name, which value, which region): the message says what to change in words, and no one spelling is the fix"], + ["STYLE_SCOPE", "a mistake the checker refuses, whose fix is the program's intent (which name, which value, which region): the message says what to change in words, and no one spelling is the fix"], + ["UNVERIFIED_ROW", "rx-tsc --rx-strict: the command it prints (`rx-verify --record`) runs the package; a case is still to write"], + ["VIEW_FN_EXPECTED", "its guide program is two modules; a case is still to write"], + ["VIEW_FN_MISPLACED", "a mistake the checker refuses, whose fix is the program's intent (which name, which value, which region): the message says what to change in words, and no one spelling is the fix"], + ["VIEW_NOT_SHOWN", "a mistake the checker refuses, whose fix is the program's intent (which name, which value, which region): the message says what to change in words, and no one spelling is the fix"], + ["WIRE_VALUE", "a mistake the checker refuses, whose fix is the program's intent (which name, which value, which region): the message says what to change in words, and no one spelling is the fix"], +]); + +// ---------------------------------------------------------------- the respellings: guide/diagnostics.md's `before` programs +// Each code's first `rx before` block of the guide (`k`: which of them, counted over the guide), refused with its code, +// pasted by what the message prints: `paste(m, src, t)` answers the module's new text from the message (`m.msg`, `m.line`) +// and its backticked spellings `t`, and throws where the spelling it is to paste is not printed. +const API_JS = `export const fetchIssue = async (id) => ({ title: "t" + id })\nexport const postRename = async (id, t) => {}\nexport const post = async (x) => "ok"\nexport const load = async (n) => n\nexport const fetchUser = async (id) => "u" + id\nexport const checkout = async () => 1\nexport const fetchDone = async () => ""\nexport const postMove = async () => ""\nexport const fetchData = async (id) => id\n`; +const API_ROWS = `export pure fn fetchIssue(id: number): Promise<{ title: string }>\nexport fn postRename(id: number, t: string): Promise\nexport fn post(x?: string): Promise\nexport pure fn load(n: number): Promise\nexport pure fn fetchUser(id: number): Promise\nexport fn checkout(): Promise\nexport pure fn fetchDone(): Promise\nexport fn postMove(): Promise\nexport pure fn fetchData(id: number): Promise\n`; +const API = { "api.js": API_JS, "api.d.rx": API_ROWS }; +const need = (t, re, what) => { const x = t.find(y => re.test(y)); if (!x) throw new Error(`no ${what} in its backticks`); return x; }; +const at = (src, line, f) => src.split("\n").map((l, i) => i === line - 1 ? f(l) : l).join("\n"); +const sub1 = (src, from, to) => { if (!src.includes(from)) throw new Error(`the program has no ${JSON.stringify(from)}`); return src.replace(from, to); }; +export const GUIDE = [ + // ---- habits from JavaScript, React and Solid (PARSE and its kinds) + { k: 0, code: "PARSE", paste: (m, s, t) => { need(t, /^\{errored … \{ … \}\}$/, "`{errored … { … }}`"); return s.replace(/^(\s*)(errored fallback\(e\) \{[^\n]*\} \{\n[\s\S]*?\n\1\})/m, "$1{$2}"); } }, + { k: 1, code: "JS_LOCAL", paste: (m, s, t) => { const tpl = need(t, /^x = …$/, "`x = …`"); return at(s, m.line, l => l.replace(/\b(?:const|let) ([\w$]+) = /, (_, n) => tpl.replace("x", n).replace(" …", " "))); } }, + { k: 2, code: "JS_FUNCTION", paste: (m, s, t) => { need(t, /^fn f\(x\) => …$/, "`fn f(x) => …`"); return s.replace(/^function ([\w$]+)\(([^)]*)\) \{ return (.*) \}$/m, "fn $1($2) => $3"); } }, + { k: 3, code: "JS_RETURN", paste: (m, s) => { if (!/a component has no `return`/.test(m.msg)) throw new Error("no word of what to write"); return s.replace(/^(\s*)return /m, "$1"); } }, + { k: 4, code: "JS_API", paste: (m, s, t) => { const tpl = need(t, /^source x := …$/, "`source x := …`"); const [, n, set, init] = /\[([\w$]+), ([\w$]+)\] = createSignal\(([^)]*)\)/.exec(s); return s.replace(/\[[\w$]+, [\w$]+\] = createSignal\([^)]*\)/, tpl.replace("x", n).replace("…", init)).replace(new RegExp(`${set}\\(([^()]*)\\)`, "g"), `${n} := $1`); } }, + { k: 5, code: "MARKUP_AS_EXPRESSION", paste: (m, s, t) => { need(t, /^\{for x in xs \{ \}\}$/, "`{for x in xs { … }}`"); return s.replace(/\{([\w$]+)\.map\(\(([\w$]+)\) => (<[\s\S]*?>)\)\}/, "{for $2 in $1 { $3 }}"); } }, + { k: 6, code: "MARKUP_AS_EXPRESSION", paste: (m, s, t) => { need(t, /^\{if c \{ \} else \{ \}\}$/, "`{if c { … } else { … }}`"); return s.replace(/\{([\w$]+) \? (.*?<\/b>) : (.*?<\/i>)\}/, "{if $1 { $2 } else { $3 }}"); } }, + { k: 7, code: "TEXT_AT_TOP", paste: (m, s, t) => { need(t, /^<>.*<\/>$/, "`<>… `"); return at(s, m.line, l => l.replace(/^(\s*)(.*)$/, "$1<>$2")); } }, + { k: 8, code: "CALL_AT_TOP", paste: (m, s, t) => { need(t, /^effect \(x\) \{ … \}$/, "`effect (x) { … }`"); return s.replace(/onSettled\(\(\) => \{ (.*) \}\)/, "effect () { $1 }"); } }, + { k: 9, code: "TYPE_AS_NAME", paste: (m, s, t) => { const n = /^([\w$]+) = …$/.exec(need(t, /^[\w$]+ = …$/, "`name = …`"))[1]; return s.replace(/^(\s*)type = /m, `$1${n} = `).replace(/\{type\}/g, `{${n}}`); } }, + { k: 10, code: "ASSIGNMENT", paste: (m, s, t) => sub1(s, "n += 1", need(t, /^n := n \+ 1$/, "`n := n + 1`")) }, + { k: 11, code: "REACTIVE_WRITE_IN_OWNED_SCOPE", paste: (m, s, t) => { need(t, /^\(\) => \{ [\w$]+ := … \}$/, "`() => { x := … }`"); return s.replace(/\(\) => ([\w$]+ := [^}]*?)\}>/, "() => { $1 }}>"); } }, + { k: 12, code: "REACTIVE_WRITE_IN_OWNED_SCOPE", paste: (m, s, t) => { const head = need(t, /^action [\w$]+\(.*\) \{ … \}$/, "`action …(…) { … }`"), name = /^action ([\w$]+)/.exec(head)[1]; return s.replace(/^(\s*)([\w$]+) = \(\) => \{ (.*) \}$/m, (_, sp, bind, body) => `${sp}${head.replace("{ … }", `{ ${body} }`)}\n${sp}${bind} = ${name}`); } }, // (declared in the component, and its name written where the closure was) + // ---- writes and their readers + { k: 16, code: "MUTATION_IN_PLACE", paste: (m, s, t) => { const tpl = need(t, /^[\w$]+ := v => \[\.\.\.v, x\]$/, "`xs := v => [...v, x]`"); const [, xs, x] = /([\w$]+)\.push\(([^()]*)\)/.exec(s); return s.replace(`${xs}.push(${x})`, tpl.replace(/^[\w$]+/, xs).replace(/, x\]$/, `, ${x}]`)); } }, + { k: 18, code: "MUTATION_IN_PLACE", paste: (m, s, t) => { need(t, /\.toSorted\(…\)$/, "`….toSorted(…)`"); return s.replace(".sort()", ".toSorted()"); } }, + { k: 21, code: "STALE_OWN_READ", paste: (m, s, t) => { need(t, /^let v = …; [\w$]+ := v$/, "`let v = …; x := v`"); return s.replace(/count := (count \+ 1); seen := count/, "let v = $1; count := v; seen := v"); } }, + { k: 22, code: "STALE_WRITE_BACK", files: API, paste: (m, s, t) => { need(t, /^[\w$]+ := v => …$/, "`x := v => …`"); return s.replace("log := before + x", "log := v => v + x"); } }, + // 06 AC-1m (round D1): an action's call after the closure's \`await\` — the closure's steps as the action it prints, the closure its call + { k: 23, code: "AWAIT_THEN_CALL", files: { "api.js": "export const search = async (q) => q\n", "api.d.rx": "export fn search(q: string): Promise\n" }, paste: (m, s, t) => { const act = need(t, /^action handle\(e\) \{.*\}$/, "`action handle(e) { … }`"), call = need(t, /^\(e\) => handle\(e\)$/, "`(e) => handle(e)`"); const body = act.slice(act.indexOf(") ") + 2); return s.split("\n").map(l => l.includes(body) ? ` ${act}\n${l.replace(`(e) => ${body}`, call)}` : l).join("\n"); } }, + { k: 25, code: "LATE_CALLBACK_WRITE", files: { "api.js": "export const load = async (w) => w\n", "api.d.ts": "export declare const load: (which: string) => Promise\n" }, paste: (m, s) => { const x = /write `([^`]*)` in place of `([^`]*)`/.exec(m.msg); if (!x) throw new Error("no `write … in place of …`"); return s.replace(x[2], x[1]); } }, // re-check 15's F-A + { k: 26, code: "STALE_NEXT_READ", files: API, paste: (m, s, t) => { const l = need(t, /^latest [\w$]+$/, "`latest x`"); return s.replace("let n = seq + 1", `let n = ${l} + 1`); } }, + { k: 27, code: "STALE_NEXT_READ", files: API, paste: (m, s, t) => sub1(s, "likes := likes + 1", need(t, /^likes := v => v \+ 1$/, "`likes := v => v + 1`")) }, // round C1, N13-4: after an \`await\`, the functional write printed from the write + { k: 30, code: "SNAPSHOT_INITIALIZER", paste: (m, s, t) => { const x = need(t, /^source [\w$]+ := peek\(.*\)$/, "`source x := peek(…)`"); return at(s, m.line, l => l.replace(/source [\w$]+ := .*$/, x)); } }, + { k: 31, code: "SNAPSHOT_ARGUMENT", paste: (m, s, t) => { need(t, /^ref$/, "`ref`"); const p = /parameter ([\w$]+)/.exec(m.msg)[1]; return s.replace(new RegExp(`fn watch\\(${p}\\)`), `fn watch(ref ${p})`); } }, + { k: 32, code: "SNAPSHOT_KEPT", paste: (m, s, t) => { need(t, /^source [\w$]+ := peek [\w$]+$/, "`source x := peek n`"); return s.replace(/^(\s*)([\w$]+) = peek ([\w$]+)$/m, "$1source $2 := peek $3"); } }, + { k: 37, code: "HELD_WRITE", files: API, paste: (m, s, t) => { need(t, /^guess [\w$]+ := …$/, "`guess x := …`"); return s.replace('status := "saving"', 'guess status := "saving"'); } }, + { k: 38, code: "AWAIT_IN_EXPRESSION", files: API, paste: (m, s, t) => { need(t, /^let v = await [\w$]+\(…\)$/, "`let v = await f(…)`"); return s.replace("try { status := `got ${await checkout()}` } catch {}", "try { let v = await checkout(); status := `got ${v}` } catch {}"); } }, + { k: 39, code: "AWAIT_IN_EXPRESSION", files: API, paste: (m, s, t) => { const x = need(t, /^source x = …$/, "`source x = …`"); return s.replace(/source ([\w$]+) := await/, `${x.replace("x", "$1").replace(" …", "")} await`); } }, + { k: 40, code: "GUESS_OUTSIDE_HOLD", paste: (m, s, t) => { if (/if this is [\w$]+'s new value, write it/.test(m.msg)) { const w = need(t, /^[\w$]+ := …$/, "`x := …`"); return s.replace(/guess ([\w$]+) := /, `${w.replace(" …", " ")}`); } const a = need(t, /^action [\w$]+\(v\) \{ guess … \}$/, "`action …(v) { guess … }`"), name = /^action ([\w$]+)/.exec(a)[1]; return s.replace(/^(\s*)effect \(draft\) \{ guess saved := \$0 \}$/m, `$1${a.replace("guess …", "guess saved := v")}\n$1effect (draft) { ${name}($0) }`); } }, + { k: 44, code: "HOOK_CALLBACK", paste: (m, s, t) => { need(t, /^onFlush\(\(\) => \{ … \}\)$/, "`onFlush(() => { … })`"); return s.replace("onFlush(open)", "onFlush(() => { log(open) })"); } }, + { k: 46, code: "UNTIL_PREDICATE", paste: (m, s, t) => { need(t, /^until\(\(\) => e\)$/, "`until(() => e)`"); return s.replace(/until\(([\w$]+)\)/, "until(() => $1)"); } }, + // ---- failures + { k: 54, code: "UNHANDLED_FAILURE", files: API, paste: (m, s) => { const x = /write `([^`]*)` in place of `([^`]*)`/.exec(m.msg); if (!x) throw new Error("no `write … in place of …`"); return sub1(s, x[2], x[1]); } }, // (re-check 15's c05: the reader wrapped as printed) + { k: 56, code: "UNCAUGHT_ACTION_FAILURE", files: API, paste: (m, s, t) => { need(t, /^try \{ … \} catch \(e\) \{ … \}$/, "`try { … } catch (e) { … }`"); return s.replace(/let r = await post\(\)\n(\s*)saved := r/, "try { let r = await post(); saved := r } catch (e) { saved := e.message }"); } }, + { k: 57, open: "the guide's program reads a value that fails with Error under a boundary typed `Missing`: declaring Missing (the spelling printed) leaves UNHANDLED_FAILURE, which the program's own intent settles", code: "NOT_AN_ERROR_CLASS", files: API, paste: (m, s, t) => { const e = need(t, /^error [\w$]+\(…\)$/, "`error X(…)`"); return `${e.replace("(…)", "")}\n${s}`; } }, + { k: 28, code: "ACTION_ANSWER_HELD", files: API, paste: (m, s, t) => { const w = need(t, /^: [\w$]+$/, "`: T`"); if (!/leave the result out/.test(m.msg)) throw new Error("no word of what to write"); return s.replace(`add(t: string)${w} {`, "add(t: string) {").replace(/\n\s*return 1\n/, "\n"); } }, + { k: 55, code: "CATCH_NOT_ON_AWAIT", files: API, paste: (m, s, t) => { need(t, /^errored fallback\(e\) \{ … \} \{ … \}$/, "`errored fallback(e) { … } { … }`"); return s.replace(/^(\s*)

    \{user catch \(e\) => "unknown"\}<\/p>$/m, "$1{errored fallback(e) {

    unknown

    } {

    {user}

    }}"); } }, + { k: 58, open: "the words a value has (`pending`, `fails(E)`) are said one a message, and which the program means to discharge where it is read is its own", code: "ROW_NARROWER_THAN_INFERRED", files: API, paste: (m, s, t) => { const w = /its value is also `(\w+)`/.exec(m.msg)?.[1]; if (!w) throw new Error("no word it is also"); return s.replace("user: lane string", `user: ${w} lane string`); } }, + { k: 59, open: "a value that has none yet on its first load is shown under a `loading` region the view places: the message says which, in words", code: "UNGUARDED_SNAPSHOT", files: API, paste: (m, s, t) => { need(t, /^try \{ … \} catch \(e\) \{ … \}$/, "`try { … } catch (e) { … }`"); return s.replace("onClick={() => { log(user) }}", "onClick={() => { try { log(user) } catch (e) { log(e) } }}"); } }, + { k: 62, code: "LOADING_ON_OUTSIDE_HOLD", files: API, paste: (m, s, t) => { const l = need(t, /^latest [\w$]+$/, "`latest x`"); return s.replace("{loading fallback {

    spinner

    } {

    {data}

    }}", `{loading fallback {

    spinner

    } {

    {${l}}

    }}`); } }, + { k: 63, code: "UNBOUND", paste: (m, s, t) => { need(t, /^\{ \.\.\.a, \.\.\.b \}$/, "`{ ...a, ...b }`"); return s.replace(/Object\.assign\((.+?), (\{[^{}]*\})\)/, "{ ...$1, ...$2 }"); } }, + // ---- names, components, contexts + { k: 66, code: "UNBOUND", paste: (m, s, t) => { need(t, /^component [\w$]+\(props: \{ … \}\)$/, "`component X(props: { … })`"); return s.replace("component Lane()", "component Lane(props: { col: string })"); } }, + { k: 71, code: "INSTANTIATION_NOT_BOUND", paste: (m, s, t) => { need(t, /^x = [\w$]+\(…\)$/, "`x = f(…)`"); return s.replace(/^(\s*)

    \{counter\(n\)\}<\/p>$/m, "$1c = counter(n)\n$1

    {c}

    "); } }, + { k: 73, code: "UNSTABLE_LIST_IDENTITY", paste: (m, s, t) => { need(t, /^x key id = …$/, "`x key id = …`"); return s.replace(/^(\s*)view = map/m, "$1view key id = map"); } }, + { k: 78, code: "CONTEXT_AS_VALUE", paste: (m, s, t) => { const u = need(t, /^use [\w$]+$/, "`use x`"); return s.replace("{theme}", `{${u}}`); } }, + { k: 79, code: "GENERIC_CONTEXT", paste: (m, s, t) => { const c = need(t, /^context [\w$]+: \(/, "`context …: (…) => …`"); return s.replace(/^context row: .*$/m, c); } }, + { k: 83, code: "FN_SHOWN", paste: (m, s, t) => { need(t, /^\{[\w$]+\(…\)\}$/, "`{f(…)}`"); return s.replace("

    {total}

    ", "

    {total(xs)}

    "); } }, + { k: 84, code: "TOP_LEVEL_MARKUP", paste: (m, s, t) => { need(t, /^export default component App\(\) \{ … \}$/, "`export default component App() { … }`"); return `export default component App() {\n${s.trim().split("\n").map(l => ` ${l}`).join("\n")}\n}\n`; } }, + // re-check 14's F3: Solid's accessor form at a \`ref\` parameter (TanStack's \`useQuery(() => ({ … }))\`), the record printed + { k: 103, code: "REF_GIVEN_ACCESSOR", files: { "api.js": "export const fetchTodo = async (id) => \"todo \" + id\n", "query.js": "export const useQuery = (o) => ({ get data() { return o().queryKey.join(\":\") } })\n" }, paste: (m, s, t) => { const r = need(t, /^useQuery\(\{ .* \}\)$/, "`useQuery({ … })`"); return s.replace(/useQuery\(\(\) => \(\{ .* \}\)\)/, r); } }, +]; diff --git a/compiler/test/pasted.mjs b/compiler/test/pasted.mjs new file mode 100644 index 000000000..33600216c --- /dev/null +++ b/compiler/test/pasted.mjs @@ -0,0 +1,355 @@ +// 99, the seventh review's C2 (2026-12-02): every refusal message the review's apps met prints a spelling that works +// when it is pasted as printed. Each app is its first pass (compiler/test/pasted//main.rx.txt, as the review's +// sub-agents wrote it: r7/apps/*/main.v1.rx.txt), refused; this takes the spelling out of each message — the text in +// its backticks, never one written here — puts it where the message says, and asks again, until rx-tsc (TypeScript and +// the crate) and both checkers accept the program; then it runs in Chromium, on Solid's development and production +// builds, and what the page shows is what the app is for. The review counted 15 causes of refusal over 13 apps, 9 of +// whose printed spellings did not work: here each cause is met in the app that met it. +// - b02 (@solid-primitives/drag-drop): a choice laid out by Prettier (`?` begins a line), two SNAPSHOT_ARGUMENTs +// (`peek(…)`), the drag's `onDragEnd` (an `extend` row, since 2026-12-02: a field carries its word), and +// `` (the JS hand-back the message prints, two files of one line). +// - b03 (@solid-primitives/scheduled): `debounce` bound where the component is made (`extend fn debounce instantiates`). +// - b04 (@solid-primitives/websocket): `patch`'s draft (the field written `handler (draft draft: S, msg: T) => void` in +// the row, written whole over the draft). Not run: it needs a WebSocket server (the review's `ws` server ran it in +// both builds, and so did this round's, by hand). +// - b06: a listener given to a library's `.on("zoom", …)` where the component is made (the named action the message +// prints); d3-zoom itself is not in the benchmark's install, so `.on` is a stand-in's. +// - b07 (@dschz/solid-flow): two stores made by the library (`extend fn … instantiates`, twice). +// - b08 (@solid-primitives/notification): `onClose` in the hook's options (an `extend` row; new on 2026-12-02). +// - b09 (@formisch/solid, valibot): a namespace import (the names the message lists), valibot's builders (`import +// pure`), `createForm` (`instantiates`), `getInput` (`import pure`, printed first since 2026-12-02: with +// `instantiates` the form's input was never stored), and no SNAPSHOT_KEPT on the form's seed (a cascade). +// - b11 (@solid-primitives/storage): a helper of the app's with no declaration (the command, then `ref` and `pure`). +// - b13 (@solid-primitives/upload): a library's `ref` field read in an action (rx-tsc's TS2345; no message now). +// Needs what bench/run.mjs needs (the crate, the runtime's build, bench/.out/ws). node compiler/test/pasted.mjs +import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs"; +import { spawnSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; +import path from "node:path"; +import { ws, repo, workspace, both, rxTsc, Runner } from "../../bench/harness.mjs"; +import { appliers } from "./paste-apply.mjs"; + +workspace(); +const fixtures = path.join(path.dirname(fileURLToPath(import.meta.url)), "pasted"); +const root = path.join(ws, "pasted"); rmSync(root, { recursive: true, force: true }); mkdirSync(root, { recursive: true }); +let pass = 0, fail = 0; +const check = (name, ok, got) => { ok ? pass++ : fail++; console.log(`${ok ? "✓" : "✗"} ${name}${ok ? "" : `\n ${String(typeof got === "string" ? got : JSON.stringify(got)).slice(0, 1200)}`}`); return ok; }; +const stage = name => { const d = path.join(root, name); cpSync(path.join(fixtures, name), d, { recursive: true }); renameSync(path.join(d, "main.rx.txt"), path.join(d, "main.rx")); return d; }; +const read = (d, f) => readFileSync(path.join(d, f), "utf8"); +const write = (d, f, s) => { mkdirSync(path.dirname(path.join(d, f)), { recursive: true }); writeFileSync(path.join(d, f), s); }; +const append = (d, f, line) => write(d, f, (existsSync(path.join(d, f)) ? read(d, f) : "") + line + "\n"); +/** What rx-tsc says of the project: the crate's diagnostics (`main.rx:L:C - error CODE: msg (RULE)`) and TypeScript's. */ +const said = d => { + const out = String(rxTsc(d)); const ds = []; + for (const l of out.split("\n")) { + let m = /^(\S+?):(\d+):\d+ - error ([A-Z][A-Z_0-9]+): (.*)$/.exec(l); if (m) { ds.push({ file: m[1], line: +m[2], code: m[3], msg: m[4] }); continue; } + m = /^(\S+?)\((\d+),\d+\): error (TS\d+): (.*)$/.exec(l); if (m) ds.push({ file: m[1], line: +m[2], code: m[3], msg: m[4] }); + } + return { out, ds }; +}; +/** The message's spellings: the text in each pair of backticks, in order. */ +const ticks = msg => [...msg.matchAll(/`([^`]+)`/g)].map(m => m[1]); +const lines = (d, f = "main.rx") => read(d, f).split("\n"); +const setLines = (d, xs, f = "main.rx") => write(d, f, xs.join("\n")); +/** Each message of `code`, pasted by `paste(message, dir)`, until rx-tsc says none (at most `n` rounds). */ +function pasteAll(d, code, paste, n = 6) { + for (let i = 0; i < n; i++) { + const s = said(d).ds.filter(x => x.code === code); if (!s.length) return true; + // (a message with no spelling where this looks for one is a failure of the message, said as one) + try { paste(s[0], d); } catch (e) { check(`${path.basename(d)}: ${code} prints a spelling to paste`, false, `${e.message} — the message: ${s[0].msg}`); return false; } + } + return !said(d).ds.some(x => x.code === code); +} +/** Accepted by rx-tsc, and by both checkers alike. */ +function accepted(name, d) { + const s = said(d); const r = both(path.join(d, "main.rx")); + return check(`${name}: pasted as printed, rx-tsc and both checkers accept it`, !s.ds.length && !s.out.trim() && r.agree && !r.crate.diagnostics.length && !r.ref.diagnostics.length, `${s.out.slice(0, 900)} | crate: ${r.crate.diagnostics.map(x => x.code).join(",")} ref: ${r.ref.diagnostics.map(x => x.code).join(",")}`); +} +const sleep = ms => new Promise(res => setTimeout(res, ms)); +/** The steps the review's runner took (r7/rt.mjs): what `.out` says after each, and what was evaluated. */ +async function play(h, page, steps) { + const text = async () => { try { return (await h.text(page, ".out")).replace(/\s+/g, " ").trim(); } catch (e) { return `ERR ${String(e.message).slice(0, 80)}`; } }; + const seen = [await text()]; + for (const s of steps) { + if (s.click) { try { await page.click(s.click, { timeout: 3000 }); } catch (e) { seen.push(`click ${s.click} failed`); } await sleep(s.then ?? 300); } + if (s.dblclick) { try { await page.dblclick(s.dblclick, { timeout: 3000 }); } catch { seen.push("dblclick failed"); } await sleep(300); } + if (s.fill) { try { await page.fill(s.fill, s.value, { timeout: 3000 }); } catch { seen.push(`fill ${s.fill} failed`); } await sleep(200); } + if (s.press) { await page.keyboard.press(s.press); await sleep(300); } + if (s.wait) await sleep(s.wait); + if (s.drag) { try { await page.dragAndDrop(s.drag, s.to, { timeout: 3000 }); } catch { seen.push("drag failed"); } await sleep(300); } + if (s.select) { try { await page.selectOption(s.select, s.value, { timeout: 3000 }); } catch { seen.push("select failed"); } await sleep(300); } + if (s.reload) { await page.reload(); await sleep(600); } + if (s.eval) { let v; try { v = await page.evaluate(s.eval); } catch (e) { v = `ERR ${e.message}`; } seen.push(`eval ${JSON.stringify(v)}`); continue; } + seen.push(await text()); + } + return seen; +} +/** Run in both builds: the same frames, nothing on the console, and `want` holds of the frames. */ +async function runs(name, d, want) { + const steps = existsSync(path.join(d, "steps.json")) ? JSON.parse(read(d, "steps.json")) : []; + const got = []; + for (const production of [false, true]) { + const h = new Runner(d, "main.rx", undefined, { production }); + try { const page = await h.open(await h.serve()); await sleep(400); got.push({ frames: await play(h, page, steps), problems: h.problems }); } + catch (e) { got.push({ frames: [`run threw: ${String(e.message ?? e).slice(0, 300)}`], problems: [] }); } + await h.close().catch(() => {}); + } + const [dev, prod] = got; + check(`${name}: runs, the same frames in Solid's development and production builds, nothing on the console`, JSON.stringify(dev.frames) === JSON.stringify(prod.frames) && !dev.problems.length && !prod.problems.length, { dev, prod }); + check(`${name}: …and does what the app is for`, want(dev.frames.join("\n")), dev.frames.join("\n")); +} + +// (PASTED_ONLY=: the generic cases of that name alone, the apps not run) +if (!process.env.PASTED_ONLY) { +// ---------------------------------------------------------------- b02: a kanban board on @solid-primitives/drag-drop +{ + const d = stage("b02"); + const first = said(d).ds.map(x => x.code); + check("b02: refused as the review met it, less the leading `?` (now read as a choice)", !first.includes("PARSE") && first.includes("SNAPSHOT_ARGUMENT") && first.includes("UNKNOWN_COMPONENT") && first.includes("REACTIVE_WRITE_IN_OWNED_SCOPE"), first); + // SNAPSHOT_ARGUMENT: "…or pass peek(…)": the argument the message names, given through peek + pasteAll(d, "SNAPSHOT_ARGUMENT", (m, d) => { + const callee = /^(\w+)\(…\)/.exec(m.msg)[1], spelled = ticks(m.msg).includes("peek(…)") || /pass peek\(…\)/.test(m.msg); + if (!spelled) throw new Error(`no peek(…) in: ${m.msg}`); + const xs = lines(d); xs[m.line - 1] = xs[m.line - 1].replace(new RegExp(`${callee}\\(([^()]*)\\)`), `${callee}(peek($1))`); setLines(d, xs); + }); + // REACTIVE_WRITE_IN_OWNED_SCOPE on `onDragEnd`: "…say so over the draft, in rx-types/X.d.rx, `extend fn …`" + pasteAll(d, "REACTIVE_WRITE_IN_OWNED_SCOPE", (m, d) => { const f = /in (rx-types\/\S+?\.d\.rx)/.exec(m.msg)[1]; append(d, f, ticks(m.msg).find(t => t.startsWith("extend fn"))); }); + // UNKNOWN_COMPONENT on : "Write `js` in ./a.js and `row` in ./a.d.rx beside it, then `import`, `binding` in the component, and here" + pasteAll(d, "UNKNOWN_COMPONENT", (m, d) => { + const [js, row, imp, binding] = ticks(m.msg).slice(-4), [, jsFile, rowFile] = /in (\.\/\S+?\.js) and .* in (\.\/\S+?\.d\.rx)/.exec(m.msg); + const tag = /^<([\w.]+)>/.exec(m.msg)[1], to = /and <(\w+)> here/.exec(m.msg)[1]; + write(d, jsFile, js + "\n"); write(d, rowFile, row + "\n"); + const xs = lines(d), lastImport = xs.map(l => /^import /.test(l)).lastIndexOf(true); xs.splice(lastImport + 1, 0, imp); + const at = xs.findIndex(l => l.includes(`<${tag}`)); let view = at; while (view > 0 && !/^ {2} l.replaceAll(`<${tag}>`, `<${to}>`).replaceAll(``, ``))); + }); + if (accepted("b02", d)) await runs("b02", d, f => /c3 dropped on doing/.test(f) && /To do \(0\)Doing \(2\)Draw mocksPlan sprintDone \(2\)Build boardWrite spec/.test(f)); +} + +// ---------------------------------------------------------------- b03: a markdown editor, its word count debounced +{ + const d = stage("b03"); + const first = said(d).ds.map(x => x.code); + check("b03: refused as the review met it (IO_IN_REACTIVE on debounce)", JSON.stringify(first) === '["IO_IN_REACTIVE"]', first); + // "…say so in rx-types/X.d.rx, `extend fn debounce instantiates`" — the spelling printed first, since what it answers is called + pasteAll(d, "IO_IN_REACTIVE", (m, d) => { const f = /in (rx-types\/\S+?\.d\.rx)/.exec(m.msg)[1]; append(d, f, ticks(m.msg).find(t => t.startsWith("extend fn"))); }); + if (accepted("b03", d)) await runs("b03", d, f => /^8 wordsTitle Some bold text/m.test(f) && /eval "# Title\\n\\nSome \*\*bold\*\*/.test(f) && f.split("\n").at(-1) === "0 words"); // the count 300 ms behind, the draft kept across a reload +} + +// ---------------------------------------------------------------- b04: presence over @solid-primitives/websocket +{ + const d = stage("b04"); + const first = said(d).ds.map(x => x.code); + check("b04: refused as the review met it (WRITE_TO_NON_SOURCE through patch's draft)", first.includes("WRITE_TO_NON_SOURCE"), first); + // "…`patch: handler (draft draft: S, msg: T) => void` (options's field) in its row, written whole in rx-types/X.d.rx (…) as + // the draft has it but for that field": the draft's row, with that field as printed + pasteAll(d, "WRITE_TO_NON_SOURCE", (m, d) => { + const field = ticks(m.msg).find(t => /^\w+: handler \(/.test(t)), f = /written whole in (rx-types\/\S+?\.d\.rx)/.exec(m.msg)[1]; + const spec = f.slice("rx-types/".length, -".d.rx".length), fn = /given to (\w+)\(…\)/.exec(m.msg)[1]; + const draft = readFileSync(path.join(ws, "node_modules/.rx-types", `${spec}.d.rx`), "utf8").split("\n").find(l => l.startsWith(`export fn ${fn}`) || l.startsWith(`export fn ${fn}<`)); + const was = field.replace(/: handler \(/, ": (").replace(/\(draft /, "("); // the field as the draft writes it + if (!draft.includes(was)) throw new Error(`the draft's row has no ${was}`); + append(d, f, draft.replace(was, field)); + }); + accepted("b04", d); +} + +// ---------------------------------------------------------------- b06: a zoom listener given where the component is made +{ + const d = stage("b06"); + const first = said(d).ds.map(x => x.code); + check("b06: refused as the review met it (REACTIVE_WRITE_IN_OWNED_SCOPE on the zoom listener)", JSON.stringify(first) === '["REACTIVE_WRITE_IN_OWNED_SCOPE"]', first); + // "…`action handle(e: ZoomEvent) { … }`, with this closure's statements as its body, declared in the component, and + // `handle` written where the closure is" + pasteAll(d, "REACTIVE_WRITE_IN_OWNED_SCOPE", (m, d) => { + const [head, name] = ticks(m.msg).filter(t => t.startsWith("action ") || /^\w+$/.test(t)).slice(-2), src = read(d, "main.rx"); + const params = /^action \w+\((.*)\) \{ … \}$/.exec(head)[1], open = src.indexOf(`(${params}) => {`); + let depth = 0, i = src.indexOf("{", open + params.length + 2); + for (let j = i; j < src.length; j++) { if (src[j] === "{") depth++; if (src[j] === "}" && --depth === 0) { i = j; break; } } + const body = src.slice(src.indexOf("{", open + params.length + 2) + 1, i), lineStart = src.lastIndexOf("\n", open) + 1; + write(d, "main.rx", src.slice(0, lineStart) + ` ${head.replace("{ … }", `{${body}}`)}\n` + src.slice(lineStart, open) + name + src.slice(i + 1)); + }); + if (accepted("b06", d)) await runs("b06", d, f => /zoom 2\.00 at -20/.test(f)); +} + +// ---------------------------------------------------------------- b07: a node graph on @dschz/solid-flow +{ + const d = stage("b07"); + const first = said(d).ds.map(x => x.code); + check("b07: refused as the review met it (IO_IN_REACTIVE on the two stores)", JSON.stringify(first) === '["IO_IN_REACTIVE","IO_IN_REACTIVE"]', first); + pasteAll(d, "IO_IN_REACTIVE", (m, d) => { const f = /in (rx-types\/\S+?\.d\.rx)/.exec(m.msg)[1]; append(d, f, ticks(m.msg).find(t => t.startsWith("extend fn"))); }); + if (accepted("b07", d)) await runs("b07", d, f => /1:Input \| 2:Default \| 5:Node 5 ; edges 1/.test(f)); +} + +// ---------------------------------------------------------------- b08: an install prompt and a notification +{ + const d = stage("b08"); + const first = said(d).ds.map(x => x.code); + check("b08: refused since 2026-12-02 (the hook's onClose carries its word)", JSON.stringify(first) === '["REACTIVE_WRITE_IN_OWNED_SCOPE"]', first); + pasteAll(d, "REACTIVE_WRITE_IN_OWNED_SCOPE", (m, d) => { const f = /in (rx-types\/\S+?\.d\.rx)/.exec(m.msg)[1]; append(d, f, ticks(m.msg).find(t => t.startsWith("extend fn"))); }); + if (accepted("b08", d)) await runs("b08", d, f => /closed/.test(f)); +} + +// ---------------------------------------------------------------- b09: a sign-up wizard on @formisch/solid and valibot +{ + const d = stage("b09"); + const first = said(d).ds.map(x => x.code); + check("b09: refused as the review met it (PARSE on `import * as v`)", first.includes("PARSE"), first); + // PARSE: "…`import { object, pipe, … } from "valibot"`" — the names the module reads off the namespace + pasteAll(d, "PARSE", (m, d) => { + const imp = ticks(m.msg).find(t => /^import \{.*\} from "/.test(t)), from = /from "([^"]+)"/.exec(imp)[1]; + const src = read(d, "main.rx"), ns = new RegExp(`^import \\* as (\\w+) from "${from}"$`, "m").exec(src)[1]; + // (the cold start's U1: a member the module declares too is imported under another name, `email as vEmail`, and called so) + let out = src.replace(new RegExp(`^import \\* as ${ns} from "${from}"$`, "m"), imp); + for (const [, name, alias] of imp.matchAll(/(\w+) as (\w+)/g)) out = out.replaceAll(`${ns}.${name}(`, `${alias}(`); + write(d, "main.rx", out.replaceAll(`${ns}.`, "")); + }); + const io = said(d).ds.filter(x => x.code === "IO_IN_REACTIVE"); + check("b09: …then IO_IN_REACTIVE on valibot's builders, createForm and getInput, and no SNAPSHOT_KEPT on the form's seed (a cascade of createForm's)", io.length > 0 && !said(d).ds.some(x => x.code === "SNAPSHOT_KEPT"), said(d).ds.map(x => x.code)); + // the spelling each message prints first: `import pure { … }` (at the import that names the callee), or an `extend` row + pasteAll(d, "IO_IN_REACTIVE", (m, d) => { + const fn = /^(\w+)\(…\)/.exec(m.msg)[1], first = ticks(m.msg).find(t => t.startsWith("import pure") || t.startsWith("extend fn")); + if (first.startsWith("extend fn")) { append(d, /in (rx-types\/\S+?\.d\.rx)/.exec(m.msg)[1], first); return; } + // (an entry is the name or `name as alias` — the cold start's U1: `email as vEmail`, the name the call is written with) + const own = e => e.split(/\s+as\s+/).pop() === fn; + const xs = lines(d), at = xs.findIndex(l => /^import \{/.test(l) && /^import \{(.*)\} from/.exec(l)[1].split(",").some(e => own(e.trim()))); + const [, names, from] = /^import \{(.*)\} from (".*")$/.exec(xs[at]), entries = names.split(",").map(s => s.trim()).filter(Boolean), rest = entries.filter(n => !own(n)), entry = entries.find(own); + const pure = xs.findIndex(l => l.startsWith("import pure {") && l.endsWith(` from ${from}`)); + // (since 2026-12-03 the message prints the import whole, as the program writes it: `import pure { getInput } from "…"`) + if (pure >= 0) xs[pure] = xs[pure].replace(/\}/, `, ${entry} }`); else xs.splice(at, 0, first); + const at2 = xs.findIndex(l => /^import \{/.test(l) && l.endsWith(` from ${from}`)); if (rest.length) xs[at2] = `import { ${rest.join(", ")} } from ${from}`; else xs.splice(at2, 1); + setLines(d, xs); + }, 20); + if (accepted("b09", d)) await runs("b09", d, f => /Welcome, Ada/.test(f) && /ada@example\.com/.test(f)); +} + +// ---------------------------------------------------------------- b11: settings kept with @solid-primitives/storage +{ + const d = stage("b11"); + const first = said(d).ds.map(x => x.code); + check("b11: refused as the review met it (IO_IN_REACTIVE on the app's own helper)", first.includes("IO_IN_REACTIVE"), first); + // "…`npx rx-declare ./prefs.js --out ./prefs.d.rx` drafts it…; there, a part … is `ref` (`[ref T, (v: T) => void]`, …) and + // called where the component is made, as here, the row needs no word: `export fn persisted` is io…" (until 2026-12-01 it + // said `export pure fn`, which is false of a primitive that makes a signal: MO-15d told it on b11m) + pasteAll(d, "IO_IN_REACTIVE", (m, d) => { + const t = ticks(m.msg), [, js, out] = /^npx rx-declare (\S+) --out (\S+)$/.exec(t.find(x => x.startsWith("npx rx-declare"))); + const r = spawnSync(process.execPath, [path.join(repo, "tooling/rx-language-server/bin/declare.js"), js, "--out", out], { cwd: d, encoding: "utf8" }); + if (r.status !== 0) throw new Error(`rx-declare: ${r.stderr}`); + const tuple = t.find(x => x.startsWith("[ref ")), fn = /^(\w+)\(…\)/.exec(m.msg)[1]; + const row = t.find(x => new RegExp(`^export (?:pure )?fn ${fn}$`).test(x)); + write(d, out, read(d, out).split("\n").map(l => l.startsWith(`export fn ${fn}`) ? l.replace(`export fn ${fn}`, row).replace(/\[\(\) => T, \(v: T\) => void\]/, tuple) : l).join("\n")); + }); + if (accepted("b11", d)) await runs("b11", d, f => /theme dark · 20px · fr · emails off/.test(f)); +} + +// ---------------------------------------------------------------- b13: uploads with @solid-primitives/upload +{ + const d = stage("b13"); + // (a `ref` field read in an action is its value to TypeScript too: no message to paste.) Round C1 (06 AC-1h, after an + // \`await\`): \`sent := sent + len(r)\` after the upload is STALE_NEXT_READ — two quick clicks would count one batch — + // and the functional write it prints is pasted + const first = said(d).ds.map(x => x.code); + check("b13: refused as round C1 has it (STALE_NEXT_READ on a count read after the await)", first.includes("STALE_NEXT_READ"), first); + pasteAll(d, "STALE_NEXT_READ", (m, d) => { const fix = ticks(m.msg).find(t => /^sent := v => /.test(t)); if (!fix) throw new Error("no functional write printed"); { const s = read(d, m.file); if (!s.includes("sent := sent + len(r)")) throw new Error("no such write"); write(d, m.file, s.replace("sent := sent + len(r)", fix)); } }); + if (accepted("b13", d)) await runs("b13", d, f => /1 files, 11 B/.test(f) && /sent 2/.test(f)); +} + +} + +// ---------------------------------------------------------------- the generic set (compiler/test/pasted-cases.mjs) +// Minimal programs, none a review's app: each code that prints a spelling, in the places its spelling depends on. A +// spelling is applied by what the message says alone — the text in its backticks, the file it names — by the appliers +// below, one a kind of way through; a message whose spelling an applier cannot find fails as "prints no spelling". +{ + const { inventory, CASES, GUIDE, OPEN, TSCONFIG_TEXT, TSCONFIG_GUIDE } = await import("./pasted-cases.mjs"); + const { APPLY } = appliers({ repo, ws }); + // (the codes a step pastes the spelling of: the case's own, and those its paste leads to, which are the declaration's) + const FAMILY = new Set(["IO_IN_REACTIVE", "IO_IN_FN", "EFFECT_WRITES_OWN_SOURCE", "REACTIVE_WRITE_IN_OWNED_SCOPE", "UNBOUND", "IMPORT_ROW_MISMATCH", "ACTION_CALLED_IN_OWNED_SCOPE"]); + const covered = new Set(); + for (const c of CASES.filter(c => !process.env.PASTED_ONLY || c.name.includes(process.env.PASTED_ONLY))) { + const d = path.join(root, "gen", c.name.replace(/\//g, "--")); mkdirSync(d, { recursive: true }); + for (const [f, s] of Object.entries({ "tsconfig.json": TSCONFIG_TEXT, ...c.files })) write(d, f, s); + if (c.steps) write(d, "steps.json", JSON.stringify(c.steps)); + const first = said(d).ds.map(x => x.code); + if (!check(`${c.name}: refused with ${c.code} at its first pass`, first.includes(c.code), first)) continue; + const st = {}; let ok = true; + for (const how of c.take) { + const ds = said(d).ds.filter(x => FAMILY.has(x.code) && !/^TS/.test(x.code)), m = ds[0]; + if (!m && how !== "hand") { ok = check(`${c.name}: a message to paste "${how}" from`, false, said(d).out); break; } + try { APPLY[how](m, d, st); } catch (e) { ok = check(`${c.name}: ${m?.code ?? "rx-declare"} prints a spelling to paste (${how})`, false, `${e.message} — the message: ${m?.msg ?? st.declared?.stderr}`); break; } + } + if (!ok) continue; + if (accepted(c.name, d)) { covered.add(c.code); if (c.want) await runs(c.name, d, f => c.want.test(f.split("\n").at(-1))); } + } + // the respellings: each guide `before` program GUIDE names, pasted by its code's spelling until accepted + const befores = []; { let code; const gl = readFileSync(path.join(repo, "guide/diagnostics.md"), "utf8").split("\n"); + for (let i = 0; i < gl.length; i++) { const h = /^### ([A-Z_]+)/.exec(gl[i]); if (h) code = h[1]; if (/^```rx before/.test(gl[i])) { let j = i + 1; const b = []; while (!/^```/.test(gl[j])) b.push(gl[j++]); befores.push({ code, src: b.join("\n") + "\n" }); } } } + for (const g of GUIDE.filter(g => !g.open && (!process.env.PASTED_ONLY || `guide/${g.code}/${g.k}`.includes(process.env.PASTED_ONLY)))) { + const name = `guide/${g.code}/${g.k}`, b = befores[g.k]; + if (!check(`${name}: the guide's before program is ${g.code}'s`, b?.code === g.code, b?.code)) continue; + const d = path.join(root, "gen", name.replace(/\//g, "--")); mkdirSync(d, { recursive: true }); + // a fence that holds its modules (`-- module: ./x.d.rx`, then `-- main`), as the crate's diagnostics_page.rs reads one + const mods = {}; let main = "", at = null; + for (const l of b.src.split("\n")) { const m = /^-- module: (.+)$/.exec(l); if (m) { at = m[1].trim().replace(/^\.\//, ""); mods[at] = ""; continue; } if (l === "-- main") { at = null; continue; } if (at) mods[at] += l + "\n"; else main += l + "\n"; } + for (const [f, s] of Object.entries({ "tsconfig.json": TSCONFIG_GUIDE, ...(g.files ?? {}), ...mods, "main.rx": main.replace(/\n$/, "") })) write(d, f, s); + const first = said(d).ds.map(x => x.code); + if (!check(`${name}: refused with ${g.code} at its first pass`, first.includes(g.code), first)) continue; + const ok = pasteAll(d, g.code, (m, d) => { const t = ticks(m.msg); write(d, m.file, g.paste(m, read(d, m.file), t)); }, 4); + if (ok && accepted(name, d)) covered.add(g.code); + else if (!ok) check(`${name}: pasted as printed, ${g.code} is gone`, false, said(d).out.slice(0, 900)); + } + // the inventory: each code a message prints a spelling for has a case here or in the apps above, or is OPEN + const APPS = ["SNAPSHOT_ARGUMENT", "REACTIVE_WRITE_IN_OWNED_SCOPE", "UNKNOWN_COMPONENT", "IO_IN_REACTIVE", "WRITE_TO_NON_SOURCE", "PARSE"]; + const inv = inventory(repo), spelled = inv.filter(x => x.spells), has = covered; + const cases = new Set([...has, ...APPS]); + if (!process.env.PASTED_ONLY) { + const missing = spelled.filter(x => !cases.has(x.code) && !OPEN.has(x.code)).map(x => x.code), stale = [...OPEN.keys()].filter(k => cases.has(k)); + console.log(`inventory: ${inv.length} codes, ${spelled.length} print a spelling; ${spelled.filter(x => cases.has(x.code)).length} have a paste case that passes (the review's apps: ${APPS.length}; this set: ${spelled.filter(x => has.has(x.code)).length}), ${spelled.filter(x => OPEN.has(x.code)).length} open`); + check("every code that prints a spelling has a paste case, or is listed open with why (pasted-cases.mjs OPEN)", !missing.length, missing); + check("no code listed open has a case (take it off OPEN)", !stale.length, stale); + } +} + +// ---------------------------------------------------------------- the development guard's own printed fix (honest words, part A) +// The lend guard (09 MO-10i) refuses a JS fn that changes what it was lent and prints the write to make instead, +// `let v = [...xs]; f(v); xs := v`. Until 2026-12-01 the guard refused that very write in development (the local was +// a value made from the state, kind "e"), and in production a list of rows came back unchanged. Here the message is +// taken from the page as the development build throws it, its spelling put in place of the call (`xs` is the +// argument the call was given, the callee is the message's), and the program run again in both builds. +if (!process.env.PASTED_ONLY || "guard-fix".includes(process.env.PASTED_ONLY)) { + const d = path.join(root, "gen", "guard-fix"); mkdirSync(d, { recursive: true }); + write(d, "tsconfig.json", (await import("./pasted-cases.mjs")).TSCONFIG_TEXT); + write(d, "h.js", "export const pushTo = (xs) => { xs.push(typeof xs[0] === \"string\" ? \"x\" : { n: 9 }); return xs.length }\n"); + write(d, "h.d.ts", "export declare const pushTo: (xs: any[]) => number;\n"); + write(d, "h.d.rx", "export fn pushTo(xs: any[]): number\n"); + write(d, "main.rx", [ + "import { pushTo } from \"./h.js\"", + "export default component App() {", + " source names: string[] := [\"b\", \"a\"]", + " source rows: { n: number }[] := [{ n: 1 }]", + "
    ", + " ", + " ", + "

    {names.join(\",\")} | {rows.map((r) => r.n).join(\",\")}

    ", + "
    ", + "}", + ""].join("\n")); + const steps = [{ click: ".a" }, { click: ".b" }]; + write(d, "steps.json", JSON.stringify(steps)); + // the development build, as written: each click is the guard's error; its message, whole, from the page + const h = new Runner(d, "main.rx", undefined, { production: false }), msgs = []; + try { const page = await h.open(await h.serve()); page.on("pageerror", e => msgs.push(String(e.message ?? e))); await sleep(400); await play(h, page, steps); } + catch (e) { msgs.push(`run threw: ${e.message}`); } + await h.close().catch(() => {}); + const fix = msgs.map(m => ({ m, t: ticks(m).find(t => /^let v = .*; \w+\(v\); xs := v$/.test(t)) })).filter(x => x.t); + if (check("guard-fix: the development build refuses pushTo(names) and pushTo(rows), and prints the write to make", fix.length === 2, { msgs, problems: h.problems })) { + const xs = lines(d); + for (const [arg, { t }] of [["names", fix[0]], ["rows", fix[1]]]) { const at = xs.findIndex(l => l.includes(`pushTo(${arg})`)), callee = /; (\w+)\(v\);/.exec(t)[1]; xs[at] = xs[at].replace(`${callee}(${arg})`, t.replaceAll("xs", arg)); } + setLines(d, xs); + if (accepted("guard-fix", d)) await runs("guard-fix", d, f => /^abb,a,x \| 1,9$/.test(f.split("\n").at(-1))); + } +} + +rmSync(root, { recursive: true, force: true }); +console.log(`\n${pass} passed, ${fail} failed`); +process.exit(fail ? 1 : 0); diff --git a/compiler/test/pasted/b02/main.rx.txt b/compiler/test/pasted/b02/main.rx.txt new file mode 100644 index 000000000..52473e7b6 --- /dev/null +++ b/compiler/test/pasted/b02/main.rx.txt @@ -0,0 +1,68 @@ +// A kanban board on @solid-primitives/drag-drop: three columns; a card is dragged onto another card (it takes its +// place) or onto a column (it goes to the end) +import { createDragContext, createDroppable, createSortable } from "@solid-primitives/drag-drop" + +type Card = { id: string; title: string } +type Column = { id: string; title: string; cards: Card[] } + +fn without(cards: Card[], id: string): Card[] => cards.filter(c => c.id != id) +fn placed(cards: Card[], card: Card, at: number): Card[] => [...cards.slice(0, at), card, ...cards.slice(at)] + +// the board after the card `cardId` was dropped on `overId`, a card or a column +fn moved(cols: Column[], cardId: string, overId: string): Column[] { + card = cols.flatMap(c => c.cards).find(c => c.id == cardId) + to = cols.find(c => c.id == overId || c.cards.some(x => x.id == overId)) + at = to == undefined ? -1 : to.id == overId ? to.cards.length : to.cards.findIndex(x => x.id == overId) + card == undefined || to == undefined || cardId == overId + ? cols + : cols.map(c => c.id == to.id ? { ...c, cards: placed(without(c.cards, cardId), card, at) } : { ...c, cards: without(c.cards, cardId) }) +} + +component CardItem(props: { card: Card }) { + s = createSortable(props.card.id) +
  • {props.card.title}
  • +} + +component ColumnView(props: { column: Column }) { + drop = createDroppable(props.column.id) +
    +

    {props.column.title} ({props.column.cards.length})

    +
      + {for card in props.column.cards { + + }} +
    +
    +} + +export default component App() { + source columns: Column[] key id := [ + { id: "todo", title: "To do", cards: [{ id: "c1", title: "Write spec" }, { id: "c2", title: "Draw mocks" }, { id: "c3", title: "Plan sprint" }] }, + { id: "doing", title: "Doing", cards: [{ id: "c4", title: "Build board" }] }, + { id: "done", title: "Done", cards: [] } + ] + source last := "nothing moved yet" + ctx = createDragContext({ + onDragEnd: (item, over) => { + if (over != null) { + columns := cs => moved(cs, str(item.id), str(over.id)) + last := `${item.id} dropped on ${over.id}` + } + } + }) + +
    + +
    + {for column in columns { + + }} +
    +
    +

    {last}

    +
    +} diff --git a/compiler/test/pasted/b02/steps.json b/compiler/test/pasted/b02/steps.json new file mode 100644 index 000000000..7c6db14c5 --- /dev/null +++ b/compiler/test/pasted/b02/steps.json @@ -0,0 +1 @@ +[{"drag":".card-c1","to":".col-done"},{"drag":".card-c3","to":".card-c2"},{"drag":".card-c2","to":".card-c4"},{"drag":".card-c4","to":".card-c1"},{"drag":".card-c3","to":".col-doing"}] diff --git a/compiler/test/pasted/b02/tsconfig.json b/compiler/test/pasted/b02/tsconfig.json new file mode 100644 index 000000000..6d1b63bb3 --- /dev/null +++ b/compiler/test/pasted/b02/tsconfig.json @@ -0,0 +1,29 @@ +{ + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "@solidjs/web", + "strict": true, + "noImplicitAny": true, + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "allowImportingTsExtensions": true, + "noEmit": true, + "skipLibCheck": true, + "lib": [ + "ES2024", + "DOM", + "DOM.Iterable" + ], + "types": [] + }, + "include": [ + "**/*.rx", + "**/*.d.ts" + ], + "exclude": [ + "node_modules", + "dist", + ".build" + ] +} \ No newline at end of file diff --git a/compiler/test/pasted/b03/main.rx.txt b/compiler/test/pasted/b03/main.rx.txt new file mode 100644 index 000000000..c0b722060 --- /dev/null +++ b/compiler/test/pasted/b03/main.rx.txt @@ -0,0 +1,21 @@ +// A markdown editor: the draft is kept in localStorage (makePersisted), the preview is a renderer's HTML (r7's b03 used +// micromark, which the benchmark's install does not hold), and the word count follows the typing 300 ms behind (debounce) +import { render } from "./md.js" +import { debounce } from "@solid-primitives/scheduled" +import { persisted } from "./storage.js" + +fn countWords(text: string): number => text.trim() == "" ? 0 : text.trim().split(/\s+/).length + +export default component App() { + [draft, setDraft] = persisted("# Hello\n\nWrite *markdown* here.", { name: "draft" }) + source words := 0 + count = debounce((text: string) => { words := countWords(text) }, 300) + effect (draft) { count($0) } + html = render(draft) + +
    +