diff --git a/.github/workflows/compiler.yml b/.github/workflows/compiler.yml index 0faa5d84..19b2b9f2 100644 --- a/.github/workflows/compiler.yml +++ b/.github/workflows/compiler.yml @@ -10,12 +10,51 @@ name: compiler on: push: branches: [main] - paths: ["compiler/**", ".github/workflows/compiler.yml"] + paths: ["compiler/**", "ref/**", "spec/**", "scenarios/**", "examples/**", ".github/workflows/compiler.yml"] pull_request: - paths: ["compiler/**", ".github/workflows/compiler.yml"] + paths: ["compiler/**", "ref/**", "spec/**", "scenarios/**", "examples/**", ".github/workflows/compiler.yml"] workflow_dispatch: jobs: + parity: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + include: + - { name: checker, flags: "" } + - { name: lowering, flags: "--lower" } + name: parity (${{ matrix.name }}) + steps: + - uses: actions/checkout@v5 + - uses: dtolnay/rust-toolchain@master + with: + toolchain: 1.99.1 + - uses: Swatinem/rust-cache@v2 + with: + workspaces: compiler + - uses: actions/setup-node@v5 + with: + node-version: 24 + - uses: pnpm/action-setup@v4 + with: + version: 11.1.1 + - run: sh ref/scripts/solid-next.sh + - run: npm ci --prefix ref + - if: matrix.flags == '' + run: npm --prefix ref run crate + - if: matrix.flags != '' + # Keep local lowering strict. In CI, tolerate only the named, existing + # mismatches until they are fixed; a crash or a different set fails. + run: | + log=$(mktemp) + status=0 + npm --prefix ref run crate -- ${{ matrix.flags }} >"$log" 2>&1 || status=$? + cat "$log" + test "$status" -le 1 + grep -Eq '^[0-9]+/[0-9]+ programs lowered alike' "$log" + diff -u ref/lowering-baseline.txt <(grep '^FAIL ' "$log" || true) + build: strategy: fail-fast: false diff --git a/CHANGELOG.md b/CHANGELOG.md index e4b64a8b..f2abdc6a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,18 @@ ## Unreleased +**Breaking** + +- MO-8c: a real `./api` implementation beside the importing module wins over the injected test API, even if + `createApp({ api })` is set. A test API call with no injected implementation now throws `MISSING_TEST_API`. +- `DEAD_TYPED_BOUNDARY` rejects a typed error boundary proven shadowed by an inner catch-all. Put the typed + boundary inside the catch-all. +- `STYLE_SCOPE` rejects a style block outside a supported style scope; move it into the component that owns the view. +- String and template escapes are cooked in the compiler; programs relying on the previous literal backslashes + must escape those backslashes explicitly. +- Multiline JSX whitespace follows the view whitespace rules (07 §4). Use an explicit `{" "}` where spacing + between pieces must survive. + **Changed** - `catch` follows only an `await`: `await f(x) catch (e) => alt` makes a matching rejection the answer. A `catch` after diff --git a/compiler/src/ast.rs b/compiler/src/ast.rs index 79e82bb7..e7c719e1 100644 --- a/compiler/src/ast.rs +++ b/compiler/src/ast.rs @@ -22,6 +22,7 @@ pub enum TplPart { #[derive(Debug, Clone)] pub enum Field { Kv { key: String, v: Expr }, + Computed { key: Expr, v: Expr }, Spread(Expr), } @@ -83,6 +84,7 @@ pub enum ExprKind { Call { f: Box, args: Vec }, Arr(Vec), Rec(Vec), + As { e: Box, ty: String }, /// `stmts`: a statement-bodied arrow (imperative scope, 07 §5) Fn { params: Vec, body: Box, stmts: Option> }, /// ST-3 @@ -420,6 +422,7 @@ impl Expr { ExprKind::Call { .. } => "call", ExprKind::Arr(_) => "arr", ExprKind::Rec(_) => "rec", + ExprKind::As { .. } => "as", ExprKind::Fn { .. } => "fn", ExprKind::Draft { .. } => "draft", ExprKind::Use(_) => "use", @@ -443,6 +446,7 @@ impl Expr { ExprKind::Pre { name, init } => obj(vec![("k", k), ("name", s(name)), ("init", ob(init))]), ExprKind::Peek(e) | ExprKind::Latest(e) | ExprKind::Pending(e) | ExprKind::Spread(e) | ExprKind::Throw(e) => obj(vec![("k", k), ("e", b(e))]), ExprKind::Omit { e, keys } => obj(vec![("k", k), ("e", b(e)), ("keys", Some(strs(keys)))]), + ExprKind::As { e, ty } => obj(vec![("k", k), ("e", b(e)), ("ty", s(ty))]), ExprKind::Await { e, init, stream } => obj(vec![("k", k), ("e", b(e)), ("init", ob(init)), ("stream", Some(Value::Bool(*stream)))]), ExprKind::If { c, t, f } => obj(vec![("k", k), ("c", b(c)), ("t", b(t)), ("f", b(f))]), ExprKind::Tpl(parts) => obj(vec![ @@ -462,6 +466,7 @@ impl Expr { .iter() .map(|f| match f { Field::Kv { key, v } => obj(vec![("key", s(key)), ("v", Some(v.to_json()))]), + Field::Computed { key, v } => obj(vec![("computed", Some(key.to_json())), ("v", Some(v.to_json()))]), Field::Spread(e) => obj(vec![("spread", Some(e.to_json()))]), }) .collect(), diff --git a/compiler/src/check.rs b/compiler/src/check.rs index ef628f7b..c2b421d2 100644 --- a/compiler/src/check.rs +++ b/compiler/src/check.rs @@ -42,6 +42,11 @@ impl Diagnostic { } const BUILTINS: &[&str] = &["len", "str", "map", "filter", "sum", "fail", "fetch", "every", "indexOf"]; +pub(crate) fn pure_global(name: &str, member: Option<&str>) -> bool { + static GLOBALS: std::sync::OnceLock>> = std::sync::OnceLock::new(); + GLOBALS.get_or_init(|| serde_json::from_str(include_str!("../../spec/pure-globals.json")).expect("pure globals")) + .get(name).is_some_and(|ms| member.is_none_or(|m| ms.iter().any(|x| x == m))) +} /// EF-5's cleanup shapes: a `return` of a closure anywhere in the body, a closure as its last expression, or an expression body that is one. fn returns_closure(f: &Expr) -> bool { fn in_stmts(ss: &[Stmt]) -> bool { @@ -395,7 +400,7 @@ pub(crate) fn children<'a>(n: Node<'a>, paths: bool) -> Vec> { Node::E(e) => match &e.k { ExprKind::Lit(_) | ExprKind::Id(_) | ExprKind::Use(_) | ExprKind::StyleMap { .. } => {} ExprKind::Bin { l, r, .. } => out.extend([Node::E(l), Node::E(r)]), - ExprKind::Un { e, .. } | ExprKind::Peek(e) | ExprKind::Latest(e) | ExprKind::Pending(e) | ExprKind::Spread(e) | ExprKind::Omit { e, .. } | ExprKind::Throw(e) => out.push(Node::E(e)), + ExprKind::Un { e, .. } | ExprKind::As { e, .. } | ExprKind::Peek(e) | ExprKind::Latest(e) | ExprKind::Pending(e) | ExprKind::Spread(e) | ExprKind::Omit { e, .. } | ExprKind::Throw(e) => out.push(Node::E(e)), ExprKind::Pre { init, .. } => out.extend(init.iter().map(|x| Node::E(x))), ExprKind::Await { e, init, .. } => { out.push(Node::E(e)); @@ -410,10 +415,12 @@ pub(crate) fn children<'a>(n: Node<'a>, paths: bool) -> Vec> { out.extend(args.iter().map(Node::E)); } ExprKind::Arr(items) => out.extend(items.iter().map(Node::E)), - ExprKind::Rec(fields) => out.extend(fields.iter().map(|f| match f { - Field::Kv { v, .. } => Node::E(v), - Field::Spread(e) => Node::E(e), - })), + ExprKind::Rec(fields) => for f in fields { + match f { + Field::Kv { v, .. } | Field::Spread(v) => out.push(Node::E(v)), + Field::Computed { key, v } => out.extend([Node::E(key), Node::E(v)]), + } + }, ExprKind::Fn { body, stmts, .. } => { out.push(Node::E(body)); if let Some(s) = stmts { @@ -480,7 +487,7 @@ pub(crate) fn free_names(e: &Expr, bound: &HashSet, out: &mut IndexSet go(x, out), + ExprKind::Latest(x) | ExprKind::Pending(x) | ExprKind::Un { e: x, .. } | ExprKind::As { e: x, .. } | ExprKind::Spread(x) | ExprKind::Omit { e: x, .. } => go(x, out), ExprKind::Bin { l, r, .. } => { go(l, out); go(r, out); @@ -517,6 +524,7 @@ pub(crate) fn free_names(e: &Expr, bound: &HashSet, out: &mut IndexSet go(v, out), + Field::Computed { key, v } => { go(key, out); go(v, out); } Field::Spread(x) => go(x, out), } } @@ -1079,6 +1087,72 @@ impl<'a> Checker<'a> { self.loading_on_outside(); self.snapshot_guards(); self.guess_while_loading(); + self.style_scope(p); + } + /// CSS-2: a component's ` { open(props.note.id) }}>{props.note.title} {props.note.updated} @@ -14,8 +18,6 @@ component Row(props: { note: Note }) { export component NoteList(props: { notes: Note[] }) { if len(props.notes) == 0 { diff --git a/guide/async.md b/guide/async.md index b67be29e..37e28d3d 100644 --- a/guide/async.md +++ b/guide/async.md @@ -5,6 +5,10 @@ don't need them to follow it. ## Rule zero: don't track requests yourself +Pure calculations can use the [fixed JS prelude](../spec/pure-globals.json) +directly, for example `Math.round(n)` and `Object.keys(record)`. Clocks, +randomness, browser APIs and timers still belong in imported JS. + Don't write sequence numbers, request ids, "latest token" checks, `if (stillCurrent)` guards, cancellation flags, or lists of pending requests. In .rx those are bugs waiting to happen, and they are never needed. The language already knows which question is current and which change a write belongs to. If you're reaching for a counter, you @@ -30,6 +34,32 @@ onFlush(() => { text := "" }) addTodo(t) ``` +### Which flight is holding this write? + +Start with the run that wrote the value, not the component that displays +it. Include its other writes, what their readers compute, and every +question the run opens that a display is waiting for (H-2). Two changes +can join: a new reader pass triggered by one change consumes a derivation +of the other's held value, or both write the same held slot (H-2, H-3, +H-3a). Merely having two outstanding requests doesn't join them. + +For example, a move waits for `moveCard`, writes the returned card and +undo entry, and does `refresh activity`. If a reader awaits that refreshed +activity, the undo entry can stay held after `moveCard` resolves and the +action reports `run end`. The activity flight lands, then the frame with +the card and undo entry commits. A timer polling presence or chat in a +separate run can still land independently, provided its readers don't +join the move's change. But a new badge pass computing from both the held +history and the fresh presence may join them; separate components alone +are not a guarantee. + +When debugging, compare the action end, the pending readers and flights, +and the write's `held`/`released` in the trace. Keep reads in the UI that +needs them. Use a separate run for independent UI state and `deferred` +when it's acceptable for an already loaded answer to lag (H-1). Don't +split the card and undo entry into separate writes just to make the button +appear faster. + ## 1. Reading from the server: an equation ```rx @@ -79,10 +109,30 @@ client's own state: a plain source the action's `catch` writes, shown beside the `found(await fetchUser(id), id)` with `fn found(it, id) => it == null ? throw NotFound(id) : it`. - Retry is `refresh x`. It is quiet (AC-4): the failure stays on screen until the new answer replaces it (H-12). +An `errored` region does not watch equations just because they are in scope. +Equations are lazy (E-3, E-8): if `shown` is false, `if shown { … }` skips +the body, and no `details` read there can trip the boundary. If the region +should report missing details even when their view is hidden, read them +first, inside the region: + +```rx +errored fallback(e) {

