diff --git a/.github/workflows/compiler.yml b/.github/workflows/compiler.yml index 0faa5d842..1672c499a 100644 --- a/.github/workflows/compiler.yml +++ b/.github/workflows/compiler.yml @@ -10,12 +10,52 @@ 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: dev lowering, flags: "--lower --dev" } + 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 e4b64a8b2..f2abdc6a2 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/Cargo.lock b/compiler/Cargo.lock index 3b4082923..e0593468e 100644 --- a/compiler/Cargo.lock +++ b/compiler/Cargo.lock @@ -990,6 +990,8 @@ dependencies = [ name = "reactivescript" version = "0.3.1" dependencies = [ + "dragonbox_ecma", + "htmlize", "indexmap", "napi", "napi-build", diff --git a/compiler/Cargo.toml b/compiler/Cargo.toml index 8ac3e98ad..26d871011 100644 --- a/compiler/Cargo.toml +++ b/compiler/Cargo.toml @@ -23,6 +23,8 @@ node = ["dep:napi", "dep:napi-derive"] [dependencies] indexmap = "2" regex = "1" +htmlize = { version = "1", features = ["unescape"] } +dragonbox_ecma = "0.1" serde_json = { version = "1", features = ["preserve_order"] } # CP-1b: Solid's compiler, at the commit ref/ runs on (ref/SOLID_NEXT), and the Oxc release it is built against (CP-1c: # the program crosses the seam, so the versions must match) diff --git a/compiler/README.md b/compiler/README.md index 17769fb84..9169cf2a1 100644 --- a/compiler/README.md +++ b/compiler/README.md @@ -29,16 +29,18 @@ cargo build --release target/release/rxc check ../examples/todo.rx # diagnostics target/release/rxc check --json ../examples/todo.rx # … with ranges, for an editor or an agent (CP-8d) target/release/rxc project ../examples/todo.rx # the TSX projection, with mappings onto .rx (CP-8c) -target/release/rxc model ../examples/todo.rx # the resolved model, as JSON +target/release/rxc model ../examples/todo.rx # the resolved model, as JSON (keys relative to the cwd, CP-6f) target/release/rxc serve # a language server's requests, a JSON line each (CP-8e) cargo build --lib --release --target wasm32-unknown-unknown # … the same requests as WebAssembly (src/wasm.rs), what the server loads target/release/rxc compile ../examples/todo.rx --out out # modules (dom; --target ssr|universal), source maps onto .rx, style.css target/release/rxc app ../examples/todo.rx # the same as JSON, imports by .rx path: what the Vite front end gets +target/release/rxc app ../examples/todo.rx --dev # a dev build: creating calls under __rt.key (CP-4b; --root dir, else the cwd); also compile target/release/rxc check --spa ../examples/todo.rx # a client-only build: a first load nothing holds is an error (08 CN-3d); also compile, app npm --prefix ../ref run crate # CP-5: the crate against ref/ on every program npm --prefix ../ref run crate -- --project # … and the TSX projection, text for text, every mapping checked RX_CRATE=1 npm --prefix ../ref run types # the types scenarios, on the crate's projection npm --prefix ../ref run crate -- --lower # … and the lowered JavaScript, for every target, and its source maps +npm --prefix ../ref run crate -- --lower --dev # … the same for dev builds RX_CRATE=1 npm --prefix ../ref run compiled # the scenarios, run on the crate's output RX_CRATE=1 npm --prefix ../ref run ssr # … served and hydrated from the crate's output ``` diff --git a/compiler/index.d.ts b/compiler/index.d.ts index 8acd2a594..ef1442292 100644 --- a/compiler/index.d.ts +++ b/compiler/index.d.ts @@ -12,6 +12,13 @@ export declare const __napiBindingTarget: 'native' | 'wasm32-wasi' | 'wasm32-was /** * `rxc app`'s answer, as JSON text: the program `entry` (an absolute path) starts, for `target` (dom, ssr or * universal; dom by default) over `module_name` (`@solidjs/web` by default). `spa`: a client-only build (dom, not - * hydratable), checked under 08 CN-3d. + * hydratable), checked under 08 CN-3d. `dev`: a dev build — each source's and equation's creating calls run under its + * key (`__rt.key`), its module relative to `root` (the process's cwd by default). */ -export declare function app(entry: string, target?: string | undefined | null, moduleName?: string | undefined | null, spa?: boolean | undefined | null): string +export declare function app(entry: string, target?: string | undefined | null, moduleName?: string | undefined | null, spa?: boolean | undefined | null, dev?: boolean | undefined | null, root?: string | undefined | null): string + +/** + * `rxc model`'s answer, as JSON text: the resolved model (CP-6) of every module the programs `entries` (absolute paths) + * start, each once, with module paths and keys relative to `root` (the process's cwd by default). + */ +export declare function model(entries: Array, root?: string | undefined | null): string diff --git a/compiler/index.js b/compiler/index.js index c1c473a7b..72ee78d87 100644 --- a/compiler/index.js +++ b/compiler/index.js @@ -836,3 +836,4 @@ function __napiStampBindingTarget(exportsObject, target) { module.exports.__napiBindingTarget = __napiStampBindingTarget(nativeBinding, __napiLoadedBindingTarget) module.exports = nativeBinding module.exports.app = nativeBinding.app +module.exports.model = nativeBinding.model diff --git a/compiler/src/app.rs b/compiler/src/app.rs index f014d014d..531bf61f6 100644 --- a/compiler/src/app.rs +++ b/compiler/src/app.rs @@ -1,8 +1,9 @@ //! A program compiled for a bundler (spec/11 CP-4b): every module of the program `entry` starts, through Solid's //! compiler for `target`, each importing its dependencies by `.rx` path, with the program's stylesheet. What `rxc app` //! prints and the Node-API build (`src/node.rs`) returns to `@reactivescript/compiler/vite`. -use crate::check::check_modules; -use crate::emit::{compile_linked, lower_view, Target}; +use crate::check::{check_modules, check_modules_in}; +use crate::emit::{lower_view, Target}; +use crate::model::module_key; use crate::modules::load_modules; use serde_json::{json, Map, Value}; use std::path::Path; @@ -26,6 +27,12 @@ pub fn target(name: &str) -> Target { /// `{entry, css, modules: {path: {code, map, css}}}` (the program's stylesheet, and each module's own), or `{diagnostics: [...]}` / `{error}`. `entry` is an absolute path. /// `spa`: a client-only build, checked under 08 CN-3d. pub fn app(entry: &str, target: Target, module_name: &str, spa: bool) -> Value { + app_dev(entry, target, module_name, spa, None) +} + +/// `app`, for a dev build when `dev` is set: each source's and equation's creating calls run under its key +/// (`emit::compile_dev`); `dev` is the project root the keys' modules are relative to. +pub fn app_dev(entry: &str, target: Target, module_name: &str, spa: bool, dev: Option<&str>) -> Value { // module keys are POSIX paths (`modules::join_path`); Windows takes `D:/a/b.rx` as it takes `D:\a\b.rx` let entry = &entry.replace('\\', "/"); (|| { @@ -43,7 +50,7 @@ pub fn app(entry: &str, target: Target, module_name: &str, spa: bool) -> Value { if !checked.diags.is_empty() { return Err(json!({ "diagnostics": checked.diags.iter().map(|d| { let mut j = d.to_json(); if j["file"].is_null() { j["file"] = json!(set.entry); } j }).collect::>() })); } - let out = compile_linked(&set, &[], true).map_err(|e| json!({ "error": format!("{entry}: not compiled: {}", e.0) }))?; + let out = crate::emit::compile_dev(&set, &[], true, dev).map_err(|e| json!({ "error": format!("{entry}: not compiled: {}", e.0) }))?; let mut modules = Map::new(); for (name, module) in &out.files { let path = &out.paths[name]; @@ -51,7 +58,35 @@ pub fn app(entry: &str, target: Target, module_name: &str, spa: bool) -> Value { let l = lower_view(module, path, target, module_name, Some((path, &text))).map_err(|e| json!({ "error": e }))?; modules.insert(path.clone(), json!({ "code": l.code, "map": l.map, "css": out.module_css[name] })); } - Ok(json!({ "entry": set.entry, "css": out.css, "modules": modules })) + let mut result = json!({ "entry": set.entry, "css": out.css, "modules": modules }); + if dev.is_some() { + result["declarations"] = json!(set.declarations.keys().collect::>()); + } + Ok(result) })() .unwrap_or_else(|e| e) } + +/// `rxc model`'s answer for the programs `entries` start (absolute paths): each module's resolved model (CP-6) once, in +/// load order, its `file` and its symbols' keys relative to `root`. `{error}` when an entry does not load. +pub fn model(entries: &[String], root: &str) -> Value { + let mut out: Vec = vec![]; + let mut seen = std::collections::HashSet::new(); + for entry in entries { + let entry = entry.replace('\\', "/"); + let set = match load_modules(&entry, &read_disk) { + Ok(s) => s, + Err(e) => return json!({ "error": e.0 }), + }; + let checked = check_modules_in(&set, false, Some(root)); + for p in &set.order { + if !seen.insert(p.clone()) { + continue; + } + let mut m = checked.models[p].clone(); + m["file"] = json!(module_key(p, Some(root))); + out.push(m); + } + } + Value::Array(out) +} diff --git a/compiler/src/ast.rs b/compiler/src/ast.rs index 79e82bb78..e7c719e1b 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 ef628f7b7..8d4935c41 100644 --- a/compiler/src/check.rs +++ b/compiler/src/check.rs @@ -9,7 +9,7 @@ use crate::ast::*; use crate::content::{misnested, misnested_inside, Shape, P_CLOSERS, P_SCOPE}; use crate::infer::{inferred_action, run_findings, scalar_type, trigger_text, Code, RunOpts}; -use crate::model::{ModelBuilder, ModelSymbol}; +use crate::model::{decl_keys, module_key, ModelBuilder, ModelSymbol}; use crate::modules::ModuleSet; use crate::parse::{js_trim, JsDecl, Part, Shape as FShape}; use crate::signature::{Catch, CompSig, ExportSig, ModSig, Own, PropSig, SigParam, HOLD}; @@ -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 { @@ -247,6 +252,8 @@ struct Sym<'a> { arity: Option, /// RG-4b: the props of `component C()`, which declares none — C's name: reading them is UNBOUND no_props: Option, + /// CP-6: a source's or an equation's identity (model.rs `decl_keys`) + key: Option, } impl<'a> Sym<'a> { fn new(kind: SymKind, name: &str, region: RId, line: i64) -> Self { @@ -284,6 +291,7 @@ impl<'a> Sym<'a> { reader: false, arity: None, no_props: None, + key: None, } } } @@ -356,6 +364,13 @@ fn snapshot_reads<'a>(n: Node<'a>, caught: bool, locals: &mut HashSet, o fn field_of(name: &str) -> String { if name == "..." { "*".into() } else { name.to_string() } } +fn index_field(e: &Expr) -> String { + match &e.k { + ExprKind::Lit(Lit::Str(s)) => s.clone(), + ExprKind::Lit(Lit::Num(n)) => if *n == 0.0 { "0".into() } else { dragonbox_ecma::Buffer::new().format(*n).into() }, + _ => "*".into(), + } +} /// an argument as a message shows it: `x={…}`, or `{...…}` for a spread fn arg_show(field: &str) -> String { @@ -395,7 +410,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 +425,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 +497,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 +534,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), } } @@ -854,6 +872,8 @@ pub struct Opts<'a> { /// CN-3d: a client-only build (no SSR): a first load nothing holds shows nothing, so every reader that can have /// no value yet needs a `loading` region above it, as a client question's reader does (SV-7b). pub spa: bool, + /// the project root a key's module is relative to (`decl_keys`); None: the path as the loader has it + pub root: Option<&'a str>, } pub struct Checker<'a> { @@ -901,6 +921,8 @@ pub struct Checker<'a> { reader_f: Vec<(RId, &'a Expr, i64, Fails)>, arg_r: Vec<(usize, String)>, arg_f: Vec<(usize, String, Fails)>, + keys: HashMap<*const Decl, String>, + boundaries: HashMap<*const Markup, usize>, } pub struct CheckResult { @@ -923,13 +945,32 @@ pub struct Checked { pub sigs: IndexMap, pub models: IndexMap, } + +/// AST sites and the matching resolved region IDs. Only the dev emitter consumes these. +pub fn boundary_regions(set: &ModuleSet) -> HashMap<*const Markup, usize> { + let mut sigs = set.signatures.clone(); + let mut sites = HashMap::new(); + for path in &set.order { + let p = &set.programs[path]; + let mut c = Checker::new(Opts { sigs: &sigs, file: Some(path.clone()), declarations: &set.declarations, spa: false, root: None }); + c.run(p); + let sig = c.signature(p); + sites.extend(c.boundaries); + sigs.insert(path.clone(), sig); + } + sites +} /// CN-4b / MO-3: check every module of a program, dependencies first, each against its imports' signatures only. pub fn check_modules(set: &ModuleSet, spa: bool) -> Checked { + check_modules_in(set, spa, None) +} +/// `check_modules`, each symbol's key naming its module relative to `root` (the project root). +pub fn check_modules_in(set: &ModuleSet, spa: bool, root: Option<&str>) -> Checked { let mut sigs: IndexMap = set.signatures.clone(); let mut diags = set.diags.clone(); let mut models = IndexMap::new(); for path in &set.order { - let r = check_with_signature(&set.programs[path], Opts { sigs: &sigs, file: Some(path.clone()), declarations: &set.declarations, spa }); + let r = check_with_signature(&set.programs[path], Opts { sigs: &sigs, file: Some(path.clone()), declarations: &set.declarations, spa, root }); diags.extend(r.diags); sigs.insert(path.clone(), r.sig); models.insert(path.clone(), r.model); @@ -978,6 +1019,8 @@ impl<'a> Checker<'a> { reader_f: vec![], arg_r: vec![], arg_f: vec![], + keys: HashMap::new(), + boundaries: HashMap::new(), } } @@ -1054,11 +1097,13 @@ impl<'a> Checker<'a> { question: if s.kind == SymKind::Source { Some(s.question) } else { None }, io: s.io, from: s.imported.clone(), + key: s.key.clone(), } }) } pub fn run(&mut self, p: &'a Program) { + self.keys = decl_keys(p, &module_key(self.opts.file.as_deref().unwrap_or("main.rx"), self.opts.root)); let r = self.region(None, "program", false, None); let root = self.env(None, r); self.root_env = Some(root); @@ -1079,6 +1124,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 `\n

badge

\n}\n`; - writeFileSync(badge, style("rgb(0, 0, 255)")); - const server = await vite.createServer(config(dir, "styled/main.rx")); await server.listen(0); - const url = server.resolvedUrls.local[0]; - const color = page => page.$eval(".badge", e => getComputedStyle(e).color); - const until = async (page, want, what) => { - for (let i = 0; i < 40 && await color(page).catch(() => "") !== want; i++) await page.waitForTimeout(100); - const got = await color(page).catch(e => e.message.split("\n")[0]); if (got !== want) throw new Error(`${what}: color ${got}, not ${want}`); - }; - await drive("styles (dev)", url, async page => { - await until(page, "rgb(0, 0, 255)", "first load"); - writeFileSync(badge, style("rgb(255, 0, 0)")); - await until(page, "rgb(255, 0, 0)", "after the edit"); - await page.reload(); await until(page, "rgb(255, 0, 0)", "after a reload"); - const fresh = await browser.newPage(); - try { await fresh.goto(url); await until(fresh, "rgb(255, 0, 0)", "in a new page"); } finally { await fresh.close(); } + await drive("todo (dev)", server.resolvedUrls.local[0], async page => { + await todo(page); + // 11 CP-4b `key`: the dev client runs each source's and equation's creating calls under its key + const code = (await server.transformRequest("/src/todo.rx"))?.code ?? ""; + if (!code.includes('__rt.key("src/todo.rx||todos", () =>')) throw new Error("the dev build keys no declaration"); }); await server.close(); } -if (!filter || "cold".includes(filter)) { // a dependency asked for before its entry, as Vitest's `fsModuleCache` leaves it - const { default: rx } = await import(pathToFileURL(path.join(pkg, "vite.mjs")).href); - const root = project("cold", "shop/main.rx"), catalog = path.join(root, "src/shop/catalog.rx"); - const ctx = (id, moduleId) => ({ id, moduleId, root, ssr: false, solid: { generate: "dom", hydratable: false }, addWatchFile() {} }); - try { - // a commented-out import is not an edge: read as one, it would make main.rx look imported and leave no entry - writeFileSync(catalog, readFileSync(catalog, "utf8") + `\n// import { x } from "./main.rx"\n`); - const warm = rx(); warm.compile("", ctx(path.join(root, "src/shop/main.rx"), path.join(root, "src/shop/main.rx"))); - const want = warm.compile("", ctx(catalog, `${catalog}?rx-dep`)).code; - const got = rx().compile("", ctx(catalog, `${catalog}?rx-dep`)).code; - if (got !== want) throw new Error("the dependency compiled cold differs from the one compiled after its entry"); - writeFileSync(catalog, readFileSync(catalog, "utf8") + "\nexport bad = missingName\n"); - let report = ""; - try { rx().compile("", ctx(catalog, `${catalog}?rx-dep`)); } catch (e) { report = e.message; } - if (!/catalog\.rx:\d+(:\d+)?: error /.test(report)) throw new Error(`a cold dependency that does not compile reports ${JSON.stringify(report.slice(0, 200))}`); - pass++; console.log("✓ cold dependency: compiled from the program that holds it, or that program's diagnostics"); - } catch (e) { fail++; console.log(`✗ cold dependency: ${e.message.split("\n")[0]}`); } -} -await browser.close(); console.log(`\n${pass} pass, ${fail} fail (vite ${vite.version}, @solidjs/vite-plugin ${JSON.parse(readFileSync(path.join(pluginDir, "package.json"), "utf8")).version})`); process.exit(fail ? 1 : 0); diff --git a/compiler/vite.mjs b/compiler/vite.mjs index ed6f02759..12c555439 100644 --- a/compiler/vite.mjs +++ b/compiler/vite.mjs @@ -13,12 +13,17 @@ // changes. The crate's output imports its dependencies as `./x.rx?rx-dep`, and a dependency is served from the build // of a program that contains it. A module several programs share is one module: its instance is keyed by its factory // (11 CP-4b `module`), not by its place in a program. +// +// Dev (Solid's `dev`, the client): each source's and equation's creating calls run under its key (11 CP-4b `key`), so +// the devtools see `rx:` names; a key's module is relative to the project root. If the project has +// `@reactivescript/map`, a program's entry also registers the program's map (`@reactivescript/map/live`), drawn from the +// resolved model, for the devtools' Map view. Builds that are not dev, and the server's, are as before. import { existsSync, readdirSync, readFileSync, statSync } from "node:fs"; import { createRequire } from "node:module"; import path from "node:path"; import { fileURLToPath } from "node:url"; -const { app } = createRequire(import.meta.url)("./index.js"); +const { app, model } = createRequire(import.meta.url)("./index.js"); const DEP = "rx-dep"; // the page each code points to: the package's copy (scripts/guide.mjs), else the repository's const GUIDE = [path.join(path.dirname(fileURLToPath(import.meta.url)), "guide/diagnostics.md"), path.join(path.dirname(fileURLToPath(import.meta.url)), "../guide/diagnostics.md")].find(existsSync) @@ -35,6 +40,9 @@ const isDep = moduleId => new URLSearchParams(moduleId.split("?")[1] ?? "").has( // `import __m0 from "./catalog.rx";` → `"./catalog.rx?rx-dep"` (one line each: the module's map is by line, CP-1c) const tagDeps = code => code.replace(/^(import \w+ from ")(\.{1,2}\/[^"?]*\.rx)(";?)$/gm, `$1$2?${DEP}$3`); +/** A source map (JSON text) for code that now starts `lines` lines later: each line is a `;` in `mappings`. */ +const shiftMap = (map, lines) => { const m = JSON.parse(map); m.mappings = ";".repeat(lines) + m.mappings; return JSON.stringify(m); }; + const RX_IMPORT = /^import\b[^"']*?\bfrom\s+(["'])(\.{1,2}\/[^"'?]*\.rx)\1/gm; /** The `.rx` files under `root` from which `file` is reached by imports: first those no other `.rx` file imports. */ function entriesOf(file, root) { @@ -58,32 +66,42 @@ function entriesOf(file, root) { return [...seen].sort().sort((a, b) => top(b) - top(a)); } +/** Dev: the lines a program's entry starts with when the project has `@reactivescript/map` — its map, registered for the + * devtools — or "" when it does not. The hook passes the resolved model to the optional integration. */ +function liveMap(entry, root) { + let req; + try { req = createRequire(path.join(root, "package.json")); req.resolve("@reactivescript/map/live"); } catch { return ""; } + const modules = JSON.parse(model([entry], root)); + return `import { registerModel as __rxMap } from "@reactivescript/map/live";\n__rxMap(${JSON.stringify(modules)}, { hot: import.meta.hot });\n`; +} + /** @returns {import("@solidjs/vite-plugin").Frontend} */ export default function rx() { - const builds = new Map(); // entry\0target\0moduleName\0spa → { entry, target, moduleName, spa, out, stamps } + const builds = new Map(); // entry\0target\0moduleName\0spa\0dev → { entry, target, moduleName, spa, dev, out, stamps } const fresh = b => [...b.stamps].every(([f, t]) => mtime(f) === t); - function build(entry, target, moduleName, spa) { - const key = `${entry}\0${target}\0${moduleName}\0${spa}`; + /** `dev`: the project root, for a dev build (keys relative to it); null otherwise. */ + function build(entry, target, moduleName, spa, dev = null) { + const key = `${entry}\0${target}\0${moduleName}\0${spa}\0${dev ?? ""}`; const prior = builds.get(key); if (prior && fresh(prior)) return prior; - const out = JSON.parse(app(entry, target, moduleName, spa)); + const out = JSON.parse(dev === null ? app(entry, target, moduleName, spa) : app(entry, target, moduleName, spa, true, dev)); if (out.modules) out.modules = Object.fromEntries(Object.entries(out.modules).map(([p, m]) => [path.resolve(p), m])); - const files = out.modules ? Object.keys(out.modules) : out.diagnostics ? [...new Set([entry, ...out.diagnostics.map(d => d.file)])] : [entry]; - const b = { entry, target, moduleName, spa, out, stamps: new Map(files.map(f => [f, mtime(f)])) }; + const files = out.modules ? [...Object.keys(out.modules), ...(out.declarations ?? [])] : out.diagnostics ? [...new Set([entry, ...out.diagnostics.map(d => d.file)])] : [entry]; + const b = { entry, target, moduleName, spa, dev, out, stamps: new Map(files.map(f => [f, mtime(f)])) }; builds.set(key, b); return b; } - const built = (file, target, moduleName, spa) => - [...builds.values()].filter(b => b.target === target && b.moduleName === moduleName && b.spa === spa && b.out.modules?.[file]); + const built = (file, target, moduleName, spa, dev) => + [...builds.values()].filter(b => b.target === target && b.moduleName === moduleName && b.spa === spa && b.dev === dev && b.out.modules?.[file]); /** A dependency: from a build of a program that has it, rebuilt if that program changed. */ - function containing(file, target, moduleName, spa, root) { - const has = built(file, target, moduleName, spa); + function containing(file, target, moduleName, spa, root, dev) { + const has = built(file, target, moduleName, spa, dev); const b = has.find(fresh) ?? has[0]; - if (b) return build(b.entry, target, moduleName, spa); + if (b) return build(b.entry, target, moduleName, spa, dev); // the entry's compile was skipped (Vitest's `fsModuleCache` served it), so find the program from the files let failed; for (const entry of entriesOf(file, root)) { - const found = build(entry, target, moduleName, spa); + const found = build(entry, target, moduleName, spa, dev); if (found.out.modules?.[file]) return found; if (!failed && found.out.diagnostics) failed = found; // the program holds it but does not compile: report why } @@ -98,13 +116,19 @@ export default function rx() { // 08 CN-3d: a client-only build (no SSR, nothing hydrates) has nothing to show on a first load nothing holds const spa = target === "dom" && solid.hydratable === false; const dep = isDep(moduleId); - const { out } = dep ? containing(file, target, moduleName, spa, path.resolve(root ?? process.cwd())) : build(file, target, moduleName, spa); + const base = path.resolve(root ?? process.cwd()); + const dev = solid.dev === true && target === "dom" ? base : null; + const { out, stamps } = dep ? containing(file, target, moduleName, spa, base, dev) : build(file, target, moduleName, spa, dev); if (out.diagnostics) throw new Error(report(out.diagnostics)); if (out.error) throw new Error(out.error); const m = out.modules[file]; - for (const p of Object.keys(out.modules)) if (p !== file) addWatchFile(p); + for (const p of stamps.keys()) if (p !== file) addWatchFile(p); + // dev: a program's entry registers its map, when the project has @reactivescript/map; the lines go first, and the + // module's map is shifted by them + const live = dev !== null && !dep ? liveMap(file, base) : ""; + const map = live && m.map ? shiftMap(m.map, live.split("\n").length - 1) : m.map; // CSS-4: each module links its own stylesheet, so a module several programs share links it once - return { code: tagDeps(m.code), map: m.map, css: m.css ?? "" }; + return { code: live + tagDeps(m.code), map, css: m.css ?? "" }; }, }; } diff --git a/examples/api.mjs b/examples/demo-api.mjs similarity index 94% rename from examples/api.mjs rename to examples/demo-api.mjs index b450b2c7c..af8765102 100644 --- a/examples/api.mjs +++ b/examples/demo-api.mjs @@ -1,4 +1,4 @@ -// A fake backend for running the examples in a browser (`ref/compile/build.ts`): every function answers after a delay. +// The injected backend for the browser demos (`ref/compile/build.ts`): each function answers after a delay. const later = (v, ms = 400) => new Promise(r => setTimeout(() => r(typeof v === "function" ? v() : v), ms)); const fail = (msg, ms = 400) => new Promise((_, j) => setTimeout(() => j(new Error(msg)), ms)); diff --git a/examples/notes/ui.rx b/examples/notes/ui.rx index f5141465b..441d966a5 100644 --- a/examples/notes/ui.rx +++ b/examples/notes/ui.rx @@ -5,6 +5,10 @@ import { open, save, saveError } from "./data.rx" export error TitleRequired() => "a note needs a title" component Row(props: { note: Note }) { + { 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 b67be29ec..37e28d3dd 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 f2ddad76d..7743a23f9 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 e06ac25c1..f9bf6f32e 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/build.mjs b/runtime/build.mjs index f771654ce..7bdebe0a9 100644 --- a/runtime/build.mjs +++ b/runtime/build.mjs @@ -2,7 +2,7 @@ // runs what the scenarios run: each is transpiled to dist/ as it is (Solid stays external, a peer of the app's), with // its declarations. import { execFileSync } from "node:child_process"; -import { mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { createRequire } from "node:module"; import { fileURLToPath } from "node:url"; import path from "node:path"; @@ -12,8 +12,17 @@ const here = path.dirname(fileURLToPath(import.meta.url)); const src = path.resolve(here, "../ref/compile"); const dist = path.join(here, "dist"); rmSync(dist, { recursive: true, force: true }); mkdirSync(dist); -for (const [from, to] of [["rt-web.ts", "web"], ["rt-server.ts", "server"]]) { - await build({ entryPoints: [path.join(src, from)], outfile: path.join(dist, `${to}.js`), format: "esm", platform: "neutral", target: "es2022", bundle: true, packages: "external", logLevel: "warning" }); +for (const [from, to] of [["rt-web.ts", "web"], ["rt-server.ts", "server"]]) for (const dev of [false, true]) { + await build({ entryPoints: [path.join(src, from)], outfile: path.join(dist, `${to}${dev ? ".dev" : ""}.js`), format: "esm", platform: "neutral", target: "es2022", bundle: true, packages: "external", logLevel: "warning", minifySyntax: true, + plugins: [{ name: "rx-runtime-tier", setup(build) { + build.onLoad({ filter: /rt-(web|server)\.ts$/ }, ({ path }) => ({ + loader: "ts", contents: readFileSync(path, "utf8") + .replace(/^const RX_(?:INSTRUMENT|HARNESS) = .*;\n/gm, "") + .replace(/\bRX_INSTRUMENT\b/g, dev ? "!!DEV" : "false") + .replace(/\bRX_HARNESS\b/g, String(dev)), + })); + } }], + }); } // declarations, unchecked: the runtime uses Solid internals its types leave out (createErrorBoundary, sharedConfig, // runInServerComponentScope); Solid's types resolve from this package's node_modules diff --git a/runtime/package.json b/runtime/package.json index 20af7113c..80a88bb94 100644 --- a/runtime/package.json +++ b/runtime/package.json @@ -14,29 +14,43 @@ ".": { "worker": { "types": "./dist/server.d.ts", + "production": "./dist/server.js", + "development": "./dist/server.dev.js", "default": "./dist/server.js" }, "browser": { "types": "./dist/web.d.ts", + "production": "./dist/web.js", + "development": "./dist/web.dev.js", "default": "./dist/web.js" }, "deno": { "types": "./dist/server.d.ts", + "production": "./dist/server.js", + "development": "./dist/server.dev.js", "default": "./dist/server.js" }, "node": { "types": "./dist/server.d.ts", + "production": "./dist/server.js", + "development": "./dist/server.dev.js", "default": "./dist/server.js" }, "types": "./dist/web.d.ts", + "production": "./dist/web.js", + "development": "./dist/web.dev.js", "default": "./dist/web.js" }, "./web": { "types": "./dist/web.d.ts", + "production": "./dist/web.js", + "development": "./dist/web.dev.js", "default": "./dist/web.js" }, "./server": { "types": "./dist/server.d.ts", + "production": "./dist/server.js", + "development": "./dist/server.dev.js", "default": "./dist/server.js" } }, diff --git a/runtime/test.mjs b/runtime/test.mjs index f9e8a480f..3768a7953 100644 --- a/runtime/test.mjs +++ b/runtime/test.mjs @@ -19,6 +19,16 @@ 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"), /cannot bind load.*createApp/); + assert.equal(createApp({ root: null }).jsError, undefined); + assert.equal(createApp({ root: null, api: { load: () => "loaded" } }).api("load")(), "loaded");`; + execFileSync(process.execPath, ["--conditions=" + cond, "--input-type=module", "-e", api], { cwd: tmp }); + execFileSync(process.execPath, ["--conditions=" + cond, "--conditions=development", "--input-type=module", "-e", ` + import assert from "node:assert/strict"; import { createApp } from "@reactivescript/runtime"; + assert.throws(() => createApp({ root: null }).api("load"), /MISSING_TEST_API/); + assert.equal(typeof createApp({ root: null }).jsError, "function");`], { cwd: tmp }); + check(`${build} gates the reference API behind development`, 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 000000000..27f6d981e --- /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 000000000..86393da04 --- /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 96450977d..71b7b1944 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 000000000..d0e0cf9a9 --- /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 000000000..1dce73877 --- /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 000000000..60088d434 --- /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 000000000..1ce6041ed --- /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 000000000..9bd564762 --- /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 000000000..5079060ee --- /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 fa3197d88..22b06c835 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 `