{e.message}

} { + loading fallback {

Loading…

} { + if details && shown {

{details.title}

} + } +} +``` + +This also demands the question while `shown` is false. If hiding the pane +should avoid the request, keep `shown` first. The MCP live model's +`failedUntripped` means the inspector saw an error but no instrumented +boundary currently reports that same error. It doesn't prove why no +boundary tripped, and inspecting a lazy equation can evaluate it. + ## 3. Writing to the server: an action ```rx -export source profile: Profile = await loadProfile() // a source with a question: it can take a guess +export source profile: Profile = await loadProfile() // a question source: the server answer can replace the guess export source saveError: string := "" export action save(next: Profile) { @@ -122,6 +172,9 @@ by what the screen should do: To guess a value a component gets as a prop, guess its own equation of it: `shown = props.title`, then `guess shown := t` in the action. A prop itself is read-only (O-4), and the guess shows wherever the child reads `shown`. +A writable `source x := seed` can take a guess too. Its plain writes land when the action commits; if nothing +writes it, the guess ends and the previous value shows again. No question or `refresh` is needed (AC-3). + ### Guesses go on the answer There is one shape for a write on server data. The server's answers are the stores the screen reads, and a write @@ -232,6 +285,23 @@ errors and guesses of the last visit then show on the next. ## 4. Things that look like bugs and aren't +### Progress and independent row saves + +One action groups its writes across its awaits. If a batch should commit +all at once, keep it in one action. If rows should settle separately, run +one action per row. Launch the row actions in separate runs, not by +calling them all synchronously from one handler (that can join their +changes). For a bulk control, an imported JS dispatcher can schedule each +row callback in a separate task. + +For progress on a single long operation, keep a separate progress source. +Publish progress from independent callbacks, or use `onFlush` to schedule +a separate write at a known milestone. Don't write progress into the +answer the operation already holds. A reader that derives from both +progress and the held answer can join the changes; render progress on its +own if it must stay responsive. The final result still belongs in the +action that awaited it. + - **A plain write in an action doesn't show until the server answers.** That's the hold. Use `guess` or `onFlush` (the table above). Don't move the code into a plain handler to escape it. - **A declined row guess stays until another action's re-ask lands.** While an action's `refresh` of the list is @@ -276,7 +346,78 @@ a value; an effect is for sending a value somewhere else (a parent's `on…` han a page belongs in a component that stays (pass it down, report changes up with an `on…` handler). - **Order**: two effects that fire in the same change run in no promised order (EF-6). -## 7. Forms +## 7. Polling, a log, and a sound per message + +A timer is a JS primitive (MO-10), declared once: + +```rx +export pure fn createTicker(ms: number): ref number +``` + +`tick = createTicker(2000)` is an instantiation. It is a number that moves. Nothing else about time is in the language. + +**Poll every n seconds.** An effect on the tick calls an action. The action does the fetch. The effect does not. + +```rx +tick = createTicker(2000) +action poll() { + try { status := await loadStatus() } + catch (e) { status := e.message } +} +effect (tick) { poll() } +``` + +**Re-ask a question without a dummy argument.** A question re-asks when its inputs change (ST-5). Passing the tick into `whoIsHere(id, tick)` so the call changes is a dummy. `refresh` re-runs an `await` equation for the same inputs, quietly (AC-4): the last answer stays up. + +```rx +tick = createTicker(5000) +here = await whoIsHere(boardId) +effect (tick) { refresh here } +``` + +**An append-only log with a cursor.** The log is a keyed source. This example +assumes the server returns all rows newer than the cursor, with a stable `seq` +and `id` on each row. Merge by id and sort by server sequence so overlapping +responses don't duplicate or reorder messages. Advance the cursor only forward. + +```rx +source log: Message[] key id := [] +source cursor := 0 +action poll() { + try { + let r = await messagesSince(boardId, cursor) + log := old => [...old.filter(m => !r.messages.some(n => n.id == m.id)), ...r.messages] + .sort((a, b) => a.seq - b.seq) + cursor := prev => prev > r.cursor ? prev : r.cursor + } catch (e) { err := e.message } +} +effect (tick) { poll() } +``` + +**A sound, or any other effect, for each message in a burst.** Several messages handled in one turn are one change (W-3): the functional writes compose, and an effect runs once, after that change has settled (EF-2). `onFlush` and `onSettled` also run once for the change, not once per updater. Leave a record in the state as you reduce, and play the new records from an effect on the counter. The effect runs after the commit, against the store that is on screen. + +In the `.rx` module: + +```rx +import { fresh, reduce, play } from "./live" +source live := fresh() +action dispatch(m) { + live := s => reduce(s, m) +} +effect (live.fxSeq) { play(live) } +``` + +In the JS module, `fresh` returns `{ fxSeq: 0, fx: [] }`. `reduce` applies the +message and appends `{ seq: ++s.fxSeq, message: m }` to `s.fx` in the same write. +`play` walks the committed records in sequence order and plays only those +after its last-played sequence. Keep that cursor per consumer, not in a JS +singleton shared by multiple instances. For a long-lived queue, drop records +only after they have been consumed. + +In `live.d.rx`, declare the reducer as `export fn reduce(s: LiveState, m: Message): void`. +`reduce` mutates the draft it is given and nothing else. Declare it `fn`, not `pure fn`: a pure function must not mutate, and this one does. `fn` is io, so call it from the action, which is imperative. A `pure fn` here would be a lie so the call would type-check from reactive scope. It does not need to. + +## 8. Forms A draft seeded once from loaded data is a source in the form's component, seeded with `peek`: `source name := peek(props.initial.name)`. It belongs to the user from then on; a save never resets it. diff --git a/guide/diagnostics.md b/guide/diagnostics.md index f2ddad76..7743a23f 100644 --- a/guide/diagnostics.md +++ b/guide/diagnostics.md @@ -97,6 +97,42 @@ export default component App() { } ``` +### JSX_TERNARY + +`c ? a : b` is an expression, and markup is not an expression. A branch of elements is `{if c { … } else { … }}`. + +```rx before +export default component App() { + source c := true +

{c ? : ""}

+} +``` + +```rx after +export default component App() { + source c := true +

{if c { } else { }}

+} +``` + +### FOR_INDEX + +`for` binds one name. The index is `xs.indexOf(x)` in the body, or map the list to pairs first. + +```rx before +export default component App() { + source xs := [1] + {for x, i in xs {

{x}

}} +} +``` + +```rx after +export default component App() { + source xs := [1] + {for x in xs {

{x} {xs.indexOf(x)}

}} +} +``` + ### ASSIGNMENT A source is written with `:=` as a statement, in a handler or an action (W-1). There is no `=`, `+=` or `++` on state. @@ -249,6 +285,12 @@ by then it may have changed (a rename accepted), be somewhere else (an earlier m action still holds, so the screen loses the edit or shows the row twice. When the answer doesn't say where a row is now (a move answers only where it went), re-ask the answers it left and joined with `refresh`. +Even `let id = entry.id` inside the action is still a projection of the row under AC-1g. If the id +identifies what the user asked for, pass just that primitive from the handler: change +`finish(entry)` to `finish(entry.id)` and `action finish(entry: Entry)` to `action finish(id: string)` +(or `number`, if that's the id type). Use `id` to find the current row inside the functional write; +don't carry the displayed row or its fields into the answer. + ```rx before type Card = { id: number; title: string } export default component App() { @@ -296,8 +338,9 @@ export default component App() { ### SNAPSHOT_ARGUMENT -A `fn` that declares state (an effect, a source) reads its value parameters once. Declare the parameter `ref` to pass -the reactive value itself, or pass `peek(…)` to say a snapshot is meant (E-10). +A block `fn` with declarations (including equations) reads its value parameters once. Declare the parameter `ref` +to pass the reactive value itself, or pass `peek(…)` to say a snapshot is meant (E-10). For a value-only calculation, +inline the equation: `fn size(xs) { n = xs.length; n }` becomes `fn size(xs) => xs.length`. ```rx before export default component App() { @@ -768,6 +811,44 @@ export default component App() { } ``` +### TYPE_IMPORT + +A `.d.rx` imports types only (MO-8e): `import { T, U as V } from "./x"`, from another `.d.rx` or an `.rx` `export type`. A function is a value. Copying the type into the file was the workaround; import the type instead. + +```rx +-- module: ./fns.d.rx +export pure fn fetch(): string + +-- module: ./api.d.rx +import { fetch } from "./fns" +export pure fn g(x: number): number +``` + +Import `Card`, not `fetch`. + +### DEAD_TYPED_BOUNDARY + +A typed `errored fallback(e: X)` wraps a catch-all with a static fallback. The catch-all takes `X` first and its static +fallback cannot fail into the typed region (R-f-4). Put the typed boundary inside the catch-all. + +```rx before +error NotFound +export default component App() { + errored fallback(e: NotFound) {

{e.message}

} { + errored fallback {

failed

} {

x

} + } +} +``` + +```rx after +error NotFound +export default component App() { + errored fallback(e) {

{e.message}

} { + errored fallback(e: NotFound) {

{e.message}

} {

x

} + } +} +``` + ### CATCH_NOT_ON_AWAIT A `catch` follows something other than an `await` (R-f-4). A value that failed is shown where it is read, by an @@ -962,6 +1043,11 @@ export default component App() { The name is not declared where it is read. A component sees its declaration site, not its caller (RG-7a): pass the value as a prop, provide it in a context, or import it. +JavaScript globals are not in scope (SV-7a). For example, put `export const Number = globalThis.Number` in +`js-globals.js` and write `import pure { Number } from "./js-globals.js"` in `.rx` +to convert values in reactive scope. For `Math`, prefer exporting the operation you +need, e.g. `export const floor = Math.floor`, then `import pure { floor } from "./js-globals.js"`. + ```rx before component Row(props) {

{caption}

} component List(props) { @@ -1231,6 +1317,34 @@ the await, `await viewport() -> 0` (SV-7b). The browser's HTML parser rewrites some nestings (a `` outside a table, a `
` inside a `

`), so the page the server sends is not the tree the client builds and hydration fails (SV-7d). Nest the elements the way HTML allows. +### STYLE_SCOPE + +A component's ``, CSS-5). + +```rx before +component Row() { +

  • x
  • +} +export default component App() { + + +} +``` + +```rx after +component Row() { + +
  • x
  • +} +export default component App() { + +} +``` + ### STYLE_PLACEMENT A view has one `;`, { filename: "class-map.tsrx", generate: "dom" }) as { code: string }; const m = /export const __s = (\{[\s\S]*?\});/.exec(r.code); return `(${m ? m[1].replace(/\n\s*/g, " ").replace(/: "[^"]*"/g, ': "" as string') : "{}"} as const)`; } // 07 CSS-5: TSRX's class map, as its typecheck projection writes it case "call": return `${go(e.f)}(${e.args.map(go).join(", ")})`; case "arr": return `[${e.items.map(go).join(", ")}]`; - case "rec": return `({ ${e.fields.map(f => "spread" in f ? `...${go(f.spread)}` : `${J(f.key)}: ${go(f.v)}`).join(", ")} })`; + case "as": return `(${go(e.e)} as ${e.ty})`; + case "rec": return `({ ${e.fields.map(f => "spread" in f ? `...${go(f.spread)}` : `${"computed" in f ? `[${go(f.computed)}]` : J(f.key)}: ${go(f.v)}`).join(", ")} })`; case "spread": return `...${go(e.e)}`; case "omit": return `__.omit(${[go(e.e), ...e.keys.map(k => J(k))].join(", ")})`; case "fn": { const ps = e.params.join(", "); - if (!e.stmts) return `((${ps}) => ${this.expr(e.body, imp, self)})`; - const w = new W(); const saved = this.w; this.w = w; this.stmts(e.stmts, " "); this.w = saved; - return `(${hasAwait(e.stmts) ? "async " : ""}(${ps}) => {\n${w.out.join("\n")}\n})`; + const names = imp ? this.handlerSnaps(e) : []; // TY-2: a handler's reads are snapshots, so a view branch does not narrow them + const saved = this.rename; + if (names.length) { this.rename = new Map(saved); for (const n of names) this.rename.set(n, `__s_${n}`); } + let inner: string; let async = false; + if (!e.stmts) inner = this.expr(e.body, imp, self); + else { async = hasAwait(e.stmts); const w = new W(); const sw = this.w; this.w = w; this.stmts(e.stmts, " "); this.w = sw; inner = w.out.join("\n"); } + this.rename = saved; + if (!names.length) return e.stmts ? `(${async ? "async " : ""}(${ps}) => {\n${inner}\n})` : `((${ps}) => ${inner})`; + const params = names.map(n => `__s_${n}: __W_${n}`).join(", "); + const args = names.join(", "); + return e.stmts ? `((${ps}) => ((${params}) => {\n${inner}\n})(${args}))` : `((${ps}) => ((${params}) => ${inner})(${args}))`; } case "serverfn": { // SF-1d: an async function, its wire checked (TY-5a) const ps = e.params.map((n, i) => `${n}${e.ptypes?.[i] ? `: ${e.ptypes[i]}` : ""}`).join(", "); diff --git a/ref/types/run.ts b/ref/types/run.ts index e06ac25c..f9bf6f32 100644 --- a/ref/types/run.ts +++ b/ref/types/run.ts @@ -11,14 +11,14 @@ import { parseScenario, moduleSet, type Scenario } from "../src/scenario.ts"; import { checkModules } from "../src/check.ts"; import { projectModules, PRELUDE, type Projected } from "./project.ts"; import { execFileSync } from "node:child_process"; -import { existsSync } from "node:fs"; +import { existsSync, statSync } from "node:fs"; import { loadModules } from "../src/modules.ts"; const rxc = fileURLToPath(new URL("../../compiler/target/release/rxc", import.meta.url)); /** RX_CRATE=1: the crate's projection of the program, read from the same files ref/ reads. */ function crateProjection(sc: Scenario, src: string): Projected[] { const files: Record = {}; - const read = (p: string) => { const s = p === sc.entry ? src : sc.modules.get(p) ?? (existsSync(p) ? readFileSync(p, "utf8") : undefined); if (s !== undefined) files[p] = s; return s; }; + const read = (p: string) => { const s = p === sc.entry ? src : sc.modules.get(p) ?? (existsSync(p) && statSync(p).isFile() ? readFileSync(p, "utf8") : undefined); if (s !== undefined) files[p] = s; return s; }; loadModules(sc.entry, read); const out = JSON.parse(execFileSync(rxc, ["project"], { input: JSON.stringify([{ id: 0, entry: sc.entry, files }]), maxBuffer: 1 << 28 }).toString()); return out.programs[0].files; diff --git a/runtime/test.mjs b/runtime/test.mjs index f9e8a480..520bade7 100644 --- a/runtime/test.mjs +++ b/runtime/test.mjs @@ -19,6 +19,11 @@ try { for (const [cond, build] of [["browser", "web"], ["node", "server"]]) { const keys = execFileSync(process.execPath, ["--conditions=" + cond, "--input-type=module", "-e", probe], { cwd: tmp }).toString().trim(); check(`${build} build (${cond})`, keys.includes("createApp"), keys); + const api = `import assert from "node:assert/strict"; import { createApp } from "@reactivescript/runtime"; + assert.throws(() => createApp({ root: null }).api("load"), /MISSING_TEST_API.*load.*createApp/); + assert.equal(createApp({ root: null, api: { load: () => "loaded" } }).api("load")(), "loaded");`; + execFileSync(process.execPath, ["--conditions=" + cond, "--input-type=module", "-e", api], { cwd: tmp }); + check(`${build} reports a missing test API and accepts an injected one`, true); } const { app: compile } = createRequire(import.meta.url)("../compiler/index.js"); const out = JSON.parse(compile(path.resolve(here, "../examples/todo.rx"), "ssr")); diff --git a/scenarios/S-action-input.md b/scenarios/S-action-input.md new file mode 100644 index 00000000..27f6d981 --- /dev/null +++ b/scenarios/S-action-input.md @@ -0,0 +1,28 @@ +# S-action-input — action arguments survive selection reset + +Rules: AC-1, W-4. An action retains the input values from its call, including +arrays and records nested inside an argument. + +## Program + +```rx +export default component App() { + source selected := ["a", "b"] + source packet := { nested: [["c"]] } + source sent := "" + action bulk(ids: string[], payload: { nested: string[][] }) { + await fetch("ready") catch (e) => "" + sent := ids.join(",") + ":" + (payload.nested[0]?.join(",") ?? "") + } +

    {selected.length}:{sent}

    +} +``` + +## Frames + +| instant | action | frame | +| --- | --- | --- | +| 0 | mount | `2:` | +| 1 | handler `bulk(selected, packet)` | `2:` | +| 2 | handler `selected := []; packet.nested[0] := []` | `0:` | +| 3 | resolve `"ready"` `"ok"` | `0:a,b:c` | diff --git a/scenarios/S-cast-1.md b/scenarios/S-cast-1.md new file mode 100644 index 00000000..86393da0 --- /dev/null +++ b/scenarios/S-cast-1.md @@ -0,0 +1,40 @@ +# S-cast-1 — A type assertion is TypeScript's, and a handler error stays on its line + +Rules exercised: 07 §3 (`e as T`), 13 TY-2. + +## Program + +```rx +type Status = "open" | "done" +export default component App() { + source s: string := "open" + source out: Status := "open" + +} +``` + +`as` is an assertion, erased where the program runs: the click writes `s`. The +projection keeps it, so `s as Status` is a `Status` and the write checks. + +## Frames + +| instant | action | frame | +| ------- | ----------------------------------- | ------ | +| 0 | mount | `open` | +| 1 | handler `out := s as Status` | `open` | + +## Rejected variants + +```rx +-- reject: PARSE +export default component App() { + source n := 1 + +} +``` + +A syntax error in a handler is that error, on its line. It is not `JS_LOCAL` +on the `let` above it: that `let` is a handler local. diff --git a/scenarios/S-check-1.md b/scenarios/S-check-1.md index 96450977..71b7b194 100644 --- a/scenarios/S-check-1.md +++ b/scenarios/S-check-1.md @@ -368,3 +368,11 @@ export default component App() { The second `` is rendered on a path with no provision (RG-7b): one path without it is enough. +## Rejected: action defaults + +```rx +-- reject: ACTION_PARAMETER_DEFAULT +type Intent = "edit" | "add" +export action save(operation: Intent = "edit") {} +export default component App() { } +``` diff --git a/scenarios/S-fail-5.md b/scenarios/S-fail-5.md new file mode 100644 index 00000000..d0e0cf9a --- /dev/null +++ b/scenarios/S-fail-5.md @@ -0,0 +1,57 @@ +# S-fail-5 — a typed error boundary wrapped by an inner catch-all is dead + +Rules: R-f-4. The catch-all takes `NotFound` first, so the typed fallback +never shows. + +## Program + +```rx +error NotFound +export default component App() { + errored fallback(e) {

    {e.message}

    } { + errored fallback(e: NotFound) {

    missing

    } {

    ok

    } + } +} +``` + +The typed boundary is inside the catch-all, which is where it can still see +`NotFound`. + +## Frames + +| instant | action | frame | +| --- | --- | --- | +| 0 | mount | `ok` | + +## Variant: a failure in the inner fallback reaches the outer region + +```rx +error NotFound +error Offline +export default component App() { + failed = throw Offline() + fallbackFailed = throw NotFound() + errored fallback(e: NotFound) {

    missing

    } { + errored fallback(e) {

    {fallbackFailed}

    } {

    {failed}

    } + } +} +``` + +| instant | action | frame | +| --- | --- | --- | +| 0 | mount | `missing` | + +## Rejected + +```rx +-- reject: DEAD_TYPED_BOUNDARY +error NotFound +export default component App() { + errored fallback(e: NotFound) {

    missing

    } { + errored fallback {

    failed

    } {

    x

    } + } +} +``` + +The inner catch-all wraps the children. `NotFound` never reaches the typed +fallback. diff --git a/scenarios/S-fail-6.md b/scenarios/S-fail-6.md new file mode 100644 index 00000000..1dce7387 --- /dev/null +++ b/scenarios/S-fail-6.md @@ -0,0 +1,24 @@ +# S-fail-6 — read order controls which failure is shown + +Rules: E-3, E-8, R-f-4. The guard can skip the `details` read entirely, +or demand it before deciding whether to show the title. + +## Program + +```rx +error Missing +export default component App() { + source shown := false + details = throw Missing() + errored fallback(e: Missing) {

    missing

    } { + if shown && details {

    title

    } + } +} +``` + +## Frames + +| instant | action | frame | +| --- | --- | --- | +| 0 | mount | | +| 1 | handler `shown := true` | `missing` | diff --git a/scenarios/S-fn-block.md b/scenarios/S-fn-block.md new file mode 100644 index 00000000..60088d43 --- /dev/null +++ b/scenarios/S-fn-block.md @@ -0,0 +1,49 @@ +# S-fn-block — declarations in a block fn instantiate + +Rules: E-9, E-10. Declarations in a block `fn` belong to the +instantiation. An arrow with a value expression needs no snapshot. + +## Program + +```rx +fn size(xs: number[]) => xs.length +export default component App() { + source xs := [1, 2] +

    {size(xs)}

    +} +``` + +## Frames + +| instant | action | frame | +| --- | --- | --- | +| 0 | mount | `2` | + +## Rejected + +```rx +-- reject: SNAPSHOT_ARGUMENT +fn total(xs: number[], k: number) { + fn twice(n: number) => n * 2 + base = xs.length + twice(base) + k +} +export default component App() { + source xs := [1, 2] + n = total(xs, 1) +

    {n}

    +} +``` + +```rx +-- reject: SNAPSHOT_ARGUMENT +fn first(id: number) { + rows = await fetch(id) catch (e) => "" + rows +} +export default component App() { + source id := 1 + row = first(id) +

    {row}

    +} +``` diff --git a/scenarios/S-handler-narrow-1.md b/scenarios/S-handler-narrow-1.md new file mode 100644 index 00000000..1ce6041e --- /dev/null +++ b/scenarios/S-handler-narrow-1.md @@ -0,0 +1,48 @@ +# S-handler-narrow-1 — A handler reads a snapshot, so a view branch does not narrow it + +Rules exercised: 13 TY-2. A read in a handler is taken when the handler runs, +not when the view branch was chosen. The branch may no longer hold, so +narrowing the handler's read would be unsound. Snapshot it and narrow the +local. + +## Program + +```rx +type Item = { id: number } +export default component App() { + source detail: Item | null := null + {if detail != null { + + }} +} +``` + +`{detail.id}` is a read of the branch, re-checked while the branch is live, so +it is narrowed. The handler snapshots `detail` into `d` and narrows that: `d` +does not change before the read. + +## Frames + +| instant | action | frame | +| ------- | ------ | ----- | +| 0 | mount | `` | + +## Rejected variants + +```rx +-- types: TS18047 +type Item = { id: number } +export default component App() { + source detail: Item | null := null + {if detail != null { + } ``` + +``` +-- reject: JSX_TERNARY +export default component App() { + source c := true +

    {c ? : ""}

    +} +``` + +``` +-- reject: FOR_INDEX +export default component App() { + source xs := [1] + {for x, i in xs {

    {x}

    }} +} +``` diff --git a/scenarios/S-pure-globals.md b/scenarios/S-pure-globals.md new file mode 100644 index 00000000..9bd56476 --- /dev/null +++ b/scenarios/S-pure-globals.md @@ -0,0 +1,40 @@ +# S-pure-globals — pure JS operations without an import + +Rule: SV-7a. Native conversions and selected static members are value calculations. + +## Program + +```rx +export default component App() { + data = JSON.parse(JSON.stringify({ a: 2 })) + copy = Object.fromEntries(Object.entries(data)) + names = Object.keys(copy) + values = Object.values(copy) + count = Math.round(Number("2.1")) + Number.parseInt("3") + text = String(count) + String.fromCharCode(33) +

    {Array.isArray(values)}:{names[0]}:{values[0]}:{text}

    +} +``` + +## Frames + +| instant | action | frame | +| --- | --- | --- | +| 0 | mount | `true:a:2:5!` | + +## Rejected + +```rx +-- reject: UNBOUND +export default component App() {

    {Math.random()}

    } +``` + +```rx +-- reject: UNBOUND +export default component App() {

    {Date.now()}

    } +``` + +```rx +-- reject: UNBOUND +export default component App() {

    {Object.assign({}, {})}

    } +``` diff --git a/scenarios/S-source-write-1.md b/scenarios/S-source-write-1.md new file mode 100644 index 00000000..5079060e --- /dev/null +++ b/scenarios/S-source-write-1.md @@ -0,0 +1,27 @@ +# S-source-write-1 — A source's type is its widened type, and a write checks that + +Rules exercised: 13 TY-2. A source is written later, so its initializer's +literal is not its type, and a branch that narrows a read does not narrow +what a write may store. + +## Program + +```rx +export default component App() { + source open := false + {if open { }} + +} +``` + +`open` is a boolean: `false` says what it starts as, not what it may become. +Inside `{if open}` the read is `true`, and `open := false` is still a boolean +write — the branch does not change the source's type. + +## Frames + +| instant | action | frame | +| ------- | ---------------------- | ----- | +| 0 | mount | `n` | +| 1 | handler `open := true` | `closey` | +| 2 | handler `open := false` | `n` | diff --git a/scenarios/S-surface-2.md b/scenarios/S-surface-2.md index fa3197d8..22b06c83 100644 --- a/scenarios/S-surface-2.md +++ b/scenarios/S-surface-2.md @@ -88,3 +88,18 @@ export default component App() { ``` One stylesheet per view (TSRX: "fragments can only have one style tag"). + +```rx +-- reject: STYLE_SCOPE +component Row() { +
  • x
  • +} +export default component App() { + + +} +``` + +`Row` is its own view (CSS-2). `App`'s `.row` does not style it. Give `Row` its own `