From 42db3631f7d4c9a561270ac274e5c2be58473ff4 Mon Sep 17 00:00:00 2001 From: Dev Agrawal Date: Tue, 24 Nov 2026 16:29:04 -0600 Subject: [PATCH 01/34] Real JS modules win over the test API and declared types bind no values --- compiler/src/emit.rs | 66 +++++++++++++++++++++--------- compiler/src/main.rs | 4 +- compiler/src/modules.rs | 19 +++++++-- compiler/test/node.mjs | 38 +++++++++++++++-- compiler/test/vite.mjs | 4 +- examples/{api.mjs => demo-api.mjs} | 2 +- ref/check.ts | 4 +- ref/compile/README.md | 4 +- ref/compile/build.ts | 8 ++-- ref/compile/emit.ts | 35 ++++++++++------ ref/compile/rt-server.ts | 7 +++- ref/compile/rt-web.ts | 11 +++-- ref/crate.ts | 20 +++++++++ ref/model.ts | 4 +- ref/src/modules.ts | 12 +++++- ref/src/scenario.ts | 4 +- ref/ssr/run.ts | 12 +++--- ref/types/run.ts | 4 +- runtime/test.mjs | 5 +++ scenarios/S-module-2.md | 4 +- spec/09-modules.md | 14 ++++++- spec/11-compiler.md | 9 ++-- spec/99-diagnostics.md | 1 + 23 files changed, 215 insertions(+), 76 deletions(-) rename examples/{api.mjs => demo-api.mjs} (94%) diff --git a/compiler/src/emit.rs b/compiler/src/emit.rs index 985f5710..95f55eb2 100644 --- a/compiler/src/emit.rs +++ b/compiler/src/emit.rs @@ -199,9 +199,15 @@ pub fn compile_modules(set: &ModuleSet, extra: &[Vec]) -> R { /// `compile_modules`, with each module importing its dependencies by their `.rx` paths (relative to the importer) when /// `by_source`, as a bundler resolves them, rather than as the sibling `.mjs` files `compile_modules` names. pub fn compile_linked(set: &ModuleSet, extra: &[Vec], by_source: bool) -> R { + compile_into(set, extra, by_source, None) +} + +/// For a sibling-file build written elsewhere, keep relative JS imports relative to their RX importer. +pub fn compile_into(set: &ModuleSet, extra: &[Vec], by_source: bool, out_dir: Option<&str>) -> R { let programs: Vec<&Program> = set.order.iter().map(|p| &set.programs[p]).collect(); let mut g = Gen::new(usage(&programs, extra), set); g.by_source = by_source; + g.out_dir = out_dir; let mut files = IndexMap::new(); let mut paths = IndexMap::new(); let mut module_css = IndexMap::new(); @@ -254,6 +260,7 @@ struct Gen<'p> { file: String, /// Modules imported by source path, for a bundler (`compile_linked`), not as sibling `.mjs` files. by_source: bool, + out_dir: Option<&'p str>, css: Vec, /// module-level code: hoisted server functions and the module's error classes top: Vec, @@ -277,11 +284,25 @@ fn is_prims(from: &str) -> bool { } impl<'p> Gen<'p> { - /// A JS import that becomes a real ES import (MO-8): a package's always; a relative one too when the modules go to a - /// bundler (`by_source`, the product), where `./util.js` is the app's own file. `./api` stays the app's injected API - /// (`createApp({ api })`, CP-4), and in the scenario runners every relative import is the harness's. - fn js_import(&self, from: &str) -> bool { - !from.starts_with('.') || (self.by_source && !from.ends_with("/api")) + fn local_js(&self, from: &str) -> bool { + from.starts_with('.') && self.set.js_files.contains(&crate::modules::join_path(&self.file, from)) + } + /// A real file wins even if its name (or one of its exports) is in the scenario prelude (MO-8c). + fn real_import(&self, from: &str, name: &str) -> bool { + if self.local_js(from) { + return true; + } + let product = self.by_source || self.out_dir.is_some(); + (!from.starts_with('.') || (product && from != "./api")) && !builtin(name) && name != "log" + } + fn js_decl(&self, declared: Option<&str>, name: &str) -> Option<&'p JsDecl> { + self.set.declarations.get(declared?).and_then(|ds| ds.iter().find(|x| x.name() == name)) + } + fn js_specifier(&self, from: &str) -> String { + if let Some(dir) = self.out_dir.filter(|_| from.starts_with('.')) { + return relative(&format!("{dir}/main.mjs"), &crate::modules::join_path(&self.file, from)); + } + from.to_string() } fn new(u: Usage, set: &'p ModuleSet) -> Self { Gen { @@ -289,6 +310,7 @@ impl<'p> Gen<'p> { set, file: "main.rx".into(), by_source: false, + out_dir: None, css: vec![], top: vec![], top_fns: HashSet::new(), @@ -366,13 +388,10 @@ impl<'p> Gen<'p> { } // a package's JS (`@solidjs/web/server-functions`): a real import at module level, where a hoisted server fn's wrappers are for d in decls { - if let Decl::Import { resolved: None, from, names, .. } = d { - if !self.js_import(from) { - continue; - } - let ns: Vec<(String, String)> = names.iter().filter(|n| !builtin(&n.name) && n.name != "log").map(|n| (n.name.clone(), format!("w${}", n.alias))).collect(); + if let Decl::Import { resolved: None, from, names, declared, .. } = d { + let ns: Vec<(String, String)> = names.iter().filter(|n| self.real_import(from, &n.name) && !matches!(self.js_decl(declared.as_deref(), &n.name), Some(JsDecl::Type { .. }))).map(|n| (n.name.clone(), format!("w${}", n.alias))).collect(); if !ns.is_empty() { - self.top.push(S::ImportNamed(ns, from.clone())); + self.top.push(S::ImportNamed(ns, self.js_specifier(from))); } } } @@ -390,7 +409,7 @@ impl<'p> Gen<'p> { ExprKind::ServerFn { params, body, .. } => self.server_hoist(name, params, body, true), ExprKind::Call { f, args } if matches!(&f.k, ExprKind::Id(_)) => { let ExprKind::Id(fname) = &f.k else { unreachable!() }; - let found = self.mod_decls.iter().any(|d| matches!(d, Decl::Import { resolved: None, from, names, .. } if self.js_import(from) && names.iter().any(|n| &n.alias == fname))); + let found = self.mod_decls.iter().any(|d| matches!(d, Decl::Import { resolved: None, from, names, .. } if names.iter().any(|n| &n.alias == fname && (self.real_import(from, &n.name) || !from.starts_with('.'))))); if !found { return fail(format!("{name}: a server fn's wrapper is a package's function (here, {fname})")); } @@ -426,15 +445,18 @@ impl<'p> Gen<'p> { let decls = self.mod_decls; for x in decls { match x { - Decl::Import { resolved: None, names, from, declared_errors, .. } => { + Decl::Import { resolved: None, names, from, declared, declared_errors, .. } => { for n in names { - if n.name == "log" || builtin(&n.name) { + if matches!(self.js_decl(declared.as_deref(), &n.name), Some(JsDecl::Type { .. })) { continue; } - if self.js_import(from) { + if self.real_import(from, &n.name) { self.set(env, &n.alias, val(format!("w${}", n.alias))); continue; } + if n.name == "log" || builtin(&n.name) { + continue; + } self.set(env, &n.alias, val(mg(&n.alias))); let v = if declared_errors.as_ref().is_some_and(|e| e.contains(&n.name)) { "jsError" } else { "api" }; pre.push(konst(mg(&n.alias), rtc(v, vec![str(n.name.clone())]))); @@ -634,7 +656,10 @@ impl<'p> Gen<'p> { Decl::Import { names, side, declared_side, declared, .. } => { for n in names { // MO-10a: a declared primitive - let x = declared.as_ref().and_then(|dp| self.set.declarations.get(dp)).and_then(|ds| ds.iter().find(|y| y.name() == n.name)); + let x = self.js_decl(declared.as_deref(), &n.name); + if matches!(x, Some(JsDecl::Type { .. })) { + continue; + } if let Some(JsDecl::Fn { params, refs, shape, instantiates: true, .. }) = x { let mut b = bind(Kind::Jfn, mg(&n.alias)); b.f = Some(FnRef { params: params.iter().enumerate().map(|(i, p)| (p.clone(), refs.get(i).copied().unwrap_or(false))).collect(), decl: None }); @@ -684,11 +709,14 @@ impl<'p> Gen<'p> { } } for d in decls { - let Decl::Import { resolved: None, names, from, declared_errors, .. } = d else { continue }; + let Decl::Import { resolved: None, names, from, declared, declared_errors, .. } = d else { continue }; let n0 = out.len(); for n in names { let (name, alias) = (&n.name, &n.alias); - let v = if self.js_import(from) && !builtin(name) && name != "log" { + if matches!(self.js_decl(declared.as_deref(), name), Some(JsDecl::Type { .. })) { + continue; + } + let v = if self.real_import(from, name) { id(format!("w${alias}")) } else if name == "log" { dot(id("__B"), "log") @@ -696,7 +724,7 @@ impl<'p> Gen<'p> { rtc("jsError", vec![str(name.clone())]) } else if builtin(name) { dot(id("__B"), name) - } else if from.ends_with("/api") { + } else if from == "./api" { rtc("api", vec![str(name.clone())]) } else if is_prims(from) { // MO-10: the scenario prelude's Solid primitives diff --git a/compiler/src/main.rs b/compiler/src/main.rs index b612ae72..02927ae3 100644 --- a/compiler/src/main.rs +++ b/compiler/src/main.rs @@ -28,7 +28,7 @@ use reactivescript::app::{self, read_disk}; use reactivescript::check::check_modules; -use reactivescript::emit::{compile_modules, lower_view, Target}; +use reactivescript::emit::{compile_modules, compile_into, lower_view, Target}; use reactivescript::parse::parse_stmts; use reactivescript::project::{project_modules, unverified, PRELUDE}; use reactivescript::modules::load_modules; @@ -286,7 +286,7 @@ fn main() { if !checked.diags.is_empty() { std::process::exit(1); } - let out = compile_modules(&set, &[]).unwrap_or_else(|e| { + let out = compile_into(&set, &[], false, Some(&abs(&dir))).unwrap_or_else(|e| { eprintln!("{}: not compiled: {}", file, e.0); std::process::exit(1); }); diff --git a/compiler/src/modules.rs b/compiler/src/modules.rs index eb1b7a48..c6676c79 100644 --- a/compiler/src/modules.rs +++ b/compiler/src/modules.rs @@ -6,7 +6,7 @@ use crate::check::Diagnostic; use crate::parse::{parse_declarations, parse_program, JsDecl, ParseError}; use crate::signature::{parse_signature, ModSig}; use indexmap::IndexMap; -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; pub struct ModuleSet { pub entry: String, @@ -15,6 +15,8 @@ pub struct ModuleSet { pub diags: Vec, /// MO-8, by `.d.rx` path pub declarations: IndexMap>, + /// MO-8c: relative JS specifiers with a local module, keyed by joined path. + pub js_files: HashSet, /// MO-9, by `.rx` path pub signatures: IndexMap, /// each program's text, which its spans index @@ -61,6 +63,7 @@ struct Loader<'r> { order: Vec, diags: Vec, declarations: IndexMap>, + js_files: HashSet, signatures: IndexMap, sources: HashMap, state: HashMap, @@ -165,6 +168,16 @@ impl Loader<'_> { self.state.insert(path.to_string(), State::Busy); for d in p.decls.iter_mut() { let Decl::Import { from, line, resolved, declared, declared_errors, declared_pure, declared_side, .. } = d else { continue }; + if !is_rx(from) && from.starts_with('.') { + let stem = join_path(path, from); + let exts = [".mjs", ".js", ".mts", ".ts", ".jsx", ".tsx", ".cjs", ".cts", ".json"]; + if (self.read)(&stem).is_some() + || exts.iter().any(|ext| (self.read)(&format!("{stem}{ext}")).is_some() || (self.read)(&format!("{stem}/index{ext}")).is_some()) + || (self.read)(&format!("{stem}/package.json")).is_some() + { + self.js_files.insert(stem); + } + } // MO-10c: a package's declaration, beside the file it resolves to let pkg_dts = if !is_rx(from) && !from.starts_with('.') && !from.starts_with('/') { package_declaration(path, from, &*self.read) } else { None }; if !is_rx(from) && (from.starts_with('.') || pkg_dts.is_some()) { @@ -242,7 +255,7 @@ pub fn load_modules_recovering(entry: &str, read: &dyn Fn(&str) -> Option Option, recover: bool) -> Result { - let mut l = Loader { read, programs: HashMap::new(), order: vec![], diags: vec![], declarations: IndexMap::new(), signatures: IndexMap::new(), sources: HashMap::new(), state: HashMap::new(), recover, parse_errors: vec![] }; + let mut l = Loader { read, programs: HashMap::new(), order: vec![], diags: vec![], declarations: IndexMap::new(), js_files: HashSet::new(), signatures: IndexMap::new(), sources: HashMap::new(), state: HashMap::new(), recover, parse_errors: vec![] }; l.visit(entry, &[])?; - Ok(ModuleSet { entry: entry.to_string(), programs: l.programs, order: l.order, diags: l.diags, declarations: l.declarations, signatures: l.signatures, sources: l.sources, parse_errors: l.parse_errors }) + Ok(ModuleSet { entry: entry.to_string(), programs: l.programs, order: l.order, diags: l.diags, declarations: l.declarations, js_files: l.js_files, signatures: l.signatures, sources: l.sources, parse_errors: l.parse_errors }) } diff --git a/compiler/test/node.mjs b/compiler/test/node.mjs index 15984a05..703e8542 100644 --- a/compiler/test/node.mjs +++ b/compiler/test/node.mjs @@ -3,8 +3,7 @@ import { createRequire } from "node:module"; import { fileURLToPath } from "node:url"; import path from "node:path"; -import { mkdtempSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; const { app } = createRequire(import.meta.url)("../index.js"); const examples = fileURLToPath(new URL("../../examples/", import.meta.url)); @@ -21,7 +20,9 @@ const bad = JSON.parse(app(path.join(examples, "missing.rx"))); if (!bad.error) { fail++; console.log("✗ a missing entry is not an error"); } else console.log("✓ a missing entry is an error"); // a relative JS import is the app's own file (MO-8): it stays an ES import, no package.json `#imports` needed; `./api` // stays the injected API (CP-4) -const dir = mkdtempSync(path.join(tmpdir(), "rx-import-")); +const outDir = new URL("./.out/", import.meta.url); +mkdirSync(outDir, { recursive: true }); +const dir = mkdtempSync(fileURLToPath(new URL("rx-import-", outDir))); writeFileSync(path.join(dir, "util.js"), "export const greet = n => `hi ${n}`;\n"); writeFileSync(path.join(dir, "main.rx"), [ 'import pure { greet } from "./util.js"', @@ -33,7 +34,36 @@ writeFileSync(path.join(dir, "main.rx"), [ ].join("\n")); const rel = JSON.parse(app(path.join(dir, "main.rx"), "dom", null, true)); const code = Object.values(rel.modules ?? {}).map(m => m.code).join("\n"); -const relOk = !rel.error && !rel.diagnostics && /from "\.\/util\.js"/.test(code) && !/from "\.\/api"/.test(code); +const relOk = !rel.error && !rel.diagnostics && /from "\.\/util\.js"/.test(code) && code.includes('__rt.api("save")'); if (!relOk) fail++; console.log(`${relOk ? "✓" : "✗"} a relative JS import stays an ES import${relOk ? "" : `: ${JSON.stringify(rel).slice(0, 300)}`}`); +try { + const entry = path.join(dir, "main.rx"); + writeFileSync(entry, [ + 'import pure { load } from "./api"', + 'import { save, Book as Volume } from "./server"', + 'import { Title } from "./types"', + 'export default component App() {', + ' source book: Volume := { title: "A" }', + ' title: Title = load()', + '

{ save(book) }}>{title}

', + '}', + ].join("\n")); + writeFileSync(path.join(dir, "server.js"), "export function save(book) {}\n"); + writeFileSync(path.join(dir, "server.d.rx"), "export fn save(book: Book)\nexport type Book = { title: string }\n"); + writeFileSync(path.join(dir, "types.ts"), 'export type Title = string;\n'); + writeFileSync(path.join(dir, "types.d.rx"), "export type Title = string\n"); + for (const ext of ["js", "ts"]) { + const api = path.join(dir, `api.${ext}`); + writeFileSync(api, 'export function load() { return "loaded"; }\n'); + const compiled = JSON.parse(app(entry, "dom", null, true)); + const code = compiled.modules?.[entry]?.code ?? ""; + const ok = /import \{ load as w\$load \} from "\.\/api"/.test(code) + && /import \{ save as w\$save \} from "\.\/server"/.test(code) + && !/__rt\.api|w\$Volume|v\$Volume|\.\/types/.test(code); + if (!ok) fail++; + console.log(`${ok ? "✓" : "✗"} ./api.${ext} stays real, and .d.rx types bind no values${ok ? "" : `: ${code || JSON.stringify(compiled)}`}`); + rmSync(api); + } +} finally { rmSync(dir, { recursive: true }); } process.exit(fail ? 1 : 0); diff --git a/compiler/test/vite.mjs b/compiler/test/vite.mjs index 05af552e..ed889c5e 100644 --- a/compiler/test/vite.mjs +++ b/compiler/test/vite.mjs @@ -48,7 +48,7 @@ function project(name, entry) { // the runtime as installed: copied, so that it takes the project's Solid (a peer), not its own dev copy for (const f of ["package.json", "dist"]) cpSync(path.join(runtime, f), path.join(nm, "@reactivescript/runtime", f), { recursive: true }); cpSync(path.join(repo, "examples"), path.join(dir, "src"), { recursive: true }); - writeFileSync(path.join(dir, "src/entry.js"), `import { createApp } from "@reactivescript/runtime";\nimport main from "./${entry}";\nimport * as api from "./api.mjs";\nconst app = createApp({ root: document.getElementById("app"), api });\napp.mount(main(app));\n`); + writeFileSync(path.join(dir, "src/entry.js"), `import { createApp } from "@reactivescript/runtime";\nimport main from "./${entry}";\nimport * as api from "./demo-api.mjs";\nconst app = createApp({ root: document.getElementById("app"), api });\napp.mount(main(app));\n`); writeFileSync(path.join(dir, "index.html"), `${name}
\n`); return dir; } @@ -99,7 +99,7 @@ for (const [name, entry] of Object.entries(apps)) { if (!filter || "shared".includes(filter)) { // two programs on one page, sharing shop/catalog.rx: no entry option, one catalog module const dir = project("shared", "shop/main.rx"); writeFileSync(path.join(dir, "src/shop/count.rx"), `import { products } from "./catalog.rx"\n\nexport default component Count() {\n errored fallback(e) {

no catalogue

} {\n

{len(products)} products

\n }\n}\n`); - writeFileSync(path.join(dir, "src/entry.js"), `import { createApp } from "@reactivescript/runtime";\nimport shop from "./shop/main.rx";\nimport count from "./shop/count.rx";\nimport * as api from "./api.mjs";\nfor (const [main, el] of [[shop, "app"], [count, "app2"]]) { const app = createApp({ root: document.getElementById(el), api }); app.mount(main(app)); }\n`); + writeFileSync(path.join(dir, "src/entry.js"), `import { createApp } from "@reactivescript/runtime";\nimport shop from "./shop/main.rx";\nimport count from "./shop/count.rx";\nimport * as api from "./demo-api.mjs";\nfor (const [main, el] of [[shop, "app"], [count, "app2"]]) { const app = createApp({ root: document.getElementById(el), api }); app.mount(main(app)); }\n`); writeFileSync(path.join(dir, "index.html"), readFileSync(path.join(dir, "index.html"), "utf8").replace('
', '
')); try { const bundle = await vite.build(config(dir, "shop/main.rx")); 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 b450b2c7..af876510 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/ref/check.ts b/ref/check.ts index 03623ec7..18658e44 100644 --- a/ref/check.ts +++ b/ref/check.ts @@ -1,7 +1,7 @@ // Usage: node --experimental-strip-types ref/check.ts [--signature] file.rx... // Runs the checker (08) over each file and every .rx module it imports (09: dependencies first, each against its imports' // signatures), and prints every diagnostic. --signature also prints each module's signature as .d.rx text (MO-3). -import { readFileSync, existsSync } from "node:fs"; +import { readFileSync, statSync } from "node:fs"; import { resolve } from "node:path"; import { loadModules } from "./src/modules.ts"; import { checkModules } from "./src/check.ts"; @@ -10,7 +10,7 @@ const args = process.argv.slice(2); const sigOut = args.includes("--signature"); let bad = 0; for (const f of args.filter(a => !a.startsWith("--"))) { try { - const set = loadModules(resolve(f), p => existsSync(p) ? readFileSync(p, "utf8") : undefined); + const set = loadModules(resolve(f), p => statSync(p, { throwIfNoEntry: false })?.isFile() ? readFileSync(p, "utf8") : undefined); const { diags, sigs } = checkModules(set); const rel = (p?: string) => (p ?? resolve(f)).replace(process.cwd() + "/", ""); if (!diags.length) console.log(`ok ${f}${set.order.length > 1 ? ` (+${set.order.length - 1} module${set.order.length > 2 ? "s" : ""})` : ""}`); diff --git a/ref/compile/README.md b/ref/compile/README.md index 6f20d7d6..119d5212 100644 --- a/ref/compile/README.md +++ b/ref/compile/README.md @@ -19,7 +19,9 @@ node --experimental-strip-types --conditions=browser --conditions=development re Status (2026-10-26): every scenario passes as compiled modules, with the divergences the oracle records (Solid bugs). Every example app builds for the -browser (`build.ts`), against `examples/api.mjs`, a fake backend with delays. +browser (`build.ts`), against `examples/demo-api.mjs`, a fake backend passed +to `createApp({ api })`. A local implementation of `./api` would take +precedence (MO-8c). A program of several `.rx` modules (spec/09) compiles to one ES module per `.rx` module: a dependency's `mN.mjs` is a factory over the app that diff --git a/ref/compile/build.ts b/ref/compile/build.ts index fd8b7bb4..9821e98b 100644 --- a/ref/compile/build.ts +++ b/ref/compile/build.ts @@ -1,7 +1,7 @@ // Usage: node --experimental-strip-types ref/compile/build.ts file.rx [--api path.mjs] // Checks and compiles a .rx app for the browser into ref/compile/.out/web// (index.html and one bundled app.js): // views through Solid's compiler, rt-web.ts, and Solid's DOM build. Serve that directory and open it. -import { readFileSync, writeFileSync, mkdirSync, copyFileSync, existsSync } from "node:fs"; +import { readFileSync, writeFileSync, mkdirSync, copyFileSync, existsSync, statSync } from "node:fs"; import { basename, dirname, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { buildSync } from "esbuild"; @@ -12,13 +12,13 @@ import { lowerViews } from "./jsx.ts"; const args = process.argv.slice(2); const file = args.find(a => !a.startsWith("--"))!; -const apiAt = args.indexOf("--api"); const api = apiAt >= 0 ? args[apiAt + 1] : resolve(fileURLToPath(new URL("../../examples/api.mjs", import.meta.url))); +const apiAt = args.indexOf("--api"); const api = apiAt >= 0 ? args[apiAt + 1] : resolve(fileURLToPath(new URL("../../examples/demo-api.mjs", import.meta.url))); const name = basename(file) === "main.rx" ? basename(dirname(resolve(file))) : basename(file).replace(/\.rx$/, ""); // examples/shop/main.rx → shop -const set = loadModules(resolve(file), p => existsSync(p) ? readFileSync(p, "utf8") : undefined); // 09: the entry and every .rx module it imports +const set = loadModules(resolve(file), p => existsSync(p) && statSync(p).isFile() ? readFileSync(p, "utf8") : undefined); const { diags } = checkModules(set); if (diags.length) { for (const d of diags) console.error(`${d.file ?? file}:${d.line}: error ${d.code} [${d.rule}] ${d.msg}`); process.exit(1); } const out = fileURLToPath(new URL(`./.out/web/${name}/`, import.meta.url)); mkdirSync(out, { recursive: true }); -const compiled = compileModules(set); +const compiled = compileModules(set, { jsSpecifier: (file, from) => from.startsWith(".") ? resolve(dirname(file), from) : from }); const src = out + "src/"; mkdirSync(src, { recursive: true }); for (const [n, js] of lowerViews(compiled.files, "dom")) writeFileSync(src + n, js); // Solid's compiler lowers the views (compile/jsx.ts) copyFileSync(api, src + "api.mjs"); diff --git a/ref/compile/emit.ts b/ref/compile/emit.ts index 7981cf47..3253ae34 100644 --- a/ref/compile/emit.ts +++ b/ref/compile/emit.ts @@ -4,7 +4,7 @@ // (`v$x` the value or accessor, `w$x` a source's writer, `p$x` a companion `pre` memo). The decisions are the // oracle's (ref/oracle/lower.ts); this file only makes them at compile time. import type { Decl, Expr, Markup, Program, Stmt } from "../src/ast.ts"; -import { singleModule, type ModuleSet } from "../src/modules.ts"; +import { joinPath, singleModule, type ModuleSet } from "../src/modules.ts"; import { innerCatches, nonTailAwaits, viewReaders } from "../src/awaits.ts"; import { inferredAction } from "../src/infer.ts"; import { transform } from "@solidjs/compiler"; @@ -70,10 +70,10 @@ export function compile(p: Program, opts: { extraStmts?: Stmt[][] } = {}): strin /** 09 MO-1: one ES module per `.rx` module. A dependency's module is a factory over the app (`__rt.module` runs it once per app, * the first time an importer instantiates — inside the mounted root, so its state is owned there); the entry's is `main`. */ -export function compileModules(set: ModuleSet, opts: { extraStmts?: Stmt[][] } = {}): { files: Map; entry: string; css: string } { +export function compileModules(set: ModuleSet, opts: { extraStmts?: Stmt[][]; jsSpecifier?: (file: string, from: string) => string } = {}): { files: Map; entry: string; css: string } { // MO-9: a module known by its signature is compiled on its own; its module is beside it, `x.rx` → `x.mjs` const out = (path: string) => path === set.entry ? "main.mjs" : set.order.includes(path) ? `m${set.order.indexOf(path)}.mjs` : `${path.split("/").pop()!.replace(/\.rx$/, "")}.mjs`; - const g = new Gen(usage([...set.programs.values()], opts.extraStmts), { set, out }); + const g = new Gen(usage([...set.programs.values()], opts.extraStmts), { set, out, jsSpecifier: opts.jsSpecifier }); const files = new Map(); for (const path of set.order) { const p = set.programs.get(path)!; g.beginModule(path, p.decls); @@ -100,14 +100,21 @@ class Gen { serverNames = new Map(); // a module-level server fn → its hoisted function private modDecls: Decl[] = []; private sfSeq = 0; + private localJS(from: string) { return this.mods?.set.jsFiles?.has(joinPath(this.file, from)); } + private realImport(from: string, name: string) { + return from.startsWith(".") ? this.localJS(from) : !BUILTINS.has(name) && name !== "log"; + } + private jsDecl(d: Extract, name: string) { + return d.declared ? this.mods?.set.declarations?.get(d.declared)?.find(x => x.name === name) : undefined; + } /** Begin a module: what a hoisted server function may name at module level (SF-3: imports, error classes, server fns). */ beginModule(path: string, decls: Decl[]) { this.file = path; this.top = []; this.modDecls = decls; this.serverNames = new Map(); for (const d of decls) if (d.k === "server" || (d.k === "eq" && unwrapServer(d.e))) this.serverNames.set(d.name, `sf$${d.name}`); - // a package's JS (\`@solidjs/web/server-functions\`): a real import at module level, where a hoisted server fn's wrappers are - for (const d of decls) if (d.k === "import" && !d.resolved && !d.from.startsWith(".")) { - const names = d.names.filter(n => !BUILTINS.has(n.name) && n.name !== "log"); - if (names.length) this.top.push(`import { ${names.map(n => `${n.name} as w$${n.alias}`).join(", ")} } from ${J(d.from)};`); + // Real JS imports live at module level so a hoisted server function can read them. + for (const d of decls) if (d.k === "import" && !d.resolved) { + const names = d.names.filter(n => this.realImport(d.from, n.name) && this.jsDecl(d, n.name)?.kind !== "type"); + if (names.length) this.top.push(`import { ${names.map(n => `${n.name} as w$${n.alias}`).join(", ")} } from ${J(this.mods?.jsSpecifier?.(path, d.from) ?? d.from)};`); } } /** 12 SF-7a: a server fn as Solid's \`"use server"\` function at module level — it may name only its parameters, its locals @@ -120,7 +127,7 @@ class Gen { const chain = (x: Expr): string => { if (x.k === "serverfn") return this.serverHoist({ name, params: x.params, body: x.body }, true); if (x.k === "call" && x.f.k === "id") { - const imp = this.modDecls.find(d => d.k === "import" && !d.resolved && !d.from.startsWith(".") && d.names.some(n => n.alias === (x.f as { name: string }).name)); + const imp = this.modDecls.find(d => d.k === "import" && !d.resolved && d.names.some(n => n.alias === (x.f as { name: string }).name && (this.realImport(d.from, n.name) || !d.from.startsWith(".")))); if (!imp) throw new CompileError(`${name}: a server fn's wrapper is a package's function (here, ${x.f.name})`); return `w$${x.f.name}(${x.args.map(a => unwrapServer(a) ? chain(a) : a.k === "lit" ? J(a.v) : (() => { throw new CompileError(`${name}: a wrapper's other arguments are literals`); })()).join(", ")})`; } @@ -134,8 +141,9 @@ class Gen { const env = new Env(null); const pre: string[] = []; for (const x of this.modDecls) { if (x.k === "import" && !x.resolved) for (const { name, alias } of x.names) { + if (this.jsDecl(x, name)?.kind === "type") continue; + if (this.realImport(x.from, name)) { env.vars.set(alias, { kind: "val", js: `w$${alias}` }); continue; } if (name === "log" || BUILTINS.has(name)) continue; - if (!x.from.startsWith(".")) { env.vars.set(alias, { kind: "val", js: `w$${alias}` }); continue; } // a package's: module level env.vars.set(alias, { kind: "val", js: mg(alias) }); pre.push(`const ${mg(alias)} = ${x.declaredErrors?.includes(name) ? `__rt.jsError(${J(name)})` : `__rt.api(${J(name)})`};`); } @@ -151,8 +159,8 @@ class Gen { return f; } private styleHash: string | null = null; // CSS-2: the scope class of the view being emitted - mods?: { set: ModuleSet; out: (path: string) => string }; - constructor(u: Usage, mods?: { set: ModuleSet; out: (path: string) => string }) { this.u = u; this.mods = mods; } + private mods?: { set: ModuleSet; out: (path: string) => string; jsSpecifier?: (file: string, from: string) => string }; + constructor(u: Usage, mods?: Gen["mods"]) { this.u = u; this.mods = mods; } private modIndex(path: string) { const { order, signatures } = this.mods!.set; return [...order, ...(signatures?.keys() ?? [])].indexOf(path); } depVar(path: string) { return `__m${this.modIndex(path)}`; } /** An imported name's binding, from the exporting module's declaration (MO-3: a source is read-only here, so an accessor). */ @@ -236,7 +244,7 @@ class Gen { // names first: hoisted functions and components; every other declaration is a const for (const d of decls) { if (d.k === "import" && d.resolved) continue; - if (d.k === "import") for (const { name, alias } of d.names) { const x = d.declared ? this.mods?.set.declarations?.get(d.declared)?.find(y => y.name === name) : undefined; env.vars.set(alias, x?.kind === "fn" && x.instantiates ? { kind: "jfn", js: mg(alias), refs: x.refs ?? [], shape: x.shape ?? "value" } : { kind: "val", js: mg(alias), client: d.side === "client" || d.declaredSide?.[name] === "client" }); } // MO-10a + if (d.k === "import") for (const { name, alias } of d.names) { const x = this.jsDecl(d, name); if (x?.kind !== "type") env.vars.set(alias, x?.kind === "fn" && x.instantiates ? { kind: "jfn", js: mg(alias), refs: x.refs ?? [], shape: x.shape ?? "value" } : { kind: "val", js: mg(alias), client: d.side === "client" || d.declaredSide?.[name] === "client" }); } // MO-10a if (d.k === "fn") env.vars.set(d.name, { kind: d.params.some(p => p.ref) || d.decls.length ? "ifn" : "fn", js: mg(d.name), fn: d }); if (d.k === "component") env.vars.set(d.name, { kind: "comp", js: cm(d.name) }); if (d.k === "action") env.vars.set(d.name, { kind: "act", js: mg(d.name) }); @@ -247,7 +255,8 @@ class Gen { if (d.k === "eq") { const jf = d.e.k === "call" && d.e.f.k === "id" ? env.lookup(d.e.f.name) : undefined; env.vars.set(d.name, { kind: "acc", js: mg(d.name), w: this.guessedEq(d) ? `w$${d.name}` : undefined, prev: this.u.prevOf.has(d.name) ? `p$${d.name}` : undefined, ...(jf?.kind === "jfn" ? { inst: `r$${d.name}`, shape: jf.shape } : {}) }); } } for (const d of decls) if (d.k === "import" && !d.resolved) for (const { name, alias } of d.names) { - const v = !d.from.startsWith(".") && !BUILTINS.has(name) && name !== "log" ? `w$${alias}` : name === "log" ? "__B.log" : d.declaredErrors?.includes(name) ? `__rt.jsError(${J(name)})` : BUILTINS.has(name) ? `__B.${name}` : d.from.endsWith("/api") ? `__rt.api(${J(name)})` : isPrims(d.from) ? `__rt.prim(${J(name)})` : null; // MO-10: the prelude's Solid primitives + if (this.jsDecl(d, name)?.kind === "type") continue; + const v = this.realImport(d.from, name) ? `w$${alias}` : name === "log" ? "__B.log" : d.declaredErrors?.includes(name) ? `__rt.jsError(${J(name)})` : BUILTINS.has(name) ? `__B.${name}` : d.from === "./api" ? `__rt.api(${J(name)})` : isPrims(d.from) ? `__rt.prim(${J(name)})` : null; // MO-10: the prelude's Solid primitives if (!v) throw new CompileError(`${name} from "${d.from}" is not in the scenario prelude`); out.push(`${pad}const ${mg(alias)} = ${v};\n${pad}__rt.reg(${J(alias)}, { value: ${mg(alias)} });`); } diff --git a/ref/compile/rt-server.ts b/ref/compile/rt-server.ts index 29c04711..e9e3849c 100644 --- a/ref/compile/rt-server.ts +++ b/ref/compile/rt-server.ts @@ -85,7 +85,7 @@ export class Flight { type Owner = ReturnType; type Ctx = { name: string; id: symbol; dflt: (() => unknown) | null; owner: Owner; dv: Entry | null }; -export function createApp(opts: { api?: Record unknown> } = {}) { +export function createApp(opts: { api?: Record unknown>; scenarioFlights?: boolean } = {}) { const flights = new Map(); const lastKey = new Map(); const registry = new Map(); @@ -121,7 +121,10 @@ export function createApp(opts: { api?: Record unknown> jsError(name: string) { if (jsErrors.has(name)) return jsErrors.get(name); const C = (opts.api?.[name] as unknown) ?? errorClass(name, ["message"], (m?: unknown) => m ?? name, `${name}#${classSeq++}`); declared.push(C); jsErrors.set(name, C); return C; }, /** A JS function's promise: a rejection with a declared class is marked safe to send; any other is redacted (SV-5). */ api: (name: string) => { - if (!opts.api) return (...a: unknown[]) => flight(`${name}:${a.map(fmt).join(",")}`); + if (!opts.api) { + if (opts.scenarioFlights) return (...a: unknown[]) => flight(`${name}:${a.map(fmt).join(",")}`); + throw new Error(`MISSING_TEST_API: cannot bind ${name} from "./api"; pass createApp({ api }) or provide a local JS module`); + } const f = opts.api[name] ?? (() => { throw new Error(`./api has no ${name}`); }); return (...a: unknown[]) => { const r = f(...a); return r && typeof (r as PromiseLike).then === "function" ? Promise.resolve(r).catch(e => { if (isA(e, declared)) markSafeError(e); throw e; }) : r; }; }, diff --git a/ref/compile/rt-web.ts b/ref/compile/rt-web.ts index a013aeef..da28388b 100644 --- a/ref/compile/rt-web.ts +++ b/ref/compile/rt-web.ts @@ -108,7 +108,7 @@ export class Flight { } // ---------------------------------------------------------------- one app instance -export function createApp(opts: { root: any; api?: Record unknown> }) { +export function createApp(opts: { root: any; api?: Record unknown>; scenarioFlights?: boolean }) { const flights = new Map(); const lastKey = new Map(); const truthOf = new Map(); // an optimistic signal-form source: its guess layer -> its question @@ -149,10 +149,15 @@ export function createApp(opts: { root: any; api?: Record opts.api?.fetch ? opts.api.fetch(key) : flight(String(key)), log: (...a: unknown[]) => { log.push(`log(${a.map(fmt).join(", ")})`); }, } as Record, - /** `import pure { f } from "./api"`: every function is a flight keyed by its name and formatted arguments. */ /** MO-8: a class `api.d.rx` declares as an error: the real module's, or (in the harness) a stand-in `C(message)`. */ jsError: (name: string) => jsErrors.get(name) ?? (jsErrors.set(name, (opts.api?.[name] as unknown) ?? errorClass(name, ["message"], (m?: unknown) => m ?? name, `${name}#${classSeq++}`)), jsErrors.get(name)), - api: (name: string) => opts.api ? (opts.api[name] ?? (() => { throw new Error(`./api has no ${name}`); })) : (...a: unknown[]) => flight(`${name}:${a.map(fmt).join(",")}`), + api: (name: string) => { + if (!opts.api) { + if (opts.scenarioFlights) return (...a: unknown[]) => flight(`${name}:${a.map(fmt).join(",")}`); + throw new Error(`MISSING_TEST_API: cannot bind ${name} from "./api"; pass createApp({ api }) or provide a local JS module`); + } + return opts.api[name] ?? (() => { throw new Error(`./api has no ${name}`); }); + }, /** MO-10: the scenario prelude's `./prims` — Solid primitives, as a library writes them (`ref/compile/prims-solid.ts`). */ prim: (name: string) => primsSolid({ createSignal: createSignal as any, createMemo: createMemo as any })[name] ?? (() => { throw new Error(`./prims has no ${name}`); }), diff --git a/ref/crate.ts b/ref/crate.ts index d95e8fc8..7582f9b7 100644 --- a/ref/crate.ts +++ b/ref/crate.ts @@ -57,6 +57,26 @@ for (const f of readdirSync(sdir).filter(f => f.endsWith(".md") && f !== "TEMPLA const walk = (d: string): string[] => readdirSync(d, { withFileTypes: true }).flatMap(e => e.isDirectory() ? walk(join(d, e.name)) : e.name.endsWith(".rx") && !e.name.endsWith(".d.rx") ? [join(d, e.name)] : []); for (const f of walk(join(root, "examples")).sort()) add(`examples/${f.slice(join(root, "examples").length + 1)}`, f, disk, lowerMode ? [] : undefined); +// MO-8c/d: a real, importer-relative API in a mixed value/type import. Exercise +// this in the lowering comparison rather than the flight-based scenario runners. +if (lowerMode) { + const files = new Map([ + ["src/main.rx", `import pure { load, Book as Volume } from "./api" +import { Title } from "./types" +export default component App() { + book: Volume = load() + title: Title = book.title +

{title}

+} +`], + ["src/api.ts", `export type Book = { title: string };\nexport const load = (): Book => ({ title: "A" });\n`], + ["src/api.d.rx", `export pure fn load(): Book\nexport type Book = { title: string }\n`], + ["src/types.ts", `export type Title = string;\n`], + ["src/types.d.rx", `export type Title = string\n`], + ]); + add("MO-8 real API and type imports", "src/main.rx", path => files.get(path), []); +} + const plain = (x: unknown) => JSON.parse(JSON.stringify(x, (_k, v) => v instanceof Map ? Object.fromEntries(v) : v instanceof Set ? [...v] : v)); function refOf(r: Req) { const read = (p: string) => r.files[p]; diff --git a/ref/model.ts b/ref/model.ts index 3af99dd5..c18a2b7a 100644 --- a/ref/model.ts +++ b/ref/model.ts @@ -1,13 +1,13 @@ // Usage: node --experimental-strip-types ref/model.ts file.rx... // Prints the resolved model (spec/11 CP-6) of each file and the .rx modules it imports, as JSON: regions, symbols, and the // computations with their reads (tracked, snapshot, pre), writes and calls. The checker's diagnostics come first, if any. -import { readFileSync, existsSync } from "node:fs"; +import { readFileSync, statSync } from "node:fs"; import { resolve } from "node:path"; import { loadModules } from "./src/modules.ts"; import { checkModules } from "./src/check.ts"; let bad = 0; for (const f of process.argv.slice(2)) { - const set = loadModules(resolve(f), p => existsSync(p) ? readFileSync(p, "utf8") : undefined); + const set = loadModules(resolve(f), p => statSync(p, { throwIfNoEntry: false })?.isFile() ? readFileSync(p, "utf8") : undefined); const { diags, models } = checkModules(set); for (const d of diags) { bad++; console.error(`${d.file ?? f}:${d.line}: error ${d.code} [${d.rule}] ${d.msg}`); } const rel = (p: string) => p.replace(process.cwd() + "/", ""); diff --git a/ref/src/modules.ts b/ref/src/modules.ts index 4d1cc361..45cb25a3 100644 --- a/ref/src/modules.ts +++ b/ref/src/modules.ts @@ -6,7 +6,7 @@ import type { Diagnostic } from "./errors.ts"; import type { ModSig } from "./check.ts"; import { parseSignature, SignatureError } from "./signature.ts"; -export type ModuleSet = { entry: string; programs: Map; order: string[]; diags: Diagnostic[]; declarations?: Map; signatures?: Map }; // declarations: MO-8, by `.d.rx` path; signatures: MO-9, by `.rx` path +export type ModuleSet = { entry: string; programs: Map; order: string[]; diags: Diagnostic[]; declarations?: Map; signatures?: Map; jsFiles?: Set }; // declarations: MO-8, by `.d.rx` path; signatures: MO-9, by `.rx` path export const isRx = (from: string) => /\.rx$/.test(from); @@ -52,6 +52,7 @@ export function packageDeclaration(fromFile: string, spec: string, read: (path: /** Load `entry` and everything it imports from `.rx`. `read` returns a module's source, or undefined when there is none. */ export function loadModules(entry: string, read: (path: string) => string | undefined): ModuleSet { const programs = new Map(); const order: string[] = []; const diags: Diagnostic[] = []; const declarations = new Map(); const signatures = new Map(); + const jsFiles = new Set(); const state = new Map(); const visit = (path: string, stack: string[]) => { if (state.get(path) === "done") return; @@ -61,6 +62,13 @@ export function loadModules(entry: string, read: (path: string) => string | unde try { p = parseProgram(src); } catch (e) { if (e instanceof ParseError) throw Object.assign(new ParseError(`${path}: ${e.message}`), { code: e.code }); throw e; } programs.set(path, p); state.set(path, "busy"); for (const d of p.decls) { + // MO-8c: a local file takes precedence over any scenario prelude. Keep + // the specifier itself unchanged for the bundler. + if (d.k === "import" && !isRx(d.from) && d.from.startsWith(".")) { + const stem = joinPath(path, d.from); + const exts = [".mjs", ".js", ".mts", ".ts", ".jsx", ".tsx", ".cjs", ".cts", ".json"]; + if ([stem, ...exts.flatMap(ext => [stem + ext, stem + "/index" + ext]), stem + "/package.json"].some(p => read(p) !== undefined)) jsFiles.add(stem); + } const pkgDts = d.k === "import" && !isRx(d.from) && !d.from.startsWith(".") && !d.from.startsWith("/") ? packageDeclaration(path, d.from, read) : undefined; // MO-10c if (d.k === "import" && !isRx(d.from) && (d.from.startsWith(".") || pkgDts)) { // MO-8: a JS module with a declaration file beside it const dts = pkgDts ?? joinPath(path, d.from.replace(/\.(m?js|ts)$/, "") + ".d.rx"); @@ -83,7 +91,7 @@ export function loadModules(entry: string, read: (path: string) => string | unde state.set(path, "done"); order.push(path); }; visit(entry, []); - return { entry, programs, order, diags, declarations, signatures }; + return { entry, programs, order, diags, declarations, signatures, jsFiles }; } /** One program with no `.rx` imports — the common case, and every scenario before 09. */ diff --git a/ref/src/scenario.ts b/ref/src/scenario.ts index d6ba8f85..4f04a2d0 100644 --- a/ref/src/scenario.ts +++ b/ref/src/scenario.ts @@ -14,7 +14,7 @@ export type Scenario = { name: string; program: string; tables: Table[]; rejecte const strip = (s: string) => s.replace(/`/g, "").trim(); -import { readFileSync, existsSync } from "node:fs"; +import { readFileSync, existsSync, statSync } from "node:fs"; import { resolve as resolvePath } from "node:path"; import { loadModules, joinPath, type ModuleSet } from "./modules.ts"; import { checkModules, type ModSig, type ExportSig } from "./check.ts"; @@ -44,7 +44,7 @@ export function signaturesInPlace(set: ModuleSet): string | null { /** The module set for one of a scenario's programs: the entry is `src`; its `.rx` imports are the `## Modules` fences, else files * beside the entry (a `file:` program). */ export function moduleSet(sc: Scenario, src: string): ModuleSet { - return loadModules(sc.entry, p => p === sc.entry ? src : sc.modules.get(p) ?? (existsSync(p) ? readFileSync(p, "utf8") : undefined)); + return loadModules(sc.entry, p => p === sc.entry ? src : sc.modules.get(p) ?? (existsSync(p) && statSync(p).isFile() ? readFileSync(p, "utf8") : undefined)); } export function parseScenario(name: string, md: string, baseDir = "."): Scenario { const sections = md.split(/^## /m).slice(1).map(s => { const nl = s.indexOf("\n"); return { title: s.slice(0, nl).trim(), body: s.slice(nl + 1) }; }); diff --git a/ref/ssr/run.ts b/ref/ssr/run.ts index bda28a87..cb923b03 100644 --- a/ref/ssr/run.ts +++ b/ref/ssr/run.ts @@ -34,7 +34,7 @@ async function serverFunction(req: import("node:http").IncomingMessage, res: imp const chunks: Buffer[] = []; for await (const c of req) chunks.push(c as Buffer); const headers = new Headers(); for (const [k, v] of Object.entries(req.headers)) if (typeof v === "string") headers.set(k, v); const request = new Request(`http://127.0.0.1${req.url}`, { method: req.method, headers, body: req.method === "GET" || req.method === "HEAD" ? undefined : Buffer.concat(chunks) }); - const rpc = createApp(); rpcApps.push(rpc); (globalThis as { __rx_app?: unknown }).__rx_app = rpc; + const rpc = createApp({ scenarioFlights: true }); rpcApps.push(rpc); (globalThis as { __rx_app?: unknown }).__rx_app = rpc; const response = await handleServerFunctionRequest(request); res.writeHead(response.status, Object.fromEntries(response.headers.entries())); if (response.body) for await (const c of response.body as unknown as AsyncIterable) res.write(c); @@ -81,7 +81,7 @@ async function serve(sc: Scenario, src: string, rows: Row[], title: string, line const dir = `${outDir}${sc.name}.${++seq}/`; mkdirSync(dir, { recursive: true }); for (const [name, js] of out.views("ssr")) writeFileSync(dir + name, directives(js, dir + name, "server")); const main = (await import(pathToFileURL(dir + out.entry).href)).default; - const app = createApp(); + const app = createApp({ scenarioFlights: true }); const got: string[] = []; let ended = false; let chunks = 0; let renderError: unknown = null; const doc: string[] = []; const served$ = new Promise(resolve => { @@ -94,7 +94,7 @@ async function serve(sc: Scenario, src: string, rows: Row[], title: string, line }; }); // SV-4: another request for the same page, in flight at the same time — its own app, its own module state - if (other) { const b = createApp(); b.stream(main(b), { write: (c: string) => { other.chunks.push(c); }, end: () => {} }); } + if (other) { const b = createApp({ scenarioFlights: true }); b.stream(main(b), { write: (c: string) => { other.chunks.push(c); }, end: () => {} }); } const nav = page.goto(`http://127.0.0.1:${port}/`, { waitUntil: "commit" }).catch(() => {}); await served$; await nav; for (let i = 0; i < 40 && chunks === 0 && !ended && !renderError; i++) await wait(10); @@ -122,7 +122,7 @@ const rtWeb = fileURLToPath(new URL("../compile/rt-web.ts", import.meta.url)); function bundle(dir: string, views: Map, entry: string) { const cdir = dir + "client/"; mkdirSync(cdir, { recursive: true }); for (const [name, js] of views) writeFileSync(cdir + name, directives(js, dir + name, "client")); // the server's filename: the same ids - writeFileSync(cdir + "client-entry.mjs", `import main from "./${entry}";\nimport { createApp, flush } from ${JSON.stringify(rtWeb)};\nimport { sharedConfig } from "solid-js";\nconst app = createApp({ root: document.getElementById("app") });\nwindow.__client = { app, flush, sharedConfig, main };\n`); + writeFileSync(cdir + "client-entry.mjs", `import main from "./${entry}";\nimport { createApp, flush } from ${JSON.stringify(rtWeb)};\nimport { sharedConfig } from "solid-js";\nconst app = createApp({ root: document.getElementById("app"), scenarioFlights: true });\nwindow.__client = { app, flush, sharedConfig, main };\n`); // the dev builds: Solid reports a hydration key miss, a tag mismatch and unclaimed server nodes on the console const r = buildSync({ entryPoints: [cdir + "client-entry.mjs"], bundle: true, write: false, format: "esm", platform: "browser", conditions: ["browser", "development"], logLevel: "silent", tsconfigRaw: "{}" }); // (not next's tsconfig paths, which map solid-js to its source) return r.outputFiles[0].text; @@ -149,7 +149,7 @@ async function hydrated(sc: Scenario, t: Scenario["tables"][number], src: string for (const [name, js] of out.views("ssr")) writeFileSync(dir + name, directives(js, dir + name, "server")); const main = (await import(pathToFileURL(dir + out.entry).href)).default; clientJs = bundle(dir, out.views("dom"), out.entry); - const app = createApp(); let ended = false; let chunks = 0; + const app = createApp({ scenarioFlights: true }); let ended = false; let chunks = 0; const csr = at === 0; // the baseline: the same bundle mounted on an empty page, no server const served$ = new Promise(resolve => { pending = res => { @@ -331,7 +331,7 @@ async function runBeforeHydration(sc: Scenario, lines: string[]): Promise(resolve => { pending = res => { res.on("error", () => {}); 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-module-2.md b/scenarios/S-module-2.md index 41e745bb..d2b54f30 100644 --- a/scenarios/S-module-2.md +++ b/scenarios/S-module-2.md @@ -1,6 +1,8 @@ # S-module-2 — a declaration file for a JS module: rows declared once, checked at every import -Rules: MO-8, R-io-4, R-f-8, R-f-4, R-f-6. +Rules: MO-8, R-io-4, R-f-8, R-f-4, R-f-6. Here `./api` has only a +declaration, so the runners supply the flights (MO-8c). `User` is for type +checking only, with no JS import or flight (MO-8d). ## Modules diff --git a/spec/09-modules.md b/spec/09-modules.md index b62221e5..b2aec238 100644 --- a/spec/09-modules.md +++ b/spec/09-modules.md @@ -174,8 +174,18 @@ export component Save(props: { v: unrendered action go catches(nothing) }) instead of at every import (S-module-2). - **MO-8c.** A JS import, relative (`./util.js`) or a package's, stays an ES import in the compiled module, for the bundler to resolve; no - `package.json` `#imports` alias is needed. The one exception is `./api`, - which is the app's injected API (`createApp({ api })`, CP-4). + `package.json` `#imports` alias is needed. For the scenarios and examples, + exactly `./api` can name the injected test API (`createApp({ api })`, + CP-4c), but only if there is no local implementation relative to the + importing file. A neighboring `api.js` or `api.ts` wins; an `api.d.rx` + declares the API's rows but is not itself an implementation. +- **MO-8d.** An `export type` in a JS module's `.d.rx` binds no value. + Its name (including a local alias) appears in the type projection, but + not in the emitted JS import or runtime bindings. An import with only + such names does not load the JS module. The runtime compiler does not + read TypeScript types or infer which imports are types from their uses: + declare type exports in `.d.rx` to erase them. No `import type` form + is needed. ## MO-9 — A signature read in place of its module diff --git a/spec/11-compiler.md b/spec/11-compiler.md index 5e9f837c..ae8b5fb4 100644 --- a/spec/11-compiler.md +++ b/spec/11-compiler.md @@ -153,12 +153,15 @@ record argued each way; this is the decision. sink)` in the server's. - **CP-4c (The harness's, not the package's).** `reg`, `lookup`, `dget`, `dset` (a scenario's `handler` rows reach any live binding by name), - `api` and `jsError` (`./api` and its declared errors as test flights, - where a program imports the real module), `B.fetch` and `B.fail` (the + `api` and `jsError` (the unresolved `./api` test API and its declared + errors, MO-8c), `B.fetch` and `B.fail` (the scenario prelude), and `flights`, `lastKey`, `log`, `asyncError`, `frame` (what the runners observe). Compiled code calls them only in a conformance build — the compiler's option for running `scenarios/` - (CP-5); `ref/compile/emit.ts` always emits one. + (CP-5); `ref/compile/emit.ts` always emits one. The unresolved `./api` + fallback also serves the example apps with `createApp({ api })`. + Outside the flight-driving runners, `__rt.api(name)` without an injected + API throws `MISSING_TEST_API` at binding rather than making a test flight. ## CP-5 — `ref/` is the conformance suite diff --git a/spec/99-diagnostics.md b/spec/99-diagnostics.md index 26010f97..5eb359da 100644 --- a/spec/99-diagnostics.md +++ b/spec/99-diagnostics.md @@ -57,6 +57,7 @@ Bins: | `FALLBACK_FLASH` | R | timing | | `STACKED_HOLDS` | R | timing | | `ABANDONED_FLIGHTS` | R | timing | +| `MISSING_TEST_API` | R | CP-4c / MO-8c: unresolved `./api` test import without an injected API outside the scenario runners | | `UNTRACKED_ASYNC_HANDLER` | R | timing; the structural half (no write before `await`, no `action`) is S | | `HOT_SCOPE_*` | R | profiling | | `WASTED_RECOMPUTE` | R | data-dependent | From f30e1bb47dade12e4d43ef023be139ab77b4ed01 Mon Sep 17 00:00:00 2001 From: Dev Agrawal Date: Tue, 24 Nov 2026 20:20:23 -0600 Subject: [PATCH 02/34] Read generic and private types in foreign declarations. --- compiler/src/check.rs | 2 +- compiler/src/parse.rs | 55 +++++++++++++++++++++++++++++++++-------- compiler/src/project.rs | 16 ++++++------ ref/src/check.ts | 2 +- ref/src/parse.ts | 37 +++++++++++++++++++-------- ref/types/project.ts | 11 +++++---- scenarios/S-module-5.md | 40 ++++++++++++++++++++++++++++++ spec/09-modules.md | 4 +++ 8 files changed, 133 insertions(+), 34 deletions(-) create mode 100644 scenarios/S-module-5.md diff --git a/compiler/src/check.rs b/compiler/src/check.rs index ef628f7b..b5c2ec4c 100644 --- a/compiler/src/check.rs +++ b/compiler/src/check.rs @@ -1445,7 +1445,7 @@ impl<'a> Checker<'a> { self.err("IMPORT_ROW_MISMATCH", "MO-8", format!("{}'s rows are declared in {}: `fails` on the import cannot restate them", from, file)); } for ImportName { name, alias } in names { - let Some(x) = decls.iter().find(|y| y.name() == name) else { + let Some(x) = decls.iter().find(|y| y.name() == name && y.exported()) else { self.err("NOT_EXPORTED", "MO-8", format!("{} declares no export {} (declare it, or it is not {}'s)", file, name, from)); let mut s = Sym::new(SymKind::Import, alias, region, line); s.io = true; diff --git a/compiler/src/parse.rs b/compiler/src/parse.rs index 52052e43..9547141e 100644 --- a/compiler/src/parse.rs +++ b/compiler/src/parse.rs @@ -245,12 +245,15 @@ fn opt_type(c: &mut Cursor, brace_stops: bool) -> R> { } /// R-f: `A | B` — error class names. `Error` (or TS's `unknown`/`any`) is every failure: `None`. fn parse_classes(c: &mut Cursor) -> R>> { + parse_class_list(c, false) +} +fn parse_class_list(c: &mut Cursor, commas: bool) -> R>> { let mut out = vec![]; loop { c.ws(true); out.push(c.ident_or("error class")?); c.ws(false); - if c.peek() == '|' && c.peek_at(1) != '|' { + if (c.peek() == '|' && c.peek_at(1) != '|') || (commas && c.peek() == ',') { c.bump(); continue; } @@ -481,36 +484,63 @@ fn shape_of(t: &str) -> Shape { pub enum JsDecl { /// ret: the type text with `ref` taken out (for TY); MO-10: refs (ref parameters), shape (what the result is), /// instantiates (written, or inferred from a ref on either side) - Fn { name: String, pure: bool, params: Vec, rejects: Option>, line: usize, side: Option, ptypes: Vec>, ret: Option, refs: Vec, shape: Shape, instantiates: bool }, + Fn { name: String, pure: bool, params: Vec, generics: Option, rejects: Option>, line: usize, side: Option, ptypes: Vec>, ret: Option, refs: Vec, shape: Shape, instantiates: bool }, Error { name: String, line: usize }, - Type { name: String, line: usize, text: String }, + Type { name: String, line: usize, text: String, exported: bool }, } impl JsDecl { + pub fn exported(&self) -> bool { + !matches!(self, Self::Type { exported: false, .. }) + } pub fn name(&self) -> &str { match self { JsDecl::Fn { name, .. } | JsDecl::Error { name, .. } | JsDecl::Type { name, .. } => name, } } } +fn type_params(c: &mut Cursor) -> R> { + let start = c.i; + if !c.eat("<") { return Ok(None); } + let mut depth = 1; + while !c.eof() { + if c.eat("=>") { continue; } + if c.eat("<") { depth += 1; } + else if c.eat(">") { + depth -= 1; + if depth == 0 { return Ok(Some(c.src[start..c.i].to_string())); } + } else if matches!(c.peek(), '\'' | '"' | '`') { + let quote = c.peek(); + c.bump(); + while !c.eof() && c.peek() != quote { + if c.eat("\\") { c.bump(); } + else { c.bump(); } + } + if c.eof() { return c.fail("unterminated string in type parameters"); } + c.bump(); + } else { c.bump(); } + } + c.fail("expected '>' to end type parameters") +} pub fn parse_declarations(src: &str) -> R> { let mut c = Cursor::new(src); let mut out = vec![]; loop { c.ws(true); + if c.eat(";") { continue; } if c.eof() { return Ok(out); } let line = c.line(); - if !c.keyword("export") { - return c.fail("a declaration file declares exports: `export pure fn …`, `export fn …`, `export error …`, `export type …`"); - } + let exported = c.keyword("export"); c.ws(true); - if c.starts_with("type") || c.starts_with("interface") { + if matches!(c.peek_ident().as_deref(), Some("type" | "interface")) { let t0 = c.i; let _ = c.keyword("type") || c.keyword("interface"); c.ws(true); let name = c.ident_or("type name")?; c.ws(true); + type_params(&mut c)?; + c.ws(true); if c.eat("=") { c.ws(true); parse_type(&mut c, false, true)?; @@ -529,9 +559,12 @@ pub fn parse_declarations(src: &str) -> R> { } } } - out.push(JsDecl::Type { name, line, text: c.src[t0..c.i].to_string() }); + out.push(JsDecl::Type { name, line, text: c.src[t0..c.i].to_string(), exported }); continue; } + if !exported { + return c.fail("a declaration file declares exports: `export pure fn …`, `export fn …`, `export error …`, `export type …`"); + } if c.keyword("error") { c.ws(true); let name = c.ident_or("error class name")?; @@ -554,6 +587,8 @@ pub fn parse_declarations(src: &str) -> R> { c.ws(true); let name = c.ident_or("fn name")?; c.ws(true); + let generics = type_params(&mut c)?; + c.ws(true); c.expect("(")?; c.ws(true); let mut params = vec![]; @@ -615,7 +650,7 @@ pub fn parse_declarations(src: &str) -> R> { if c.keyword("rejects") { c.ws(true); c.expect("(")?; - rejects = Some(parse_classes(&mut c)?.unwrap_or_else(|| vec!["Error".to_string()])); + rejects = Some(parse_class_list(&mut c, true)?.unwrap_or_else(|| vec!["Error".to_string()])); c.ws(true); c.expect(")")?; } @@ -623,7 +658,7 @@ pub fn parse_declarations(src: &str) -> R> { let written = c.keyword("instantiates"); let instantiates = written || refs.iter().any(|x| *x) || shape.as_ref().is_some_and(|s| s.has_ref()); // MO-10a let shape = shape.unwrap_or(Shape::Part(Part::Value)); - out.push(JsDecl::Fn { name, pure, params, rejects, line, side, ptypes, ret, refs, shape, instantiates }); + out.push(JsDecl::Fn { name, pure, params, generics, rejects, line, side, ptypes, ret, refs, shape, instantiates }); } } diff --git a/compiler/src/project.rs b/compiler/src/project.rs index d1a3751b..f0b592bb 100644 --- a/compiler/src/project.rs +++ b/compiler/src/project.rs @@ -229,14 +229,14 @@ fn declaration_file(decls: &[JsDecl]) -> String { decls .iter() .map(|d| match d { - JsDecl::Type { text, .. } => format!("export {text}"), + JsDecl::Type { text, exported, .. } => format!("{}{text}", if *exported { "export " } else { "" }), JsDecl::Error { name, .. } => format!("export declare class {name}$ extends Error {{}}\nexport declare const {name}: (message?: string) => {name}$;\nexport type {name} = {name}$;"), - JsDecl::Fn { name, params, ptypes, ret, .. } => { + JsDecl::Fn { name, params, generics, ptypes, ret, .. } => { let ps = params.iter().enumerate().map(|(i, n)| match ptypes.get(i).and_then(|t| t.as_ref()) { Some(t) => format!("{n}: {t}"), None => n.clone(), }); - format!("export declare function {name}({}): {};", ps.collect::>().join(", "), ret.as_deref().unwrap_or("any")) + format!("export declare function {name}{}({}): {};", generics.as_deref().unwrap_or(""), ps.collect::>().join(", "), ret.as_deref().unwrap_or("any")) } }) .collect::>() @@ -527,16 +527,18 @@ impl Proj<'_> { fn import_decl(&mut self, d: &Decl, ind: &str) { let Decl::Import { names, from, line, resolved, declared, .. } = d else { return }; let sp = d.span(); + let is_prelude = |n: &ImportName| from == "./prelude" && builtin(&n.name); for n in names { - if builtin(&n.name) { - // the prelude's own (`import { log } from "./prelude"`) + if is_prelude(n) { self.declared.remove(&n.alias); + } else { + self.declared.insert(n.alias.clone()); } } - for n in names.iter().filter(|n| builtin(&n.name)) { + for n in names.iter().filter(|n| is_prelude(n)) { self.used.insert(n.name.clone()); } - let rest: Vec<&ImportName> = names.iter().filter(|n| !builtin(&n.name)).collect(); + let rest: Vec<&ImportName> = names.iter().filter(|n| !is_prelude(n)).collect(); if rest.is_empty() { return; } diff --git a/ref/src/check.ts b/ref/src/check.ts index 13ab81f1..9f95fcd8 100644 --- a/ref/src/check.ts +++ b/ref/src/check.ts @@ -574,7 +574,7 @@ class Checker { const decls = this.opts.declarations?.get(d.declared!) ?? []; const file = d.declared!.split("/").pop(); if (d.fails) this.err("IMPORT_ROW_MISMATCH", "MO-8", `${d.from}'s rows are declared in ${file}: \`fails\` on the import cannot restate them`); for (const { name, alias } of d.names) { - const x = decls.find(y => y.name === name); + const x = decls.find(y => y.name === name && (y.kind !== "type" || y.exported)); if (!x) { this.err("NOT_EXPORTED", "MO-8", `${file} declares no export ${name} (declare it, or it is not ${d.from}'s)`); this.bind(env, alias, { kind: "import", name: alias, region: env.region, line: d.line, io: true }); continue; } if (x.kind === "type") continue; if (x.kind === "error") { this.bind(env, alias, { kind: "errclass", name: alias, region: env.region, line: d.line }); continue; } diff --git a/ref/src/parse.ts b/ref/src/parse.ts index 2933d0cb..9e5f3022 100644 --- a/ref/src/parse.ts +++ b/ref/src/parse.ts @@ -106,9 +106,9 @@ function splitKey(type: string | undefined): { type?: string; key?: string } { c function optType(c: Cursor, braceStops = false): string | undefined { c.ws(false); if (c.peek() === ":" && c.peek(1) !== "=") { c.i++; c.ws(); return parseType(c, braceStops); } return undefined; } /** R-f: `A | B` — error class names. `Error` (or TS's `unknown`/`any`) is every failure: undefined. */ -function parseClasses(c: Cursor): string[] | undefined { +function parseClasses(c: Cursor, commas = false): string[] | undefined { const out: string[] = []; - for (;;) { c.ws(); out.push(c.ident() ?? c.fail("error class")); c.ws(false); if (c.peek() === "|" && c.peek(1) !== "|") { c.i++; continue; } break; } + for (;;) { c.ws(); out.push(c.ident() ?? c.fail("error class")); c.ws(false); if ((c.peek() === "|" && c.peek(1) !== "|") || (commas && c.peek() === ",")) { c.i++; continue; } break; } return out.some(n => n === "Error" || n === "unknown" || n === "any") ? undefined : out; } @@ -132,32 +132,49 @@ export function parseProgram(src: string): Program { /** MO-8: a declaration file (`api.d.rx`) for a JS module — what each export is, in rows: `export pure fn f(a) rejects(A | B)`, * `export fn g(a)` (io: dirty is the default, R-io-4), `export error NotFound` (a JS class that is an error class), `export type T`. */ export type JsDecl = - | { kind: "fn"; name: string; pure: boolean; params: string[]; rejects?: string[]; line: number; side?: "server" | "client"; ptypes?: (string | undefined)[]; ret?: string; refs?: boolean[]; shape?: Shape; instantiates?: boolean } // side: 12 SF-5; types: text, for TY (types/), `ref` taken out; MO-10: refs (ref parameters), shape (what its result is), instantiates (written, or inferred from a ref) + | { kind: "fn"; name: string; pure: boolean; params: string[]; generics?: string; rejects?: string[]; line: number; side?: "server" | "client"; ptypes?: (string | undefined)[]; ret?: string; refs?: boolean[]; shape?: Shape; instantiates?: boolean } // side: 12 SF-5; types: text, for TY (types/), `ref` taken out; MO-10: refs (ref parameters), shape (what its result is), instantiates (written, or inferred from a ref) | { kind: "error"; name: string; line: number } - | { kind: "type"; name: string; line: number; text?: string }; + | { kind: "type"; name: string; line: number; text?: string; exported: boolean }; +function typeParams(c: Cursor): string | undefined { + const start = c.i; + if (!c.eat("<")) return; + let depth = 1; + while (!c.eof()) { + if (c.eat("=>")) continue; + if (c.eat("<")) depth++; + else if (c.eat(">")) { if (--depth === 0) return c.src.slice(start, c.i); } + else if (c.peek() === "'" || c.peek() === '"' || c.peek() === "`") { + const quote = c.peek(); c.i++; + while (!c.eof() && c.peek() !== quote) { if (c.eat("\\")) c.i++; else c.i++; } + c.expect(quote); + } else c.i++; + } + c.fail("expected '>' to end type parameters"); +} export function parseDeclarations(src: string): JsDecl[] { const c = new Cursor(src); const out: JsDecl[] = []; for (;;) { - c.ws(); if (c.eof()) return out; + c.ws(); if (c.eat(";")) continue; if (c.eof()) return out; const line = c.line; - if (!c.keyword("export")) c.fail("a declaration file declares exports: `export pure fn …`, `export fn …`, `export error …`, `export type …`"); + const exported = c.keyword("export"); c.ws(); - if (c.startsWith("type") || c.startsWith("interface")) { const t0 = c.i; c.keyword("type") || c.keyword("interface"); c.ws(); const name = c.ident() ?? c.fail("type name"); c.ws(); if (c.eat("=")) { c.ws(); parseType(c, false, true); } else if (c.startsWith("{")) { let depth = 0; do { if (c.peek() === "{") depth++; if (c.peek() === "}") depth--; c.i++; } while (!c.eof() && depth); } out.push({ kind: "type", name, line, text: c.src.slice(t0, c.i) }); continue; } + if (c.peekIdent() === "type" || c.peekIdent() === "interface") { const t0 = c.i; c.keyword("type") || c.keyword("interface"); c.ws(); const name = c.ident() ?? c.fail("type name"); c.ws(); typeParams(c); c.ws(); if (c.eat("=")) { c.ws(); parseType(c, false, true); } else if (c.startsWith("{")) { let depth = 0; do { if (c.peek() === "{") depth++; if (c.peek() === "}") depth--; c.i++; } while (!c.eof() && depth); } out.push({ kind: "type", name, line, text: c.src.slice(t0, c.i), exported }); continue; } + if (!exported) c.fail("a declaration file declares exports: `export pure fn …`, `export fn …`, `export error …`, `export type …`"); if (c.keyword("error")) { c.ws(); const name = c.ident() ?? c.fail("error class name"); out.push({ kind: "error", name, line }); continue; } const side = c.keyword("server") ? "server" as const : c.keyword("client") ? "client" as const : undefined; c.ws(); // 12 SF-5: runs on one side only const pure = c.keyword("pure"); c.ws(); if (!c.keyword("fn")) c.fail("fn"); - c.ws(); const name = c.ident() ?? c.fail("fn name"); c.ws(); c.expect("("); c.ws(); + c.ws(); const name = c.ident() ?? c.fail("fn name"); c.ws(); const generics = typeParams(c); c.ws(); c.expect("("); c.ws(); const params: string[] = []; const ptypes: (string | undefined)[] = []; const refs: boolean[] = []; while (!c.startsWith(")")) { const r = c.keyword("ref"); if (r) c.ws(); refs.push(r); params.push(c.ident() ?? c.fail("param")); c.ws(false); ptypes.push(c.peek() === ":" ? (c.i++, c.ws(), parseType(c, false, true)) : undefined); c.ws(); if (!c.eat(",")) break; c.ws(); } // MO-10a: a ref parameter takes an accessor c.expect(")"); const save = c.i; c.ws(false); let ret: string | undefined; let shape: Shape | undefined; if (c.peek() === ":" ) { c.i++; c.ws(); const t = c.src.slice(c.i).split("\n")[0]; const r = /\brejects\(|\binstantiates\b/.exec(t); const raw = (r ? t.slice(0, r.index) : t).replace(/\/\/.*$/, "").trim(); shape = raw ? shapeOf(raw) : undefined; ret = raw.replace(/\bref\s+/g, "") || undefined; c.i += r ? r.index : t.length; } else c.i = save; // MO-10b: `ref T` is an accessor, read as T c.ws(false); let rejects: string[] | undefined; - if (c.keyword("rejects")) { c.ws(); c.expect("("); rejects = parseClasses(c) ?? ["Error"]; c.ws(); c.expect(")"); } + if (c.keyword("rejects")) { c.ws(); c.expect("("); rejects = parseClasses(c, true) ?? ["Error"]; c.ws(); c.expect(")"); } c.ws(false); const written = c.keyword("instantiates"); const instantiates = written || refs.some(x => x) || shapeHasRef(shape); // MO-10a: inferred from a ref on either side - out.push({ kind: "fn", name, pure, params, rejects, line, ptypes, ret, ...(side ? { side } : {}), ...(instantiates ? { refs, shape: shape ?? "value", instantiates } : {}) }); + out.push({ kind: "fn", name, pure, params, generics, rejects, line, ptypes, ret, ...(side ? { side } : {}), ...(instantiates ? { refs, shape: shape ?? "value", instantiates } : {}) }); } } diff --git a/ref/types/project.ts b/ref/types/project.ts index 7c24ac4e..aacca828 100644 --- a/ref/types/project.ts +++ b/ref/types/project.ts @@ -110,10 +110,10 @@ function signatureStub(sig: ModSig): string { /** MO-8: a `.d.rx` as TypeScript's `.d.ts` for the same JS module. */ function declarationFile(decls: JsDecl[]): string { return decls.map(d => { - if (d.kind === "type") return `export ${d.text ?? `type ${d.name} = any`}`; + if (d.kind === "type") return `${d.exported ? "export " : ""}${d.text ?? `type ${d.name} = any`}`; if (d.kind === "error") return `export declare class ${d.name}$ extends Error {}\nexport declare const ${d.name}: (message?: string) => ${d.name}$;\nexport type ${d.name} = ${d.name}$;`; const ps = d.params.map((n, i) => `${n}${d.ptypes?.[i] ? `: ${d.ptypes[i]}` : ""}`).join(", "); - return `export declare function ${d.name}(${ps}): ${d.ret ?? "any"};`; + return `export declare function ${d.name}${d.generics ?? ""}(${ps}): ${d.ret ?? "any"};`; }).join("\n") + "\n"; } @@ -183,10 +183,11 @@ class Proj { private importDecl(d: Extract, ind: string) { const names = d.names.map(n => n.name === "default" ? null : n.name === n.alias ? n.name : `${n.name} as ${n.alias}`).filter(Boolean); const dflt = d.names.find(n => n.name === "default")?.alias; - for (const n of d.names) if (BUILTINS.has(n.name)) this.declared.delete(n.alias); // the prelude's own (`import { log } from "./prelude"`) - const prelude = d.names.filter(n => BUILTINS.has(n.name)); + const isPrelude = (n: string) => d.from === "./prelude" && BUILTINS.has(n); + for (const n of d.names) if (isPrelude(n.name)) this.declared.delete(n.alias); else this.declared.add(n.alias); + const prelude = d.names.filter(n => isPrelude(n.name)); if (prelude.length) { for (const n of prelude) this.used.add(n.name); } - const rest = d.names.filter(n => !BUILTINS.has(n.name)); if (!rest.length) return; + const rest = d.names.filter(n => !isPrelude(n.name)); if (!rest.length) return; let from = d.from; if (!d.resolved && !d.declared) { // a JS module with no declaration: `any` const key = this.modPath(d.from) + ".ts"; let s = this.jsStubs.get(key); if (!s) this.jsStubs.set(key, (s = new Set())); for (const n of rest) s.add(n.name); from = d.from; diff --git a/scenarios/S-module-5.md b/scenarios/S-module-5.md new file mode 100644 index 00000000..6f760810 --- /dev/null +++ b/scenarios/S-module-5.md @@ -0,0 +1,40 @@ +# S-module-5 — Foreign function types survive projection + +Rules exercised: MO-8, TY-4b. + +## Modules + +```rx +-- module: ./api.d.rx +type Cleanup = () => void +export error Offline +export error Stopped +export fn every(callback: () => void, ms: number): Cleanup +export pure fn identity(value: T): T +export fn flush(): Promise rejects(Offline, Stopped) +``` + +## Program + +```rx +import { every, identity } from "./api" +action start() { + every(() => {}, 5000) +} +fn roundTrip(n: number): number => identity(n) +export default component App() {

ok

} +``` + +## Frames + +| instant | action | frame | +| --- | --- | --- | +| 0 | mount | `ok` | + +## Rejected: private aliases are not exports + +```rx +-- reject: NOT_EXPORTED +import { Cleanup } from "./api" +export default component App() {

ok

} +``` diff --git a/spec/09-modules.md b/spec/09-modules.md index b2aec238..2aa31cdb 100644 --- a/spec/09-modules.md +++ b/spec/09-modules.md @@ -164,6 +164,10 @@ export component Save(props: { v: unrendered action go catches(nothing) }) `rejects(…)` defaults to `Error`. In every `.d.rx` — written for a JS module or printed for an `.rx` one — `pure fn` is pure, `fn` is io, and `action` is an action. + A JS declaration may use TypeScript type parameters, as in `export pure + fn identity(value: T): T`, and private `type` or `interface` + declarations for types used in the file. In a JS declaration, + `rejects(A, B)` names the same rejection row as `rejects(A | B)`. - **MO-8b.** With a declaration file, the file is the row, as a signature is for an `.rx` import (MO-4a): an import that names an undeclared export is `NOT_EXPORTED`; `pure` on the import must agree (`IMPORT_ROW_MISMATCH` From d103f9586f0d3bcc8efea2b0c351f5b016fe747d Mon Sep 17 00:00:00 2001 From: Dev Agrawal Date: Tue, 24 Nov 2026 20:24:33 -0600 Subject: [PATCH 03/34] Parse computed keys, casts, and multiline member chains. --- compiler/src/ast.rs | 5 ++++ compiler/src/check.rs | 24 ++++++++++------ compiler/src/emit.rs | 2 ++ compiler/src/infer.rs | 6 ++-- compiler/src/js.rs | 1 + compiler/src/oxc.rs | 4 ++- compiler/src/parse.rs | 62 ++++++++++++++++++++++++++++++++++++++-- compiler/src/project.rs | 2 ++ compiler/src/spans.rs | 15 ++++++---- ref/compile/emit.ts | 3 +- ref/oracle/lower.ts | 3 +- ref/src/ast.ts | 3 +- ref/src/check.ts | 31 +++++++++++--------- ref/src/infer.ts | 5 ++-- ref/src/parse.ts | 37 ++++++++++++++++++++++-- ref/src/runtime.ts | 7 +++-- ref/types/project.ts | 3 +- scenarios/S-ts-expr-1.md | 23 +++++++++++++++ 18 files changed, 191 insertions(+), 45 deletions(-) create mode 100644 scenarios/S-ts-expr-1.md 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 b5c2ec4c..29f6102a 100644 --- a/compiler/src/check.rs +++ b/compiler/src/check.rs @@ -395,7 +395,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 +410,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 +482,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 +519,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), } } @@ -2170,7 +2173,7 @@ impl<'a> Checker<'a> { self.expr(x, env, ctx, None); self.model.probe = save; } - ExprKind::Un { e: x, .. } | ExprKind::Spread(x) | ExprKind::Omit { e: x, .. } => self.expr(x, env, ctx, None), + ExprKind::Un { e: x, .. } | ExprKind::As { e: x, .. } | ExprKind::Spread(x) | ExprKind::Omit { e: x, .. } => self.expr(x, env, ctx, None), ExprKind::Await { e: inner, init, .. } => { if ctx.imperative && !self.stmt_awaits.contains(&(e as *const Expr)) { let sh = show(e); @@ -2255,12 +2258,15 @@ impl<'a> Checker<'a> { for f in fields { match f { Field::Kv { v, .. } => self.expr(v, env, ctx, None), + Field::Computed { key, v } => { self.expr(key, env, ctx, None); self.expr(v, env, ctx, None); } Field::Spread(x) => self.expr(x, env, ctx, None), } } } ExprKind::Call { f, args } => { - if let ExprKind::Id(fname) = &f.k { + let mut callee = &**f; + while let ExprKind::As { e, .. } = &callee.k { callee = e; } + if let ExprKind::Id(fname) = &callee.k { if fname == "until" && self.lookup(env, "until").is_none() { if !ctx.imperative { self.err("IO_IN_REACTIVE", "AC-6", "until(…) waits for the world to confirm a condition: it is called from imperative scope (an action or a handler), and awaited".into()); @@ -3820,12 +3826,14 @@ impl<'a> Checker<'a> { fn root(x: &Expr) -> &Expr { match &x.k { ExprKind::Member { o, .. } | ExprKind::Index { o, .. } => root(o), + ExprKind::As { e, .. } => root(e), _ => x, } } let error = || -> IndexSet { ["Error".to_string()].into_iter().collect() }; match &e.k { ExprKind::Lit(_) | ExprKind::Tpl(_) | ExprKind::Arr(_) | ExprKind::Rec(_) | ExprKind::Bin { .. } | ExprKind::Un { .. } => IndexSet::new(), + ExprKind::As { e, .. } => self.rejects(e, env, seen), ExprKind::If { t, f, .. } => { let mut a = self.rejects(t, env, seen); a.extend(self.rejects(f, env, seen)); diff --git a/compiler/src/emit.rs b/compiler/src/emit.rs index 95f55eb2..0e71b279 100644 --- a/compiler/src/emit.rs +++ b/compiler/src/emit.rs @@ -1376,6 +1376,7 @@ impl<'p> Gen<'p> { rtc("preOr", vec![call(id(p), vec![]), thunk(i)]) } ExprKind::Peek(x) => rtc("untrack", vec![thunk(self.expr(x, env, &sub)?)]), + ExprKind::As { e: x, .. } => self.expr(x, env, &sub)?, // RG-4b: Solid's live view ExprKind::Omit { e: x, keys } => rtc("omit", std::iter::once(self.expr(x, env, &sub)).chain(keys.iter().map(|k| Ok(str(k.clone())))).collect::, _>>()?), ExprKind::Await { e: x, stream, .. } => { @@ -1491,6 +1492,7 @@ impl<'p> Gen<'p> { ps.push(match f { crate::ast::Field::Spread(x) => Prop::Spread(self.expr(x, env, &sub)?), crate::ast::Field::Kv { key, v } => Prop::Kv(Key::Str(key.clone()), self.expr(v, env, &sub)?), + crate::ast::Field::Computed { key, v } => Prop::Kv(Key::Computed(Box::new(self.expr(key, env, &sub)?)), self.expr(v, env, &sub)?), }); } E::Obj(ps) diff --git a/compiler/src/infer.rs b/compiler/src/infer.rs index a90d1b48..49258385 100644 --- a/compiler/src/infer.rs +++ b/compiler/src/infer.rs @@ -304,7 +304,7 @@ impl<'o> Walker<'o> { self.read(l, st, sh, local, depth); self.read(r, st, sh, local, depth); } - ExprKind::Un { e, .. } | ExprKind::Spread(e) | ExprKind::Omit { e, .. } | ExprKind::Throw(e) => self.read(e, st, sh, local, depth), + ExprKind::Un { e, .. } | ExprKind::As { e, .. } | ExprKind::Spread(e) | ExprKind::Omit { e, .. } | ExprKind::Throw(e) => self.read(e, st, sh, local, depth), ExprKind::Await { e, init, .. } => { self.read(e, st, sh, local, depth); if let Some(i) = init { @@ -332,6 +332,7 @@ impl<'o> Walker<'o> { for f in fields { match f { Field::Kv { v, .. } => self.read(v, st, sh, local, depth), + Field::Computed { key, v } => { self.read(key, st, sh, local, depth); self.read(v, st, sh, local, depth); } Field::Spread(e) => self.read(e, st, sh, local, depth), } } @@ -395,7 +396,7 @@ impl<'o> Walker<'o> { self.deps(l, st, sh, out); self.deps(r, st, sh, out); } - ExprKind::Un { e, .. } | ExprKind::Spread(e) | ExprKind::Omit { e, .. } | ExprKind::Throw(e) => self.deps(e, st, sh, out), + ExprKind::Un { e, .. } | ExprKind::As { e, .. } | ExprKind::Spread(e) | ExprKind::Omit { e, .. } | ExprKind::Throw(e) => self.deps(e, st, sh, out), ExprKind::If { c, t, f } => { self.deps(c, st, sh, out); self.deps(t, st, sh, out); @@ -417,6 +418,7 @@ impl<'o> Walker<'o> { for f in fields { match f { Field::Kv { v, .. } => self.deps(v, st, sh, out), + Field::Computed { key, v } => { self.deps(key, st, sh, out); self.deps(v, st, sh, out); } Field::Spread(e) => self.deps(e, st, sh, out), } } diff --git a/compiler/src/js.rs b/compiler/src/js.rs index 78357c0f..7a4a74b1 100644 --- a/compiler/src/js.rs +++ b/compiler/src/js.rs @@ -48,6 +48,7 @@ pub enum P { pub enum Key { Ident(String), Str(String), + Computed(Box), } #[derive(Debug, Clone)] diff --git a/compiler/src/oxc.rs b/compiler/src/oxc.rs index d7bd6bd7..76bcb6b3 100644 --- a/compiler/src/oxc.rs +++ b/compiler/src/oxc.rs @@ -328,11 +328,13 @@ impl<'a> Build<'a> { SPAN, self.vec(props.iter().map(|p| match p { Prop::Kv(k, v) => { + let computed = matches!(k, Key::Computed(_)); let key = match k { Key::Ident(n) => PropertyKey::new_static_identifier(SPAN, self.s(n), b), Key::Str(s) => PropertyKey::new_string_literal(SPAN, self.s(s), None, b), + Key::Computed(x) => PropertyKey::from(self.expr(x)), }; - ObjectPropertyKind::new_object_property(SPAN, PropertyKind::Init, key, self.expr(v), false, false, false, b) + ObjectPropertyKind::new_object_property(SPAN, PropertyKind::Init, key, self.expr(v), false, false, computed, b) } Prop::Spread(x) => ObjectPropertyKind::new_spread_property(SPAN, self.expr(x), b), })), diff --git a/compiler/src/parse.rs b/compiler/src/parse.rs index 9547141e..f83b7ccd 100644 --- a/compiler/src/parse.rs +++ b/compiler/src/parse.rs @@ -512,8 +512,8 @@ fn type_params(c: &mut Cursor) -> R> { let quote = c.peek(); c.bump(); while !c.eof() && c.peek() != quote { - if c.eat("\\") { c.bump(); } - else { c.bump(); } + c.eat("\\"); + c.bump(); } if c.eof() { return c.fail("unterminated string in type parameters"); } c.bump(); @@ -1610,6 +1610,12 @@ fn parse_bin(c: &mut Cursor, lvl: usize) -> R { let start = l.span.start as usize; loop { c.ws(false); + if lvl == 4 && c.keyword("as") { + c.ws(true); + let ty = assertion_type(c)?; + l = ex(start, ExprKind::As { e: Box::new(l), ty }, c); + continue; + } let op = LEVELS[lvl].iter().find(|o| c.starts_with(o) && !(**o == "-" && c.peek_at(1) == '>')); let Some(op) = op else { return Ok(l) }; c.i += op.len(); @@ -1623,6 +1629,43 @@ fn parse_bin(c: &mut Cursor, lvl: usize) -> R { l = Expr::new(ExprKind::Bin { op: op.to_string(), l: Box::new(l), r: Box::new(r) }, Span::new(start, c.i)); } } +/// A type assertion ends at the surrounding expression's delimiter, not at a nested type delimiter. +fn assertion_type(c: &mut Cursor) -> R { + let start = c.i; + let mut end = start; + let mut stack = vec![]; + while !c.eof() { + let ch = c.peek(); + if stack.is_empty() && (",\n;:)=]}?+*/%!<>-".contains(ch) || c.starts_with("&&") || c.starts_with("||") || matches!(c.peek_ident().as_deref(), Some("as" | "catch"))) { + if ch != '<' { break; } + if type_params(c).is_err() { break; } + end = c.i; + continue; + } + if c.ident().is_some() { end = c.i; continue; } + if !stack.is_empty() && c.eat("=>") { end = c.i; continue; } + if matches!(ch, '\'' | '"' | '`') { + c.bump(); + while !c.eof() && c.peek() != ch { c.eat("\\"); c.bump(); } + if c.eof() { return c.fail("unterminated string in type assertion"); } + c.bump(); + } else { + match ch { + '(' => stack.push(')'), + '[' => stack.push(']'), + '{' => stack.push('}'), + '<' => stack.push('>'), + _ if stack.last() == Some(&ch) => { stack.pop(); } + _ => {} + } + c.bump(); + } + if !ch.is_whitespace() { end = c.i; } + } + if end == start || !stack.is_empty() { return c.fail("type after `as`"); } + c.i = end; + Ok(c.src[start..end].to_string()) +} fn parse_unary(c: &mut Cursor) -> R { c.ws(true); let start = c.i; @@ -1682,6 +1725,9 @@ fn parse_postfix(c: &mut Cursor) -> R { let mut e = parse_primary(c)?; let start = e.span.start as usize; loop { + let save = c.i; + c.ws(true); + if !c.starts_with(".") && !c.starts_with("?.") { c.i = save; } if c.eat("?.") { if c.peek() == '[' { c.bump(); @@ -1844,6 +1890,18 @@ fn parse_primary(c: &mut Cursor) -> R { c.ws(true); continue; } + if c.eat("[") { + let key = parse_expr(c)?; + c.ws(true); + c.expect("]")?; + c.ws(true); + c.expect(":")?; + fields.push(Field::Computed { key, v: parse_expr(c)? }); + c.ws(true); + if !c.eat(",") { break; } + c.ws(true); + continue; + } let k0 = c.i; let key = match c.ident() { Some(k) => k, diff --git a/compiler/src/project.rs b/compiler/src/project.rs index f0b592bb..0bd33b64 100644 --- a/compiler/src/project.rs +++ b/compiler/src/project.rs @@ -753,6 +753,7 @@ impl Proj<'_> { } } ExprKind::Peek(x) | ExprKind::Latest(x) => go!(x), + ExprKind::As { e: x, ty } => Code::of("(").c(go!(x)).t(" as ").c(self.ty(ty, e.span, &mut (x.span.end as usize))).t(")"), ExprKind::Pending(x) => Code::of("__.pending(").c(go!(x)).t(")"), ExprKind::Await { e: x, init, stream } => { if imp { @@ -804,6 +805,7 @@ impl Proj<'_> { .map(|f| match f { Field::Spread(x) => Code::of("...").c(go!(x)), Field::Kv { key, v } => Code::of(&js_str(key)).t(": ").c(go!(v)), + Field::Computed { key, v } => Code::of("[").c(go!(key)).t("]: ").c(go!(v)), }) .collect(); Code::of("({ ").c(Code::join(fs, ", ")).t(" })") diff --git a/compiler/src/spans.rs b/compiler/src/spans.rs index 9eac036b..1b73e658 100644 --- a/compiler/src/spans.rs +++ b/compiler/src/spans.rs @@ -150,7 +150,7 @@ impl Spans<'_> { sub(l); sub(r); } - ExprKind::Un { e, .. } | ExprKind::Peek(e) | ExprKind::Latest(e) | ExprKind::Pending(e) | ExprKind::Spread(e) | ExprKind::Omit { e, .. } | ExprKind::Throw(e) => sub(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) => sub(e), ExprKind::Pre { init, .. } => init.iter().for_each(|x| sub(x)), ExprKind::Await { e, init, .. } => { sub(e); @@ -178,6 +178,7 @@ impl Spans<'_> { ExprKind::Arr(items) => items.iter().for_each(&mut sub), ExprKind::Rec(fields) => fields.iter().for_each(|f| match f { Field::Kv { v, .. } => sub(v), + Field::Computed { key, v } => { sub(key); sub(v); } Field::Spread(x) => sub(x), }), ExprKind::Catch { e, alt, .. } => { @@ -353,7 +354,7 @@ pub fn walk(p: &Program, f: &mut dyn FnMut(Span)) { match &e.k { ExprKind::Lit(_) | ExprKind::Id(_) | ExprKind::Use(_) | ExprKind::StyleMap { .. } => {} ExprKind::Bin { l, r, .. } => sub.extend([&**l, &**r]), - ExprKind::Un { e, .. } | ExprKind::Peek(e) | ExprKind::Latest(e) | ExprKind::Pending(e) | ExprKind::Spread(e) | ExprKind::Omit { e, .. } | ExprKind::Throw(e) => sub.push(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) => sub.push(e), ExprKind::Pre { init, .. } => sub.extend(init.iter().map(|x| &**x)), ExprKind::Await { e, init, .. } => sub.extend(std::iter::once(&**e).chain(init.iter().map(|x| &**x))), ExprKind::If { c, t, f } => sub.extend([&**c, &**t, &**f]), @@ -362,10 +363,12 @@ pub fn walk(p: &Program, f: &mut dyn FnMut(Span)) { ExprKind::Index { o, i, .. } => sub.extend([&**o, &**i]), ExprKind::Call { f, args } => sub.extend(std::iter::once(&**f).chain(args.iter())), ExprKind::Arr(items) => sub.extend(items.iter()), - ExprKind::Rec(fields) => sub.extend(fields.iter().map(|x| match x { - Field::Kv { v, .. } => v, - Field::Spread(x) => x, - })), + ExprKind::Rec(fields) => for f in fields { + match f { + Field::Kv { v, .. } | Field::Spread(v) => sub.push(v), + Field::Computed { key, v } => sub.extend([key, v]), + } + }, ExprKind::Catch { e, alt, .. } => sub.extend([&**e, &**alt]), ExprKind::Fn { body, stmts, .. } => { sub.push(body); diff --git a/ref/compile/emit.ts b/ref/compile/emit.ts index 3253ae34..8a8bdc42 100644 --- a/ref/compile/emit.ts +++ b/ref/compile/emit.ts @@ -489,7 +489,8 @@ class Gen { return `${go(e.f)}(${e.args.map(go).join(", ")})`; } case "arr": return `[${e.items.map(i => i.k === "spread" ? `...${go(i.e)}` : go(i)).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); + 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 "fn": { const inner = this.params(env, e.params); const ps = e.params.map(mg).join(", "); if (e.stmts && inferredAction(e.stmts)) return `(${ps}) => __rt.action(function* () {\n${this.stmts(e.stmts, inner, { imp: true, gen: true, dyn: ctx.dyn, effect: ctx.effect }, 1)}\n})()`; // AC-1b: an inferred action lowers as `action { … }` does, to Solid's action() diff --git a/ref/oracle/lower.ts b/ref/oracle/lower.ts index 6c22b90d..390bf77a 100644 --- a/ref/oracle/lower.ts +++ b/ref/oracle/lower.ts @@ -500,7 +500,8 @@ export class Oracle { return BIN[e.op](l, r); } case "arr": { const out: unknown[] = []; for (const i of e.items) { if (i.k === "spread") out.push(...(this.ev(i.e, scope, env) as unknown[])); else out.push(this.ev(i, scope, env)); } return out; } - case "rec": { const o: Record = {}; for (const f of e.fields) { if ("spread" in f) Object.assign(o, this.ev(f.spread, scope, env)); else o[f.key] = this.ev(f.v, scope, env); } return o; } + case "as": return this.ev(e.e, scope, env); + case "rec": { const o: Record = {}; for (const f of e.fields) { if ("spread" in f) Object.assign(o, this.ev(f.spread, scope, env)); else if ("computed" in f) Object.defineProperty(o, this.ev(f.computed, scope, env) as PropertyKey, { value: this.ev(f.v, scope, env), enumerable: true, configurable: true, writable: true }); else o[f.key] = this.ev(f.v, scope, env); } return o; } case "fn": if (e.stmts && inferredAction(e.stmts)) return this.lowerAction(e.params, e.stmts, scope, env); // AC-1b return (...args: unknown[]) => { const en = new Map(env); e.params.forEach((p, i) => en.set(p, args[i])); return e.stmts ? this.runStmts(e.stmts, scope, en) : this.ev(e.body, scope, en); }; case "stylemap": return classMap(e.css); // 07 CSS-5 diff --git a/ref/src/ast.ts b/ref/src/ast.ts index 8c6a1a39..6ca1a114 100644 --- a/ref/src/ast.ts +++ b/ref/src/ast.ts @@ -17,7 +17,8 @@ export type Expr = | { k: "index"; o: Expr; i: Expr; opt?: boolean } | { k: "call"; f: Expr; args: Expr[] } | { k: "arr"; items: Expr[] } - | { k: "rec"; fields: ({ key: string; v: Expr } | { spread: Expr })[] } + | { k: "rec"; fields: ({ key: string; v: Expr } | { computed: Expr; v: Expr } | { spread: Expr })[] } + | { k: "as"; e: Expr; ty: string } | { k: "fn"; params: string[]; body: Expr; stmts?: Stmt[] } // stmts: a statement-bodied arrow (imperative scope, 07 §5) | { k: "draft"; seed: Expr; body: Stmt[] } // ST-3: the only writes in reactive scope, to `d` | { k: "use"; name: string } // RG-7b: the nearest provision above diff --git a/ref/src/check.ts b/ref/src/check.ts index 9f95fcd8..3191a717 100644 --- a/ref/src/check.ts +++ b/ref/src/check.ts @@ -119,7 +119,7 @@ export function freeNames(e: Expr, bound: Set, out: Set): void { case "pre": if (!bound.has(e.name)) out.add(`pre:${e.name}`); return; case "peek": go(e.e); return; case "await": go(e.e); if (e.init) go(e.init); return; - case "latest": case "pending": case "un": case "spread": case "omit": go(e.e); return; + case "latest": case "pending": case "un": case "spread": case "omit": case "as": go(e.e); return; case "bin": go(e.l); go(e.r); return; case "if": go(e.c); go(e.t); go(e.f); return; case "tpl": for (const p of e.parts) if (typeof p !== "string") go(p); return; @@ -127,7 +127,7 @@ export function freeNames(e: Expr, bound: Set, out: Set): void { case "index": go(e.o); go(e.i); return; case "call": go(e.f); e.args.forEach(go); return; case "arr": e.items.forEach(go); return; - case "rec": for (const f of e.fields) go("spread" in f ? f.spread : f.v); return; + case "rec": for (const f of e.fields) { if ("computed" in f) go(f.computed); go("spread" in f ? f.spread : f.v); } return; case "fn": { const b = new Set([...bound, ...e.params]); freeNames(e.body, b, out); if (e.stmts) freeNamesStmts(e.stmts, b, out); return; } case "draft": { go(e.seed); freeNamesStmts(e.body, new Set([...bound, "d"]), out); return; } case "throw": go(e.e); return; @@ -852,7 +852,7 @@ class Checker { case "use": { if (ctx.server) this.err("SERVER_CAPTURE", "SF-3", `a server function's body reads \`use ${e.name}\`: a provision is the client's — pass it as an argument`); const c = this.ctxOf(e.name, env); if (c) this.model.read(c, ctx.scope === "imperative"); if (c && !c.ctx!.dflt) this.uses.push({ region: env.region, name: c.ctx!.key, line: this.line, display: e.name }); return; } case "peek": this.model.snap++; go(e.e); this.model.snap--; return; // E-5: a snapshot case "latest": case "pending": { const save = this.model.probe; this.model.probe = e.k; go(e.e); this.model.probe = save; return; } // R-9, R-12: probes - case "un": case "spread": case "omit": go(e.e); return; + case "un": case "spread": case "omit": case "as": go(e.e); return; case "await": if (ctx.scope === "imperative" && !this.stmtAwaits.has(e)) this.err("AWAIT_IN_EXPRESSION", "AC-1", `\`${show(e)}\` inside an expression of imperative scope: a run suspends only at a statement — bind it first, \`let v = ${show(e)}\` (a \`catch (e) => alt\` may follow it)`); this.awaitedCalls.add(e.e); go(e.e); if (e.init) go(e.init); return; @@ -877,8 +877,9 @@ class Checker { case "member": if (e.o.k === "id") this.expr(e.o, env, ctx, e.p); else go(e.o); return; case "index": go(e.o); go(e.i); return; case "arr": e.items.forEach(go); return; - case "rec": for (const f of e.fields) go("spread" in f ? f.spread : f.v); return; + case "rec": for (const f of e.fields) { if ("computed" in f) go(f.computed); go("spread" in f ? f.spread : f.v); } return; case "call": { + let callee = e.f; while (callee.k === "as") callee = callee.e; if (e.f.k === "id" && e.f.name === "until" && !env.lookup("until")) { // AC-6: `until(() => p)`, a function of the language (Solid's until) if (ctx.scope === "reactive") this.err("IO_IN_REACTIVE", "AC-6", "until(…) waits for the world to confirm a condition: it is called from imperative scope (an action or a handler), and awaited"); const p = e.args[0]; @@ -895,16 +896,17 @@ class Checker { this.expr(p, env, { scope: "imperative", server: ctx.server }); // the callback is imperative scope return; } - if (e.f.k === "id") { - const s = env.lookup(e.f.name); - if (ctx.scope === "reactive" && (s?.io || (!s && e.f.name === "log"))) { - if (ctx.inFn) this.err("IO_IN_FN", "R-io-2", `${e.f.name}(…) is io; a fn is pure by definition`); - else this.err(s?.kind === "action" ? "ACTION_CALLED_IN_OWNED_SCOPE" : "IO_IN_REACTIVE", "IO-2", `${e.f.name}(…) is io and is called in reactive scope (R-io-3)${s?.ioVia ? ` — its server body calls ${s.ioVia}` : ""}`); + if (callee.k === "id") { + const name = callee.name; + const s = env.lookup(name); + if (ctx.scope === "reactive" && (s?.io || (!s && name === "log"))) { + if (ctx.inFn) this.err("IO_IN_FN", "R-io-2", `${name}(…) is io; a fn is pure by definition`); + else this.err(s?.kind === "action" ? "ACTION_CALLED_IN_OWNED_SCOPE" : "IO_IN_REACTIVE", "IO-2", `${name}(…) is io and is called in reactive scope (R-io-3)${s?.ioVia ? ` — its server body calls ${s.ioVia}` : ""}`); } - if (s?.side === "client" && ctx.scope === "reactive" && !ctx.server && !this.awaitedCalls.has(e)) this.err("CLIENT_NOT_AWAITED", "SF-5b", `${e.f.name}(…) is \`client\` JS: in reactive scope it is awaited — a client question, asked once the browser has the page (SV-7b) — never called for its value now`); - if (s?.kind === "fn" && s.instantiating) this.err("INSTANTIATION_NOT_BOUND", "E-9", `${e.f.name}(…) declares state: bind it, \`x = ${e.f.name}(…)\` (RG-6)`); - if (s?.kind === "comp") this.err("COMPONENT_AS_VALUE", "RG-4a", `component ${e.f.name} called as a function: apply it in a view`); - if (s?.kind === "action" && s.arity !== undefined && e.args.length !== s.arity) this.err("ARGUMENT_COUNT", "AC-1f", `${e.f.name} takes ${s.arity === 0 ? "no arguments" : s.arity === 1 ? "1 argument" : `${s.arity} arguments`} and is called with ${e.args.length}: an action's parameters are its whole input — pass each one, and nothing it does not declare`); + if (s?.side === "client" && ctx.scope === "reactive" && !ctx.server && !this.awaitedCalls.has(e)) this.err("CLIENT_NOT_AWAITED", "SF-5b", `${name}(…) is \`client\` JS: in reactive scope it is awaited — a client question, asked once the browser has the page (SV-7b) — never called for its value now`); + if (s?.kind === "fn" && s.instantiating) this.err("INSTANTIATION_NOT_BOUND", "E-9", `${name}(…) declares state: bind it, \`x = ${name}(…)\` (RG-6)`); + if (s?.kind === "comp") this.err("COMPONENT_AS_VALUE", "RG-4a", `component ${name} called as a function: apply it in a view`); + if (s?.kind === "action" && s.arity !== undefined && e.args.length !== s.arity) this.err("ARGUMENT_COUNT", "AC-1f", `${name} takes ${s.arity === 0 ? "no arguments" : s.arity === 1 ? "1 argument" : `${s.arity} arguments`} and is called with ${e.args.length}: an action's parameters are its whole input — pass each one, and nothing it does not declare`); this.model.call(s); } go(e.f); e.args.forEach(go); return; @@ -1298,9 +1300,10 @@ class Checker { } /** R-f-8: what an awaited value's promise may reject with. A call into a JS import: its declared failure (Error unless narrowed). */ private rejects(e: Expr, env: Env, seen: Set): Set { - const root = (x: Expr): Expr => x.k === "member" || x.k === "index" ? root(x.o) : x; + const root = (x: Expr): Expr => x.k === "member" || x.k === "index" ? root(x.o) : x.k === "as" ? root(x.e) : x; switch (e.k) { case "lit": case "tpl": case "arr": case "rec": case "bin": case "un": return new Set(); // values: `await` is the value (R-1) + case "as": return this.rejects(e.e, env, seen); case "if": return new Set([...this.rejects(e.t, env, seen), ...this.rejects(e.f, env, seen)]); case "call": { const r = root(e.f); diff --git a/ref/src/infer.ts b/ref/src/infer.ts index 00ce0227..6586a76a 100644 --- a/ref/src/infer.ts +++ b/ref/src/infer.ts @@ -99,7 +99,7 @@ export function runFindings(stmts: Stmt[], action: boolean, bound: string[] = [] } default: for (const v of Object.values(x as object)) { - if (Array.isArray(v)) v.forEach(y => { if (y && typeof y === "object") { if ("k" in y) read(y as Expr); else if ("v" in y) read((y as { v: Expr }).v); else if ("spread" in y) read((y as { spread: Expr }).spread); } }); + if (Array.isArray(v)) v.forEach(y => { if (y && typeof y === "object") { if ("computed" in y) read((y as { computed: Expr }).computed); if ("k" in y) read(y as Expr); else if ("v" in y) read((y as { v: Expr }).v); else if ("spread" in y) read((y as { spread: Expr }).spread); } }); else if (v && typeof v === "object" && "k" in (v as object)) read(v as Expr); } } @@ -116,7 +116,7 @@ export function runFindings(stmts: Stmt[], action: boolean, bound: string[] = [] case "fn": case "serverfn": case "draft": case "pending": case "latest": case "lit": case "pre": case "peek": case "stylemap": case "await": return out; default: for (const v of Object.values(x as object)) { - if (Array.isArray(v)) v.forEach(y => { if (y && typeof y === "object") { if ("k" in y) deps(y as Expr, out); else if ("v" in y) deps((y as { v: Expr }).v, out); else if ("spread" in y) deps((y as { spread: Expr }).spread, out); } }); + if (Array.isArray(v)) v.forEach(y => { if (y && typeof y === "object") { if ("computed" in y) deps((y as { computed: Expr }).computed, out); if ("k" in y) deps(y as Expr, out); else if ("v" in y) deps((y as { v: Expr }).v, out); else if ("spread" in y) deps((y as { spread: Expr }).spread, out); } }); else if (v && typeof v === "object" && "k" in (v as object)) deps(v as Expr, out); } return out; @@ -175,4 +175,3 @@ export function runFindings(stmts: Stmt[], action: boolean, bound: string[] = [] walk(stmts, { written: new Map(), held: new Set(), dead: false, taint: taint0, epoch: 0 }, new Set(bound), new Map(), new Set()); return out; } - diff --git a/ref/src/parse.ts b/ref/src/parse.ts index 9e5f3022..a538ad2f 100644 --- a/ref/src/parse.ts +++ b/ref/src/parse.ts @@ -145,7 +145,7 @@ function typeParams(c: Cursor): string | undefined { else if (c.eat(">")) { if (--depth === 0) return c.src.slice(start, c.i); } else if (c.peek() === "'" || c.peek() === '"' || c.peek() === "`") { const quote = c.peek(); c.i++; - while (!c.eof() && c.peek() !== quote) { if (c.eat("\\")) c.i++; else c.i++; } + while (!c.eof() && c.peek() !== quote) { if (c.eat("\\")) c.i++; c.i++; } c.expect(quote); } else c.i++; } @@ -525,12 +525,39 @@ function parseBin(c: Cursor, lvl: number): Expr { let l = parseBin(c, lvl + 1); for (;;) { c.ws(false); + if (lvl === 4 && c.keyword("as")) { + c.ws(); l = { k: "as", e: l, ty: assertionType(c) }; + continue; + } const op = LEVELS[lvl].find(o => c.startsWith(o) && !(o === "-" && c.peek(1) === ">")); if (!op) return l; c.i += op.length; c.ws(); l = { k: "bin", op: OP_ALIAS[op] ?? op, l, r: parseBin(c, lvl + 1) }; } } +/** A type assertion ends at the surrounding expression's delimiter, not at a nested type delimiter. */ +function assertionType(c: Cursor): string { + const start = c.i; let end = start; const stack: string[] = []; + while (!c.eof()) { + const ch = c.peek(); + if (!stack.length && (/[,\n;:)=\]}?+*/%!&<>-]/.test(ch) && !(ch === "&" && c.peek(1) !== "&") || c.startsWith("||") || c.peekIdent() === "as" || c.peekIdent() === "catch")) { + if (ch !== "<") break; + try { typeParams(c); end = c.i; continue; } catch (e) { if (!(e instanceof ParseError)) throw e; c.i = end; break; } + } + if (c.ident() !== null) { end = c.i; continue; } + if (c.startsWith("=>") && stack.length) { c.i += 2; end = c.i; continue; } + if (ch === '"' || ch === "'" || ch === "`") { + c.i++; while (!c.eof() && c.peek() !== ch) { if (c.eat("\\")) c.i++; c.i++; } c.expect(ch); + } else { + if (ch === "(" || ch === "[" || ch === "{" || ch === "<") stack.push(({ "(": ")", "[": "]", "{": "}", "<": ">" })[ch]!); + else if (stack.at(-1) === ch) stack.pop(); + c.i++; + } + if (!/\s/.test(ch)) end = c.i; + } + if (end === start || stack.length) c.fail("type after `as`"); + c.i = end; return c.src.slice(start, end); +} function parseUnary(c: Cursor): Expr { c.ws(); if (c.eat("!")) return { k: "un", op: "!", e: parseUnary(c) }; @@ -555,6 +582,8 @@ function parseUnary(c: Cursor): Expr { function parsePostfix(c: Cursor): Expr { let e = parsePrimary(c); for (;;) { + const save = c.i; c.ws(); + if (!c.startsWith(".") && !c.startsWith("?.")) c.i = save; if (c.eat("?.")) { if (c.peek() === "[") { c.i++; c.ws(); const i = parseExpr(c); c.ws(); c.expect("]"); e = { k: "index", o: e, i, opt: true }; } else e = { k: "member", o: e, p: c.ident() ?? c.fail("member"), opt: true }; } else if (c.eat(".")) e = { k: "member", o: e, p: c.ident() ?? c.fail("member") }; else if (c.peek() === "[") { c.i++; c.ws(); const i = parseExpr(c); c.ws(); c.expect("]"); e = { k: "index", o: e, i }; } @@ -603,9 +632,13 @@ function parsePrimary(c: Cursor): Expr { c.expect("]"); return { k: "arr", items }; } if (c.eat("{")) { - c.ws(); const fields: ({ key: string; v: Expr } | { spread: Expr })[] = []; + c.ws(); const fields: Extract["fields"] = []; while (!c.startsWith("}")) { if (c.eat("...")) { c.ws(); fields.push({ spread: parseExpr(c) }); c.ws(); if (!c.eat(",")) break; c.ws(); continue; } + if (c.eat("[")) { + const computed = parseExpr(c); c.ws(); c.expect("]"); c.ws(); c.expect(":"); + fields.push({ computed, v: parseExpr(c) }); c.ws(); if (!c.eat(",")) break; c.ws(); continue; + } const key = c.ident() ?? (c.peek() === '"' || c.peek() === "'" ? String((parsePrimary(c) as { v: unknown }).v) : c.fail("field")); c.ws(); if (c.eat(":")) { c.ws(); fields.push({ key, v: parseExpr(c) }); } else fields.push({ key, v: { k: "id", name: key } }); c.ws(); if (!c.eat(",")) break; c.ws(); diff --git a/ref/src/runtime.ts b/ref/src/runtime.ts index a9ca0e14..111ba0d4 100644 --- a/ref/src/runtime.ts +++ b/ref/src/runtime.ts @@ -888,7 +888,8 @@ export class Runtime { case "arr": { const items: unknown[] = []; let bad: unknown; for (const i of e.items) { if (i.k === "spread") { const v = this.ev(i.e, region, env); if (isAbsent(v)) bad ??= v; else items.push(...(v as unknown[])); } else { const v = this.ev(i, region, env); if (isAbsent(v)) bad ??= v; items.push(v); } } return bad ?? items; } case "spread": throw new RuleError("SYNTAX", "spread outside an array literal"); case "omit": { const v = this.ev(e.e, region, env); if (isAbsent(v)) return v; const o: Record = {}; if (isObj(v)) for (const k of Object.keys(v)) if (!e.keys.includes(k)) { this.track(v, k); o[k] = v[k]; } return o; } // RG-4b: an object rest - case "rec": { const o: Record = {}; let bad: unknown; for (const f of e.fields) { if ("spread" in f) { const v = this.ev(f.spread, region, env); if (isAbsent(v)) bad ??= v; else if (isObj(v)) { for (const k of Object.keys(v)) { this.track(v, k); o[k] = v[k]; } } continue; } const v = this.ev(f.v, region, env); if (isAbsent(v)) bad ??= v; o[f.key] = v; } return bad ?? o; } + case "as": return this.ev(e.e, region, env); + case "rec": { const o: Record = {}; let bad: unknown; for (const f of e.fields) { if ("spread" in f) { const v = this.ev(f.spread, region, env); if (isAbsent(v)) bad ??= v; else if (isObj(v)) { for (const k of Object.keys(v)) { this.track(v, k); o[k] = v[k]; } } continue; } const k = "computed" in f ? this.ev(f.computed, region, env) : f.key; const v = this.ev(f.v, region, env); if (isAbsent(k)) bad ??= k; else if ("computed" in f) Object.defineProperty(o, k as PropertyKey, { value: v, enumerable: true, configurable: true, writable: true }); else o[f.key] = v; if (isAbsent(v)) bad ??= v; } return bad ?? o; } case "draft": { // ST-3: a copy of the seed, written only along `d`, is the value const seed = this.ev(e.seed, region, env); if (isAbsent(seed)) return seed; const copied = new Set(); @@ -1266,10 +1267,10 @@ function freeVars(e: Expr, out: Set) { case "index": freeVars(e.o, out); freeVars(e.i, out); break; case "call": freeVars(e.f, out); e.args.forEach(a => freeVars(a, out)); break; case "arr": e.items.forEach(a => freeVars(a, out)); break; - case "rec": e.fields.forEach(f => freeVars("spread" in f ? f.spread : f.v, out)); break; + case "rec": e.fields.forEach(f => { if ("computed" in f) freeVars(f.computed, out); freeVars("spread" in f ? f.spread : f.v, out); }); break; case "tpl": e.parts.forEach(p => { if (typeof p !== "string") freeVars(p, out); }); break; case "fn": { const o = new Set(); freeVars(e.body, o); for (const st of e.stmts ?? []) if ("e" in st) freeVars(st.e, o); for (const n of o) if (!e.params.includes(n)) out.add(n); break; } - case "spread": case "omit": freeVars(e.e, out); break; + case "spread": case "omit": case "as": freeVars(e.e, out); break; case "use": break; case "draft": { freeVars(e.seed, out); for (const st of e.body) { if (st.k === "write" || st.k === "let" || st.k === "expr" || st.k === "optimistic") freeVars(st.e, out); if (st.k === "write") for (const p of st.target.path) if (typeof p !== "string") freeVars(p, out); } out.delete("d"); break; } } diff --git a/ref/types/project.ts b/ref/types/project.ts index aacca828..bbe5106a 100644 --- a/ref/types/project.ts +++ b/ref/types/project.ts @@ -264,7 +264,8 @@ class Proj { case "stylemap": { const r = transform(`export const __s = ;`, { 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": { diff --git a/scenarios/S-ts-expr-1.md b/scenarios/S-ts-expr-1.md new file mode 100644 index 00000000..7d538233 --- /dev/null +++ b/scenarios/S-ts-expr-1.md @@ -0,0 +1,23 @@ +# S-ts-expr-1 — Computed keys, assertions, and multiline chains + +Rules exercised: 07 §3, E-7, TY-1a. + +## Program + +```rx +fn show(n: number): number => n +export default component App() { + record = { [key]: 4 } + key = "value" + value: unknown = record[key] + first = ([show(value as number)] + .map(n => n + 1))[0] +

{first}

+} +``` + +## Frames + +| instant | action | frame | +| --- | --- | --- | +| 0 | mount | `5` | From 706577855f469cc2ac785d664fb55fd6c22dbedf Mon Sep 17 00:00:00 2001 From: Dev Agrawal Date: Tue, 24 Nov 2026 20:27:34 -0600 Subject: [PATCH 04/34] Run the expression fixture in declaration order. --- scenarios/S-ts-expr-1.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scenarios/S-ts-expr-1.md b/scenarios/S-ts-expr-1.md index 7d538233..d94e6d75 100644 --- a/scenarios/S-ts-expr-1.md +++ b/scenarios/S-ts-expr-1.md @@ -7,8 +7,8 @@ Rules exercised: 07 §3, E-7, TY-1a. ```rx fn show(n: number): number => n export default component App() { - record = { [key]: 4 } key = "value" + record = { [key]: 4 } value: unknown = record[key] first = ([show(value as number)] .map(n => n + 1))[0] From 81aaa4a752205792d92766aef424e0558d4bedee Mon Sep 17 00:00:00 2001 From: Dev Agrawal Date: Tue, 24 Nov 2026 20:29:38 -0600 Subject: [PATCH 05/34] Report diagnostics across a recovering module graph. --- compiler/src/main.rs | 19 ++++++++++++++++--- spec/11-compiler.md | 6 +++++- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/compiler/src/main.rs b/compiler/src/main.rs index 02927ae3..f5fcb1a6 100644 --- a/compiler/src/main.rs +++ b/compiler/src/main.rs @@ -31,7 +31,7 @@ use reactivescript::check::check_modules; use reactivescript::emit::{compile_modules, compile_into, lower_view, Target}; use reactivescript::parse::parse_stmts; use reactivescript::project::{project_modules, unverified, PRELUDE}; -use reactivescript::modules::load_modules; +use reactivescript::modules::{load_modules, load_modules_recovering}; use reactivescript::serve; use reactivescript::signature::print_signature; use serde_json::{json, Map, Value}; @@ -322,7 +322,9 @@ fn main() { let as_json = cmd == "check" && args.iter().any(|a| a == "--json"); let mut found: Vec = vec![]; for f in args[1..].iter().filter(|a| !a.starts_with("--")) { - let set = match load_modules(&abs(f), &read_disk) { + let entry = abs(f); + let loaded = if cmd == "check" { load_modules_recovering(&entry, &read_disk) } else { load_modules(&entry, &read_disk) }; + let set = match loaded { Ok(s) => s, Err(e) => { bad += 1; @@ -334,8 +336,19 @@ fn main() { continue; } }; + for e in &set.parse_errors { + bad += 1; + if as_json { + found.push(parse_error_json(f, e)); + } else { + eprintln!("{}", parse_error_text(f, e)); + } + } let checked = check_modules(&set, spa); for d in &checked.diags { + // As in `rx-tsc`, a file with parse errors gets its parse diagnostics, + // not checker diagnostics from its partial tree. Still check other files. + if set.parse_errors.iter().any(|e| e.2 == d.file) { continue; } bad += 1; if as_json { found.push(serve::diagnostic_json(&set, d)); @@ -355,7 +368,7 @@ fn main() { }) .collect(); println!("{}", serde_json::to_string_pretty(&ms).unwrap()); - } else if checked.diags.is_empty() && !as_json { + } else if checked.diags.is_empty() && set.parse_errors.is_empty() && !as_json { println!("{}: ok", f); } } diff --git a/spec/11-compiler.md b/spec/11-compiler.md index ae8b5fb4..b66073e3 100644 --- a/spec/11-compiler.md +++ b/spec/11-compiler.md @@ -294,7 +294,11 @@ TY-1c), so every position has to cross between `.rx` and the projection. 0-based columns in UTF-16 code units (LSP's), and byte offsets. The checker is line-precise (CN-1a), so a diagnostic's range is its line's: from the first node that starts on it to the furthest any such node - reaches on it (decision 9). + reaches on it (decision 9). `rxc check` uses the recovering source + parse (CP-8e) and reports a batch across the module graph: a source + with parse errors reports those, while other sources report their + checker diagnostics. It does not run TypeScript; use `rx-tsc` for + the projection's type errors (TY-1a). - **CP-8e (the editor).** An editor's parse recovers: a declaration that does not parse is a parse error on its line and is skipped to the next line that starts at column 0, and a missing expression is an empty name, From 5ad54b36625a78a8bca73917575b9cf0271e4c5c Mon Sep 17 00:00:00 2001 From: Dev Agrawal Date: Tue, 24 Nov 2026 20:30:47 -0600 Subject: [PATCH 06/34] Type assertions parse in handlers, and a handler parse error stays on its line. `e as T` is TypeScript's assertion: erased where the program runs, kept in the projection. A statement-bodied arrow that fails to parse is no longer re-read as a record, which blamed the handler's `let` with JS_LOCAL. --- compiler/src/ast.rs | 4 ++++ compiler/src/emit.rs | 1 + compiler/src/parse.rs | 29 ++++++++++++++++++++++++----- compiler/src/project.rs | 1 + ref/compile/emit.ts | 1 + ref/src/ast.ts | 1 + ref/src/parse.ts | 18 ++++++++++++++---- ref/src/runtime.ts | 3 ++- ref/types/project.ts | 1 + scenarios/S-cast-1.md | 40 ++++++++++++++++++++++++++++++++++++++++ spec/07-surface.md | 1 + spec/13-types.md | 1 + 12 files changed, 91 insertions(+), 10 deletions(-) create mode 100644 scenarios/S-cast-1.md diff --git a/compiler/src/ast.rs b/compiler/src/ast.rs index e7c719e1..6a0fa8d8 100644 --- a/compiler/src/ast.rs +++ b/compiler/src/ast.rs @@ -100,6 +100,8 @@ pub enum ExprKind { Catch { e: Box, name: Option, classes: Option>, alt: Box }, /// 07 CSS-5 StyleMap { css: String, line: usize }, + /// 07 §3: `e as T` — a type assertion, erased at run time; the projection keeps it + As { e: Box, ty: String }, /// 12 SF-1d ServerFn { params: Vec, ptypes: Vec>, ret: Option, body: Vec }, } @@ -431,6 +433,7 @@ impl Expr { ExprKind::Throw(_) => "throw", ExprKind::Catch { .. } => "catch", ExprKind::StyleMap { .. } => "stylemap", + ExprKind::As { .. } => "as", ExprKind::ServerFn { .. } => "serverfn", } } @@ -478,6 +481,7 @@ impl Expr { ExprKind::Use(n) => obj(vec![("k", k), ("name", s(n))]), ExprKind::Catch { e, name, classes, alt } => obj(vec![("k", k), ("e", b(e)), ("name", os(name)), ("classes", classes.as_ref().map(|c| strs(c))), ("alt", b(alt))]), ExprKind::StyleMap { css, line } => obj(vec![("k", k), ("css", s(css)), ("line", num(*line))]), + ExprKind::As { e, ty } => obj(vec![("k", k), ("e", b(e)), ("type", s(ty))]), ExprKind::ServerFn { params, ptypes, ret, body } => obj(vec![("k", k), ("params", Some(strs(params))), ("ptypes", Some(ostrs(ptypes))), ("ret", os(ret)), ("body", Some(stmts_json(body)))]), } } diff --git a/compiler/src/emit.rs b/compiler/src/emit.rs index 0e71b279..ec049b1f 100644 --- a/compiler/src/emit.rs +++ b/compiler/src/emit.rs @@ -1451,6 +1451,7 @@ impl<'p> Gen<'p> { E::Index(Box::new(o), Box::new(self.expr(i, env, &sub)?), true) } // 07 CSS-5 + ExprKind::As { e, .. } => self.expr(e, env, ctx)?, // 07 §3: a type assertion, erased ExprKind::StyleMap { css, line } => self.class_map(css, *line)?, ExprKind::Call { f, args } => { // AC-6: Solid's until; the predicate is reactive scope diff --git a/compiler/src/parse.rs b/compiler/src/parse.rs index f83b7ccd..226e56ef 100644 --- a/compiler/src/parse.rs +++ b/compiler/src/parse.rs @@ -206,7 +206,7 @@ fn parse_type(c: &mut Cursor, brace_stops: bool, arrows: bool) -> R { continue; } let ch = c.peek(); - if depth == 0 && (c.starts_with("//") || c.starts_with("=>") || c.starts_with(":=") || ch == '=' || ch == ',' || ch == ')' || ch == ';' || ch == '\n' || (brace_stops && ch == '{')) { + if depth == 0 && (c.starts_with("//") || c.starts_with("=>") || c.starts_with(":=") || ch == '=' || ch == ',' || ch == ')' || ch == '}' || ch == ';' || ch == '\n' || (brace_stops && ch == '{')) { break; } if "([{<".contains(ch) { @@ -1551,12 +1551,22 @@ fn parse_expr_no_catch(c: &mut Cursor) -> R { c.ws(true); if c.peek() == '{' { let at = c.i; - if let Ok(stmts) = parse_block(c) { - if stmts.iter().any(|st| !matches!(&st.k, StmtKind::Expr(Expr { k: ExprKind::Id(_), .. }))) { - return Ok(ex(start, ExprKind::Fn { params, body: Box::new(Expr::made(ExprKind::Lit(Lit::Undefined))), stmts: Some(stmts) }, c)); + let stmt_err = match parse_block(c) { + Ok(stmts) => { + if stmts.iter().any(|st| !matches!(&st.k, StmtKind::Expr(Expr { k: ExprKind::Id(_), .. }))) { + return Ok(ex(start, ExprKind::Fn { params, body: Box::new(Expr::made(ExprKind::Lit(Lit::Undefined))), stmts: Some(stmts) }, c)); + } + None } - } + Err(e) => Some(e), + }; c.i = at; + // A handler is a statement body. If that reading fails and the record reading does too, report the + // statement error — the record reading fails at the first `let` and the hint then blames a local that is in a handler. + return match parse_expr(c) { + Ok(body) => Ok(ex(start, ExprKind::Fn { params, body: Box::new(body), stmts: None }, c)), + Err(e) => Err(stmt_err.unwrap_or(e)), + }; } let body = parse_expr(c)?; return Ok(ex(start, ExprKind::Fn { params, body: Box::new(body), stmts: None }, c)); @@ -1765,6 +1775,15 @@ fn parse_postfix(c: &mut Cursor) -> R { c.expect(")")?; e = Expr::new(ExprKind::Call { f: Box::new(e), args }, Span::new(start, c.i)); } else { + let save = c.i; + c.ws(false); // 07 §3: `e as T`, same line only (a newline is the next statement) + if c.keyword("as") { + c.ws(false); + let ty = parse_type(c, false, false)?; + e = Expr::new(ExprKind::As { e: Box::new(e), ty }, Span::new(start, c.i)); + continue; + } + c.i = save; return Ok(e); } } diff --git a/compiler/src/project.rs b/compiler/src/project.rs index 0bd33b64..f46e07d6 100644 --- a/compiler/src/project.rs +++ b/compiler/src/project.rs @@ -789,6 +789,7 @@ impl Proj<'_> { go!(o).t(if *opt { "?" } else { "" }).at(&dot, at) } ExprKind::Index { o, i, opt } => go!(o).t(if *opt { "?.[" } else { "[" }).c(go!(i)).t("]"), + ExprKind::As { e, ty } => Code::of("(").c(go!(e)).t(" as ").t(ty).t(")"), // 07 §3: the assertion is what TypeScript checks ExprKind::StyleMap { css, .. } => Code::of(&class_map(css)), ExprKind::Call { f, args } => { let fc = go!(f); diff --git a/ref/compile/emit.ts b/ref/compile/emit.ts index 8a8bdc42..d57aad5e 100644 --- a/ref/compile/emit.ts +++ b/ref/compile/emit.ts @@ -479,6 +479,7 @@ class Gen { return `__rt.${ctx.imp ? "tryCatch" : "catchRead"}(() => ${this.expr(e.e, env, sub)}, (__e) => __rt.isA(__e, ${this.classes(e.classes, env)}), (${e.name ? mg(e.name) : "__e"}) => ${this.expr(e.alt, inner, sub)})`; } case "tpl": return `(${e.parts.map(p => typeof p === "string" ? J(p) : `__rt.fmt(${go(p)})`).join(" + ") || '""'})`; + case "as": return go(e.e); // 07 §3: a type assertion, erased case "member": return `${go(e.o)}?.${e.p}`; case "index": return `${go(e.o)}?.[${go(e.i)}]`; case "stylemap": return this.classMap(e.css, e.line); // 07 CSS-5 diff --git a/ref/src/ast.ts b/ref/src/ast.ts index 6ca1a114..530e2a63 100644 --- a/ref/src/ast.ts +++ b/ref/src/ast.ts @@ -27,6 +27,7 @@ export type Expr = | { k: "throw"; e: Expr } // R-f-3: a failure; an expression in reactive scope too | { k: "catch"; e: Expr; name?: string; classes?: string[]; alt: Expr } | { k: "stylemap"; css: string; line?: number } // 07 CSS-5: `styles = ` — a class map, a constant + | { k: "as"; e: Expr; type: string } // 07 §3: `e as T` — a type assertion, erased at run time; the projection keeps it | { k: "serverfn"; params: string[]; ptypes?: (string | undefined)[]; ret?: string; body: Stmt[] }; // 12 SF-1d: `server fn (a) { … }`, an expression — for a wrapper (`GET(server fn …)`) // R-f-4: `e catch (x: A | B) => alt`; classes absent: every failure export type Target = { name: string; path: (string | Expr)[]; ctx?: boolean }; // ctx: `use name` — a provided source (RG-7, O-4) diff --git a/ref/src/parse.ts b/ref/src/parse.ts index a538ad2f..1242b123 100644 --- a/ref/src/parse.ts +++ b/ref/src/parse.ts @@ -84,7 +84,7 @@ class Cursor { } } -/** A TypeScript type, kept as text: balanced up to a depth-0 stop (`=`, `:=`, `,`, `)`, `=>`, `{` when `braceStops`). 07 §2. */ +/** A TypeScript type, kept as text: balanced up to a depth-0 stop (`=`, `:=`, `,`, `)`, `}`, `=>`, `{` when `braceStops`). 07 §2. `}` at depth 0 closes the block or JSX expression around an `as`. */ /** A type's text, up to where the declaration goes on. `=>` inside brackets is a function type, as it is anywhere in a * type alias (`arrows`); elsewhere at the top it starts a body (`fn f(): T => …`). */ function parseType(c: Cursor, braceStops = false, arrows = false): string { @@ -93,7 +93,7 @@ function parseType(c: Cursor, braceStops = false, arrows = false): string { const ch = c.peek(); if (c.startsWith("=>") && (depth > 0 || arrows)) { c.i += 2; continue; } if (depth === 0) { - if (c.startsWith("//") || c.startsWith("=>") || c.startsWith(":=") || ch === "=" || ch === "," || ch === ")" || ch === ";" || ch === "\n" || (braceStops && ch === "{")) break; + if (c.startsWith("//") || c.startsWith("=>") || c.startsWith(":=") || ch === "=" || ch === "," || ch === ")" || ch === "}" || ch === ";" || ch === "\n" || (braceStops && ch === "{")) break; } if (ch === "(" || ch === "[" || ch === "{" || ch === "<") depth++; else if (ch === ")" || ch === "]" || ch === "}" || ch === ">") depth--; @@ -495,8 +495,14 @@ function parseExprNoCatch(c: Cursor): Expr { c.expect("=>"); c.ws(); if (c.peek() === "{") { // `=> { … }`: a statement body (imperative scope) unless it reads as a record literal const at = c.i; - try { const stmts = parseBlock(c); if (stmts.some(st => !(st.k === "expr" && st.e.k === "id"))) return { k: "fn", params, body: { k: "lit", v: undefined }, stmts }; } catch (e) { if (!(e instanceof ParseError)) throw e; } + let stmtErr: ParseError | undefined; + try { const stmts = parseBlock(c); if (stmts.some(st => !(st.k === "expr" && st.e.k === "id"))) return { k: "fn", params, body: { k: "lit", v: undefined }, stmts }; } + catch (e) { if (!(e instanceof ParseError)) throw e; stmtErr = e; } c.i = at; + // A handler is a statement body. If that reading fails and the record reading does too, report the statement + // error — the record reading fails at the first `let` and the hint then blames a local that is in a handler. + try { return { k: "fn", params, body: parseExpr(c) }; } + catch (e) { if (stmtErr) throw stmtErr; throw e; } } return { k: "fn", params, body: parseExpr(c) }; } @@ -591,7 +597,11 @@ function parsePostfix(c: Cursor): Expr { c.i++; c.ws(); const args: Expr[] = []; while (!c.startsWith(")")) { args.push(parseExpr(c)); c.ws(); if (!c.eat(",")) break; c.ws(); } c.expect(")"); e = { k: "call", f: e, args }; - } else return e; + } else { + const save = c.i; c.ws(false); // 07 §3: `e as T`, same line only (a newline is the next statement) + if (c.keyword("as")) { c.ws(false); const type = parseType(c); e = { k: "as", e, type }; continue; } + c.i = save; return e; + } } } function parsePrimary(c: Cursor): Expr { diff --git a/ref/src/runtime.ts b/ref/src/runtime.ts index 111ba0d4..22131147 100644 --- a/ref/src/runtime.ts +++ b/ref/src/runtime.ts @@ -780,7 +780,7 @@ export class Runtime { private nodeOf(e: Expr, region: Region, env?: Map): Node | null { if (e.k === "id") { if (env?.has(e.name)) return null; const b = region.lookup(e.name); return b instanceof Node ? b : null; } if (e.k === "member" || e.k === "index") return this.nodeOf(e.o, region, env); - if (e.k === "latest") return this.nodeOf(e.e, region, env); + if (e.k === "latest" || e.k === "as") return this.nodeOf(e.e, region, env); return null; } private ev(e: Expr, region: Region, env?: Map): unknown { @@ -801,6 +801,7 @@ export class Runtime { if ("action" in b) { const a = b.action, home = b.home; return Object.assign((...args: unknown[]) => { const en = new Map(); if (env?.has("log")) en.set("log", env.get("log")); a.params.forEach((p, i) => en.set(p, args[i])); this.startRun(a.body, home, en, true); }, { io: true }); } // AC-1: an action is io; its body is lexical (its declaration's names) { const v = this.readNode(b); if (!this.demandMode && this.currentRun && v instanceof ErrVal) throw v.err; return v; } // R-f-7: a snapshot of an error throws it } + case "as": return this.ev(e.e, region, env); // 07 §3: erased case "member": { const v = this.ev(e.o, region, env); if (isAbsent(v)) return v; if (!isObj(v)) { if (e.opt || v == null) return undefined; return (v as any)?.[e.p]; } this.track(v, e.p); return v[e.p]; } case "index": { const i = this.ev(e.i, region, env); if (isAbsent(i)) return i; const v = this.ev(e.o, region, env); if (isAbsent(v)) return v; if (!isObj(v)) { if (e.opt || v == null) return undefined; return (v as any)?.[String(i)]; } this.track(v, String(i)); return v[String(i)]; } case "tpl": { let out = ""; for (const part of e.parts) { if (typeof part === "string") { out += part; continue; } const v = this.ev(part, region, env); if (isAbsent(v)) return v; out += fmt(v); } return out; } diff --git a/ref/types/project.ts b/ref/types/project.ts index bbe5106a..87591c8a 100644 --- a/ref/types/project.ts +++ b/ref/types/project.ts @@ -259,6 +259,7 @@ class Proj { case "throw": return `__.raise(${go(e.e)})`; case "catch": return `__.caught(${go(e.e)}, (${e.name ?? "__e"}: ${e.classes ? e.classes.join(" | ") : "Error"}) => ${go(e.alt)})`; case "tpl": return "`" + e.parts.map(p => typeof p === "string" ? p.replace(/[`\\]|\$\{/g, m => "\\" + m) : "${" + go(p) + "}").join("") + "`"; + case "as": return `(${go(e.e)} as ${e.type})`; // 07 §3: the assertion is what TypeScript checks case "member": return `${go(e.o)}${e.opt ? "?." : "."}${e.p}`; case "index": return `${go(e.o)}${e.opt ? "?.[" : "["}${go(e.i)}]`; case "stylemap": { const r = transform(`export const __s = ;`, { 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 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/spec/07-surface.md b/spec/07-surface.md index b1a53f99..9e65f2e9 100644 --- a/spec/07-surface.md +++ b/spec/07-surface.md @@ -127,6 +127,7 @@ Added: | `===` / `!==` | accepted as `==` / `!=` | E-6 | | `use name` | the nearest provision above (a unary form: `(use x) == y`) | RG-7 | | `type T = …` | a TS type declaration, kept as text | — | +| `e as T` | a type assertion, TypeScript's, erased at run time; the projection keeps it so the type layer checks it (13 TY-2). Same line as `e` — a newline is the next statement | TY-2 | | `throw e` | a failure, in either scope: `x > 0 ? x : throw BadInput(x)` (TC39's throw expression) | R-f-3 | | `await e catch (x: A \| B) => alt` | `alt` is the answer when the promise rejects with `A` or `B`; `catch (x) =>` takes every class; only after an `await` (`CATCH_NOT_ON_AWAIT`) | R-f-4 | diff --git a/spec/13-types.md b/spec/13-types.md index 6e07c688..8d28880b 100644 --- a/spec/13-types.md +++ b/spec/13-types.md @@ -40,6 +40,7 @@ does for `.tsrx`. Nothing here is a second type system. | `use c` / `provide c = e` | the context's type / `e` checked against it (RG-7) | | `error C(a: T) => …` | a class `C` (a subclass of `Error` with the field `a: T`), constructed by `C(a)` | | `fn`, `action`, `server fn` | functions of their parameters; an action and a server fn return a promise | +| `e as T` | `e` asserted as `T` (07 §3); erased where the program runs | | `if x { … }` | the branch narrows `x` (RG-1c); a handler is a closure that runs later, and TypeScript's rules for closures apply to it | | `for x in xs { … }` | `x` is an element of `xs` | From adf0cc87d3584a0a1800e9f6ee963f20b5bf5eb5 Mon Sep 17 00:00:00 2001 From: Dev Agrawal Date: Tue, 24 Nov 2026 20:33:38 -0600 Subject: [PATCH 07/34] Visit computed keys during expression analysis. --- ref/src/awaits.ts | 2 ++ ref/src/check.ts | 6 +++--- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/ref/src/awaits.ts b/ref/src/awaits.ts index 2f2d1ad8..48ce6ddb 100644 --- a/ref/src/awaits.ts +++ b/ref/src/awaits.ts @@ -14,6 +14,7 @@ export function nonTailAwaits(root: Expr, tail = true): Hoisted[] { const out: Hoisted[] = []; const walk = (x: Expr, tail: boolean, g: Guard[]): void => { switch (x.k) { + case "rec": for (const f of x.fields) { if ("computed" in f) walk(f.computed, false, g); walk("spread" in f ? f.spread : f.v, false, g); } return; case "await": if (!tail) out.push({ node: x, guards: g }); walk(x.e, false, g); if (x.init) walk(x.init, false, g); return; case "if": walk(x.c, false, g); walk(x.t, tail, [...g, { e: x.c }]); walk(x.f, tail, [...g, { e: x.c, neg: true }]); return; case "bin": @@ -61,6 +62,7 @@ export function innerCatches(root: Expr): HoistedCatch[] { const hasAwait = (x: unknown): boolean => { if (!x || typeof x !== "object") return false; if (Array.isArray(x)) return x.some(hasAwait); const o = x as Record; if (o.k === "fn") return false; if (o.k === "await" || o.k === "pre") return true; return Object.values(o).some(hasAwait); }; const walk = (x: Expr, root: boolean, g: Guard[]): void => { switch (x.k) { + case "rec": for (const f of x.fields) { if ("computed" in f) walk(f.computed, false, g); walk("spread" in f ? f.spread : f.v, false, g); } return; case "catch": if (root) { walk(x.e, false, g); walk(x.alt, false, g); } else if (!hasAwait(x)) out.push({ node: x, guards: g }); return; case "if": walk(x.c, false, g); walk(x.t, false, [...g, { e: x.c }]); walk(x.f, false, [...g, { e: x.c, neg: true }]); return; case "bin": diff --git a/ref/src/check.ts b/ref/src/check.ts index 3191a717..4f240b16 100644 --- a/ref/src/check.ts +++ b/ref/src/check.ts @@ -655,7 +655,7 @@ class Checker { case "id": { const s = env.lookup(x.name); if (s?.rows) for (const r of s.rows()) rows.add(r); return; } } for (const v of Object.values(x as object)) { - if (Array.isArray(v)) v.forEach(y => { if (y && typeof y === "object") { if ("k" in y) walk(y as Expr); else if ("v" in y) walk((y as { v: Expr }).v); else if ("spread" in y) walk((y as { spread: Expr }).spread); } }); + if (Array.isArray(v)) v.forEach(y => { if (y && typeof y === "object") { if ("computed" in y) walk((y as { computed: Expr }).computed); if ("k" in y) walk(y as Expr); else if ("v" in y) walk((y as { v: Expr }).v); else if ("spread" in y) walk((y as { spread: Expr }).spread); } }); else if (v && typeof v === "object" && "k" in (v as object)) walk(v as Expr); } }; @@ -1043,7 +1043,7 @@ class Checker { return; } for (const v of Object.values(x as object)) { - if (Array.isArray(v)) v.forEach(y => { if (y && typeof y === "object") { if ("k" in y) walk(y as Expr, res); else if ("v" in y) walk((y as { v: Expr }).v, res); else if ("spread" in y) walk((y as { spread: Expr }).spread, res); } }); + if (Array.isArray(v)) v.forEach(y => { if (y && typeof y === "object") { if ("computed" in y) walk((y as { computed: Expr }).computed, res); if ("k" in y) walk(y as Expr, res); else if ("v" in y) walk((y as { v: Expr }).v, res); else if ("spread" in y) walk((y as { spread: Expr }).spread, res); } }); else if (v && typeof v === "object" && "k" in (v as object)) walk(v as Expr, res); } }; @@ -1291,7 +1291,7 @@ class Checker { case "draft": { go(e.seed); for (const st of e.body) { if (st.k === "let" || st.k === "expr" || st.k === "write") go(st.e); } return out; } default: { for (const v of Object.values(e as object)) { - if (Array.isArray(v)) v.forEach(y => { if (typeof y === "string") return; if (y && typeof y === "object") { if ("k" in y) go(y as Expr); else if ("v" in y) go((y as { v: Expr }).v); else if ("spread" in y) go((y as { spread: Expr }).spread); } }); + if (Array.isArray(v)) v.forEach(y => { if (typeof y === "string") return; if (y && typeof y === "object") { if ("computed" in y) go((y as { computed: Expr }).computed); if ("k" in y) go(y as Expr); else if ("v" in y) go((y as { v: Expr }).v); else if ("spread" in y) go((y as { spread: Expr }).spread); } }); else if (v && typeof v === "object" && "k" in (v as object)) go(v as Expr); } return out; From 66e6758f575e73e21414a6364c2df77d889f1645 Mon Sep 17 00:00:00 2001 From: Dev Agrawal Date: Tue, 24 Nov 2026 20:33:38 -0600 Subject: [PATCH 08/34] Document foreign declaration type parameters and rows. --- guide/libraries.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/guide/libraries.md b/guide/libraries.md index 5cc39188..c5e0074a 100644 --- a/guide/libraries.md +++ b/guide/libraries.md @@ -23,6 +23,10 @@ export pure fn createEventListener(target: EventTarget, type: string, handler: ( only for a primitive with no `ref` on either side (one that registers a listener, or returns a store). - `pure fn` is right for a primitive: making it writes nothing but its own state. +A declaration can use type parameters (`export pure fn identity(value: T): T`) +and private type aliases. `rejects(Offline, Stopped)` and `rejects(Offline | Stopped)` +declare the same row. + Where the file goes: - **Your own JS module:** `./media.js` with `./media.d.rx` beside it. From 7c0e41b2c02ddf43499ee03ef5d5f43084512dc9 Mon Sep 17 00:00:00 2001 From: Dev Agrawal Date: Tue, 24 Nov 2026 20:39:00 -0600 Subject: [PATCH 09/34] A write checks the source's type, not the type a branch narrowed it to. `source open := false` is already a boolean. Inside `{if open}` the read is `true`, and `open := false` was checked against that. The projection keeps the slot's type and checks the write against it. --- compiler/src/project.rs | 30 +++++++++++++++++++++++++++--- ref/types/project.ts | 19 ++++++++++++++++--- scenarios/S-source-write-1.md | 27 +++++++++++++++++++++++++++ spec/13-types.md | 2 +- 4 files changed, 71 insertions(+), 7 deletions(-) create mode 100644 scenarios/S-source-write-1.md diff --git a/compiler/src/project.rs b/compiler/src/project.rs index f46e07d6..66c76658 100644 --- a/compiler/src/project.rs +++ b/compiler/src/project.rs @@ -179,7 +179,7 @@ pub fn project_modules_with(set: &ModuleSet, prelude: Option<&str>) -> Vec { used: IndexSet, /// names the module declares (they shadow the prelude) declared: HashSet, + /// sources and equations: a write checks this type, not a branch's narrowing (TY-2) + slots: HashSet, prelude: Option<&'a str>, } @@ -385,6 +387,9 @@ impl Proj<'_> { if let Some(n) = d.name() { self.declared.insert(n.to_string()); } + if matches!(d, Decl::Source { .. } | Decl::Eq { .. }) { + self.slots.insert(d.name().unwrap().to_string()); // before actions, whose writes name them + } } for d in ds { let sp = d.span(); @@ -496,12 +501,14 @@ impl Proj<'_> { None => Code::of("__.src(").c(self.expr(init, false, None)).t(")"), }; self.w.emit(Code::of(ind).t(ex(d)).t("const ").c(nm).c(a).t(" = ").c(v).t(";").from(sp), *line); + self.w.emit(Code::of(&format!("{ind}type __W_{name} = typeof {name};")), *line); } Decl::Eq { name, e, line, ty, .. } => { let nm = self.name(name, sp, &mut at); let a = self.ann(ty, sp, &mut at); let v = Code::of("__.eq(").c(self.expr(e, false, Some(name))).t(", true)"); // R-1: no promise without `await` self.w.emit(Code::of(ind).t(ex(d)).t("const ").c(nm).c(a).t(" = ").c(v).t(";").from(sp), *line); + self.w.emit(Code::of(&format!("{ind}type __W_{name} = typeof {name};")), *line); } Decl::Provide { name, e, line, .. } => { let nm = self.name(name, sp, &mut at); @@ -658,9 +665,26 @@ impl Proj<'_> { self.w.emit(Code::of(&format!("{ind}throw ")).c(v).t(";").from(sp), 0); } StmtKind::Write { target, e } | StmtKind::Optimistic { target, e } => { - let t = self.target(target, sp, &mut at); let v = self.expr(e, true, None); - self.w.emit(Code::of(&format!("{ind}__.set(")).c(t).t(")(").c(v).t(");").from(sp), 0); + // TY-2: a write is checked against the slot's type, not the type a branch has narrowed the read to. + if !target.is_ctx() && self.slots.contains(&target.name) { + let mut path = String::new(); + for p in &target.path { + match p { + PathSeg::Name(n) => path.push_str(&format!(".{n}")), + PathSeg::Expr(x) => path.push_str(&format!("[{}]", self.expr(x, true, None).s)), + } + } + let base = if target.path.is_empty() { + format!("({} as __W_{})", target.name, target.name) + } else { + format!("({} as NonNullable<__W_{}>)", target.name, target.name) + }; + self.w.emit(Code::of(&format!("{ind}__.set({base}{path})(")).c(v).t(");").from(sp), 0); + } else { + let t = self.target(target, sp, &mut at); + self.w.emit(Code::of(&format!("{ind}__.set(")).c(t).t(")(").c(v).t(");").from(sp), 0); + } } StmtKind::Refresh(n) | StmtKind::Affects(n) => { let nm = self.name(n, sp, &mut at); diff --git a/ref/types/project.ts b/ref/types/project.ts index 87591c8a..5b5cce06 100644 --- a/ref/types/project.ts +++ b/ref/types/project.ts @@ -121,6 +121,7 @@ class Proj { w: W; set: ModuleSet; path: string; jsStubs: Map>; private used = new Set(); // prelude names the module reads private declared = new Set(); // names the module declares (they shadow the prelude) + private slots = new Set(); // sources and equations: a write checks this type, not a branch's narrowing (TY-2) constructor(w: W, set: ModuleSet, path: string, jsStubs: Map>) { this.w = w; this.set = set; this.path = path; this.jsStubs = jsStubs; } module(p: Program) { @@ -142,6 +143,7 @@ class Proj { decls(ds: Decl[], ind: string, top = false) { const ex = (d: Decl) => top && (d as { exported?: boolean }).exported ? "export " : ""; for (const d of ds) if ("name" in d) this.declared.add(d.name); + for (const d of ds) if (d.k === "source" || d.k === "eq") this.slots.add(d.name); // before actions, whose writes name them for (const d of ds) { if (d.k === "import") this.importDecl(d, ind); if (d.k === "typedecl") this.w.emit(`${ind}${ex(d)}${d.text ?? `type ${d.name} = any;`}`, d.line); @@ -170,8 +172,8 @@ class Proj { } } for (const d of this.order(ds)) { - if (d.k === "source") this.w.emit(`${ind}${ex(d)}const ${d.name}${ann(d.type)} = ${typeText(d.type) ? `__.typed<${typeText(d.type)}>(${this.expr(d.init, false)})` : `__.src(${this.expr(d.init, false)})`};`, d.line); - if (d.k === "eq") this.w.emit(`${ind}${ex(d)}const ${d.name}${ann(d.type)} = __.eq(${this.expr(d.e, false, d.name)}, true);`, d.line); // R-1: no promise without `await` + if (d.k === "source") { this.w.emit(`${ind}${ex(d)}const ${d.name}${ann(d.type)} = ${typeText(d.type) ? `__.typed<${typeText(d.type)}>(${this.expr(d.init, false)})` : `__.src(${this.expr(d.init, false)})`};`, d.line); this.w.emit(`${ind}type __W_${d.name} = typeof ${d.name};`, d.line); } + if (d.k === "eq") { this.w.emit(`${ind}${ex(d)}const ${d.name}${ann(d.type)} = __.eq(${this.expr(d.e, false, d.name)}, true);`, d.line); this.w.emit(`${ind}type __W_${d.name} = typeof ${d.name};`, d.line); } // R-1: no promise without `await` if (d.k === "provide") this.w.emit(`${ind}__.provide(${d.name}, ${this.expr(d.e, false)});`, d.line); } for (const d of ds) if (d.k === "effect") { @@ -222,7 +224,7 @@ class Proj { case "expr": this.w.emit(`${ind}${e(s.e)};`, 0); break; case "return": this.w.emit(`${ind}return${s.e ? " " + e(s.e) : ""};`, 0); break; case "throw": this.w.emit(`${ind}throw ${e(s.e)};`, 0); break; - case "write": case "optimistic": this.w.emit(`${ind}__.set(${this.target(s.target)})(${e(s.e)});`, 0); break; + case "write": case "optimistic": this.write(s.target, e(s.e), ind); break; case "refresh": case "affects": this.w.emit(`${ind}void ${s.name};`, 0); break; case "action": this.w.emit(`${ind}void (async () => {`, 0); this.stmts(s.body, ind + " "); this.w.emit(`${ind}})();`, 0); break; case "sif": this.w.emit(`${ind}if (${e(s.c)}) {`, 0); this.stmts(s.t, ind + " "); this.w.emit(`${ind}} else {`, 0); this.stmts(s.f, ind + " "); this.w.emit(`${ind}}`, 0); break; @@ -235,6 +237,17 @@ class Proj { } } } + /** TY-2: a write is checked against the slot's type, not the type a branch has narrowed the read to. */ + private write(t: Target, v: string, ind: string) { + if (!t.ctx && this.slots.has(t.name)) { + let path = ""; + for (const p of t.path) path += typeof p === "string" ? `.${p}` : `[${this.expr(p, true)}]`; + const base = t.path.length ? `(${t.name} as NonNullable<__W_${t.name}>)` : `(${t.name} as __W_${t.name})`; + this.w.emit(`${ind}__.set(${base}${path})(${v});`, 0); + return; + } + this.w.emit(`${ind}__.set(${this.target(t)})(${v});`, 0); + } private target(t: Target): string { let s = t.ctx ? `__.use(${t.name})` : t.name; for (const p of t.path) s += typeof p === "string" ? `.${p}` : `[${this.expr(p, true)}]`; 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/spec/13-types.md b/spec/13-types.md index 8d28880b..83e3e632 100644 --- a/spec/13-types.md +++ b/spec/13-types.md @@ -33,7 +33,7 @@ does for `.tsrx`. Nothing here is a second type system. | --- | --- | | `x = e` (an equation) | a `const` of `e`'s type; with `x: T = e`, of `T` (row words such as `pending` are not types, CN-4a) | | `source x := e`, `source x = e` | with a written type, that type — not what the initializer narrows it to; without one, the initializer's type widened: a literal to its primitive, `null`, `undefined` and `[]` to `any` (they say nothing about later writes) | -| `x := v`, `x.a := v` | `v` (or a function of the slot, W-6) checked against the target's type | +| `x := v`, `x.a := v` | `v` (or a function of the slot, W-6) checked against the target's type — the source's or equation's, not the type a branch has narrowed a read of it to (`{if open { open := false }}` is a boolean write) | | `await e` | the answer's type (`Awaited`); `await* e` the stream's element type; `-> v` adds `v`'s type | | `e catch (x: A \| B) => alt` | `e`'s type or `alt`'s; `x` is `A \| B` (untyped: `Error`) | | `pre x -> i`, `latest e`, `peek e` | the node's own type; `pending? e` is `boolean` | From 3f7da8d676fbbe9812ffa42ae53e72904f9a8393 Mon Sep 17 00:00:00 2001 From: Dev Agrawal Date: Tue, 24 Nov 2026 20:48:37 -0600 Subject: [PATCH 10/34] A .d.rx is the type of its JS module, even when a .ts sits beside it. The projection checks the import against the declaration, so a ref parameter or result is that type and not the accessor the implementation is written with. The compiled import is unchanged. --- compiler/src/project.rs | 58 +++++++++++++++++++++++++- ref/types/project.ts | 25 +++++++++++ spec/13-types.md | 5 ++- tooling/rx-language-server/test/tsc.js | 10 +++++ 4 files changed, 96 insertions(+), 2 deletions(-) diff --git a/compiler/src/project.rs b/compiler/src/project.rs index 66c76658..7f07fb86 100644 --- a/compiler/src/project.rs +++ b/compiler/src/project.rs @@ -156,6 +156,14 @@ fn j(l: &Lit) -> String { fn js_str(s: &str) -> String { serde_json::to_string(s).unwrap() } +/// The namespace a `.d.rx` is declared as. Same spelling as `ref/types/project.ts`. +fn ns_name(declared: &str) -> String { + let mut s = String::from("__D_"); + for c in declared.chars() { + s.push(if c.is_ascii_alphanumeric() || c == '_' { c } else { '_' }); + } + s +} fn is_handler(a: &str) -> bool { crate::awaits::is_handler(a) } @@ -179,7 +187,7 @@ pub fn project_modules_with(set: &ModuleSet, prelude: Option<&str>) -> Vec { declared: HashSet, /// sources and equations: a write checks this type, not a branch's narrowing (TY-2) slots: HashSet, + /// a JS module's `.d.rx`, emitted once as the types the import is checked against (TY-4b) + ambients: HashSet, prelude: Option<&'a str>, } @@ -557,6 +567,13 @@ impl Proj<'_> { s.insert(n.name.clone()); } } + if let Some(dts) = declared { + if let Some(decls) = self.set.declarations.get(dts) { + // TY-4b: the `.d.rx` is the type, even where a `.ts` sits beside it + self.declared_import(d, &rest, decls, ind); + return; + } + } let mut at = sp.start as usize; let def = rest.iter().find(|n| n.name == "default").map(|n| self.name(&n.alias, sp, &mut at)); let parts: Vec = rest @@ -584,6 +601,45 @@ impl Proj<'_> { c = c.t(" from ").at(&q, fa).t(";"); self.w.emit(c, *line); } + /// TY-4b: check the import against its `.d.rx`, not whatever TypeScript would resolve the JS module to. + fn declared_import(&mut self, d: &Decl, rest: &[&ImportName], decls: &[JsDecl], ind: &str) { + let Decl::Import { from, line, declared, .. } = d else { return }; + // a declare namespace, not a module: nothing for TypeScript to resolve beside the `.ts` + let ns = ns_name(declared.as_deref().unwrap_or(from)); + if declared.as_ref().is_some_and(|p| self.ambients.insert(p.clone())) { + let body = declaration_file(decls).trim_end().replace("export declare ", "export ").lines().map(|l| format!(" {l}")).collect::>().join("\n"); + self.w.emit(Code::of(&format!("{ind}declare namespace {ns} {{\n{body}\n{ind}}}")), *line); + } + let of = |n: &str| decls.iter().find(|x| x.name() == n); + let values: Vec<&&ImportName> = rest.iter().filter(|n| !matches!(of(&n.name), Some(JsDecl::Type { .. }))).collect(); + if !values.is_empty() { + let def = values.iter().find(|n| n.name == "default"); + let parts: Vec = values.iter().filter(|n| n.name != "default").map(|n| format!("{} as __js_{}", n.name, n.alias)).collect(); + let mut s = format!("{ind}import "); + if let Some(def) = def { + s.push_str(&format!("__js_{}", def.alias)); + if !parts.is_empty() { + s.push_str(", "); + } + } + if !parts.is_empty() { + s.push_str(&format!("{{ {} }}", parts.join(", "))); + } + s.push_str(&format!(" from {};", js_str(from))); + self.w.emit(Code::of(&s), *line); + } + for n in rest { + let x = of(&n.name); + if x.is_none() || matches!(x, Some(JsDecl::Type { .. })) { + self.w.emit(Code::of(&format!("{ind}type {} = {ns}.{};", n.alias, n.name)), *line); + } else { + self.w.emit(Code::of(&format!("{ind}const {} = __js_{} as typeof {ns}.{};", n.alias, n.alias, n.name)), *line); + } + if matches!(x, Some(JsDecl::Error { .. })) { + self.w.emit(Code::of(&format!("{ind}type {} = {ns}.{};", n.alias, n.name)), *line); + } + } + } /// A JS import's module, from the program's root (where the stubs are written). fn mod_path(&self, from: &str) -> String { let mut parts: Vec<&str> = self.path.split('/').collect(); diff --git a/ref/types/project.ts b/ref/types/project.ts index 5b5cce06..2eea5ccd 100644 --- a/ref/types/project.ts +++ b/ref/types/project.ts @@ -122,6 +122,7 @@ class Proj { private used = new Set(); // prelude names the module reads private declared = new Set(); // names the module declares (they shadow the prelude) private slots = new Set(); // sources and equations: a write checks this type, not a branch's narrowing (TY-2) + private ambients = new Set(); // a JS module's `.d.rx`, emitted once as the types the import is checked against (TY-4b) constructor(w: W, set: ModuleSet, path: string, jsStubs: Map>) { this.w = w; this.set = set; this.path = path; this.jsStubs = jsStubs; } module(p: Program) { @@ -195,10 +196,34 @@ class Proj { const key = this.modPath(d.from) + ".ts"; let s = this.jsStubs.get(key); if (!s) this.jsStubs.set(key, (s = new Set())); for (const n of rest) s.add(n.name); from = d.from; } void names; void dflt; + const decls = d.declared ? this.set.declarations?.get(d.declared) : undefined; + if (decls) { this.declaredImport(d, rest, decls, ind); return; } // TY-4b: the `.d.rx` is the type, even where a `.ts` sits beside it const parts = rest.filter(n => n.name !== "default").map(n => n.name === n.alias ? n.name : `${n.name} as ${n.alias}`); const def = rest.find(n => n.name === "default")?.alias; this.w.emit(`${ind}import ${def ? def + (parts.length ? ", " : "") : ""}${parts.length ? `{ ${parts.join(", ")} }` : ""} from "${from}";`, d.line); } + /** TY-4b: check the import against its `.d.rx`, not whatever TypeScript would resolve the JS module to. */ + private declaredImport(d: Extract, rest: { name: string; alias: string }[], decls: JsDecl[], ind: string) { + const ns = "__D_" + d.declared!.replace(/[^A-Za-z0-9_]/g, "_"); // a declare namespace, not a module: nothing for TypeScript to resolve beside the `.ts` + if (!this.ambients.has(d.declared!)) { + this.ambients.add(d.declared!); + const body = declarationFile(decls).trimEnd().replace(/export declare /g, "export ").split("\n").map(l => ` ${l}`).join("\n"); + this.w.emit(`${ind}declare namespace ${ns} {\n${body}\n${ind}}`, d.line); + } + const of = (n: string) => decls.find(x => x.name === n); + const values = rest.filter(n => of(n.name)?.kind !== "type"); + if (values.length) { + const parts = values.filter(n => n.name !== "default").map(n => `${n.name} as __js_${n.alias}`); + const def = values.find(n => n.name === "default"); + this.w.emit(`${ind}import ${def ? `__js_${def.alias}` + (parts.length ? ", " : "") : ""}${parts.length ? `{ ${parts.join(", ")} }` : ""} from ${J(d.from)};`, d.line); + } + for (const n of rest) { + const x = of(n.name); + if (!x || x.kind === "type") this.w.emit(`${ind}type ${n.alias} = ${ns}.${n.name};`, d.line); + else this.w.emit(`${ind}const ${n.alias} = __js_${n.alias} as typeof ${ns}.${n.name};`, d.line); + if (x?.kind === "error") this.w.emit(`${ind}type ${n.alias} = ${ns}.${n.name};`, d.line); + } + } /** A JS import's module, from the program's root (where the stubs are written). */ private modPath(from: string) { const base = this.path.split("/").slice(0, -1); const parts = [...base]; for (const seg of from.split("/")) { if (seg === "." || !seg) continue; if (seg === "..") parts.pop(); else parts.push(seg); } return parts.join("/"); } /** E-7: values in dependency order (C-1 makes it a DAG; a `pre` reads the previous instant, so it is no edge). */ diff --git a/spec/13-types.md b/spec/13-types.md index 83e3e632..c02e6909 100644 --- a/spec/13-types.md +++ b/spec/13-types.md @@ -64,7 +64,10 @@ does for `.tsrx`. Nothing here is a second type system. - **TY-4b.** A `.d.rx` is its JS module's `.d.ts`: each function's parameter types and return type (`export pure fn f(id: number): Promise`), its `export type`s, and its error classes (MO-8). A JS module with no - declaration file is `any`. + declaration file is `any`. Where a `.ts` (or `.js`) sits beside the + `.d.rx`, the type layer still checks the import against the `.d.rx`: + a `ref` parameter or result is that type, not the accessor the `.ts` + implementation is written with. The compiled import is unchanged (MO-8c). - **TY-4c.** An `.rx` module read by its `.d.rx` (09 MO-9) is typed by the `.d.ts` TypeScript emits from that module's projection (TY-1c), shipped beside it: the `.d.rx` carries rows, the `.d.ts` types. `ref/` has no such diff --git a/tooling/rx-language-server/test/tsc.js b/tooling/rx-language-server/test/tsc.js index 532302db..58342985 100644 --- a/tooling/rx-language-server/test/tsc.js +++ b/tooling/rx-language-server/test/tsc.js @@ -82,5 +82,15 @@ const decl = run( ); check("a .d.rx in include passes", decl.status === 0 && decl.out.trim() === "", decl); +// TY-4b: the sibling .ts is what the bundler runs; the .d.rx is what .rx is checked against. +// createHash's implementation returns Accessor; .d.rx says `ref string`, which .rx reads as string. +const refWin = run( + { include: ["."] }, + { file: "hash.d.rx", text: () => "export pure fn createHash(): ref string\nexport pure fn createDebounced(ref source: string, ms: number): ref string\n" }, + { file: "hash.ts", text: () => "import { type Accessor, createSignal } from 'solid-js';\nexport function createHash(): Accessor { return createSignal('')[0]; }\nexport function createDebounced(source: Accessor, _ms: number): Accessor { return source; }\n" }, + { file: "main.rx", text: () => 'import pure { createHash, createDebounced } from "./hash"\nexport default component App() {\n source q := ""\n h = createHash().trim()\n d = createDebounced(q, 10)\n

{h}{d}

\n}\n' }, +); +check("a .d.rx wins over the sibling .ts (ref is string, not Accessor)", refWin.status === 0 && refWin.out.trim() === "", refWin); + console.log(`\n${pass} passed, ${fail} failed`); process.exit(fail ? 1 : 0); From f4667d724988b9c8d5ef8668cdf51b7dd581e367 Mon Sep 17 00:00:00 2001 From: Dev Agrawal Date: Tue, 24 Nov 2026 21:01:05 -0600 Subject: [PATCH 11/34] A handler reads a snapshot, so a view branch does not narrow it. The read happens when the handler runs, and the branch may no longer hold. Snapshot into a local and narrow that. A check inside the handler still narrows its own snapshot. --- compiler/src/project.rs | 121 +++++++++++++++++++++++++++++--- guide/diagnostics.md | 20 ++++++ ref/types/project.ts | 61 ++++++++++++++-- scenarios/S-handler-narrow-1.md | 48 +++++++++++++ spec/13-types.md | 2 +- 5 files changed, 237 insertions(+), 15 deletions(-) create mode 100644 scenarios/S-handler-narrow-1.md diff --git a/compiler/src/project.rs b/compiler/src/project.rs index 7f07fb86..370f7fd7 100644 --- a/compiler/src/project.rs +++ b/compiler/src/project.rs @@ -10,7 +10,7 @@ use crate::signature::{ExportSig, ModSig}; use indexmap::{IndexMap, IndexSet}; use regex::Regex; use serde_json::Value; -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::sync::LazyLock; /// The helpers every projection imports (`__`), and the prelude's names (`len`, `map`, …): `ref/types/project.ts`'s PRELUDE. @@ -187,7 +187,7 @@ pub fn project_modules_with(set: &ModuleSet, prelude: Option<&str>) -> Vec { declared: HashSet, /// sources and equations: a write checks this type, not a branch's narrowing (TY-2) slots: HashSet, + /// a handler read is a fresh snapshot of this name's type (TY-2) + snap: HashSet, + /// inside a handler, a snap name reads as its snapshot binding + rename: HashMap, /// a JS module's `.d.rx`, emitted once as the types the import is checked against (TY-4b) ambients: HashSet, prelude: Option<&'a str>, @@ -398,7 +402,9 @@ impl Proj<'_> { self.declared.insert(n.to_string()); } if matches!(d, Decl::Source { .. } | Decl::Eq { .. }) { - self.slots.insert(d.name().unwrap().to_string()); // before actions, whose writes name them + let n = d.name().unwrap().to_string(); + self.slots.insert(n.clone()); // before actions, whose writes name them + self.snap.insert(n); } } for d in ds { @@ -600,6 +606,79 @@ impl Proj<'_> { let fa = self.find(&q[1..q.len() - 1], sp, at).map(|a| a - 1).filter(|a| self.src[*a..].starts_with(&q)); c = c.t(" from ").at(&q, fa).t(";"); self.w.emit(c, *line); + for n in &rest { + if !self.is_type_import(d, &n.name) { + self.snap_alias(&n.alias, ind, *line); + } + } + } + fn is_type_import(&self, d: &Decl, name: &str) -> bool { + let Decl::Import { resolved: Some(r), .. } = d else { return false }; + if self.set.programs.get(r).is_some_and(|p| p.decls.iter().any(|x| matches!(x, Decl::TypeDecl { name: n, .. } if n == name))) { + return true; + } + self.set.signatures.get(r).and_then(|s| s.exports.get(name)).is_some_and(|x| matches!(x, ExportSig::Type)) + } + /// Snap names a handler reads, not counting its parameters, its locals, or a nested arrow. Sorted, so both projections agree. + fn handler_snaps(&self, params: &[String], body: &Expr, stmts: Option<&[Stmt]>) -> Vec { + let mut bound: HashSet = params.iter().cloned().collect(); + let mut out = HashSet::new(); + fn expr(e: &Expr, snap: &HashSet, bound: &HashSet, out: &mut HashSet) { + match &e.k { + ExprKind::Fn { .. } | ExprKind::ServerFn { .. } | ExprKind::Draft { .. } => {} + ExprKind::Id(n) => { + if snap.contains(n) && !bound.contains(n) { + out.insert(n.clone()); + } + } + ExprKind::Bin { l, r, .. } => { expr(l, snap, bound, out); expr(r, snap, bound, out); } + ExprKind::Un { e, .. } | ExprKind::Peek(e) | ExprKind::Latest(e) | ExprKind::Pending(e) | ExprKind::Spread(e) | ExprKind::Throw(e) | ExprKind::As { e, .. } => expr(e, snap, bound, out), + ExprKind::Pre { init, .. } => init.iter().for_each(|x| expr(x, snap, bound, out)), + ExprKind::Await { e, init, .. } => { expr(e, snap, bound, out); init.iter().for_each(|x| expr(x, snap, bound, out)); } + ExprKind::If { c, t, f } => { expr(c, snap, bound, out); expr(t, snap, bound, out); expr(f, snap, bound, out); } + ExprKind::Member { o, .. } => expr(o, snap, bound, out), + ExprKind::Index { o, i, .. } => { expr(o, snap, bound, out); expr(i, snap, bound, out); } + ExprKind::Call { f, args } => { expr(f, snap, bound, out); args.iter().for_each(|a| expr(a, snap, bound, out)); } + ExprKind::Arr(items) => items.iter().for_each(|a| expr(a, snap, bound, out)), + ExprKind::Rec(fields) => fields.iter().for_each(|f| match f { Field::Kv { v, .. } => expr(v, snap, bound, out), Field::Spread(x) => expr(x, snap, bound, out) }), + ExprKind::Tpl(parts) => parts.iter().for_each(|p| if let TplPart::Expr(x) = p { expr(x, snap, bound, out) }), + ExprKind::Catch { e, alt, .. } => { expr(e, snap, bound, out); expr(alt, snap, bound, out); } + ExprKind::Omit { e, .. } => expr(e, snap, bound, out), + _ => {} + } + } + fn walk_stmts(ss: &[Stmt], snap: &HashSet, bound: &mut HashSet, out: &mut HashSet) { + for s in ss { + match &s.k { + StmtKind::Let { name, e, .. } => { expr(e, snap, bound, out); bound.insert(name.clone()); } + StmtKind::Write { target, e } | StmtKind::Optimistic { target, e } => { + for p in &target.path { + if let PathSeg::Expr(x) = p { expr(x, snap, bound, out); } + } + expr(e, snap, bound, out); + } + StmtKind::Expr(e) | StmtKind::Throw(e) => expr(e, snap, bound, out), + StmtKind::Return(Some(e)) => expr(e, snap, bound, out), + StmtKind::Sif { c, t, f } => { expr(c, snap, bound, out); walk_stmts(t, snap, bound, out); walk_stmts(f, snap, bound, out); } + StmtKind::Try { body, handler, fin, .. } => { + walk_stmts(body, snap, bound, out); + if let Some(h) = handler { walk_stmts(h, snap, bound, out); } + if let Some(h) = fin { walk_stmts(h, snap, bound, out); } + } + StmtKind::Action(body) => walk_stmts(body, snap, bound, out), + _ => {} + } + } + } + if let Some(ss) = stmts { walk_stmts(ss, &self.snap, &mut bound, &mut out); } else { expr(body, &self.snap, &bound, &mut out); } + let mut v: Vec = out.into_iter().collect(); + v.sort(); + v + } + /// A handler's read of this name is a snapshot of its type, not a branch's narrowing (TY-2). + fn snap_alias(&mut self, alias: &str, ind: &str, line: usize) { + self.snap.insert(alias.to_string()); + self.w.emit(Code::of(&format!("{ind}type __W_{alias} = typeof {alias};")), line); } /// TY-4b: check the import against its `.d.rx`, not whatever TypeScript would resolve the JS module to. fn declared_import(&mut self, d: &Decl, rest: &[&ImportName], decls: &[JsDecl], ind: &str) { @@ -634,6 +713,7 @@ impl Proj<'_> { self.w.emit(Code::of(&format!("{ind}type {} = {ns}.{};", n.alias, n.name)), *line); } else { self.w.emit(Code::of(&format!("{ind}const {} = __js_{} as typeof {ns}.{};", n.alias, n.alias, n.name)), *line); + self.snap_alias(&n.alias, ind, *line); } if matches!(x, Some(JsDecl::Error { .. })) { self.w.emit(Code::of(&format!("{ind}type {} = {ns}.{};", n.alias, n.name)), *line); @@ -817,7 +897,10 @@ impl Proj<'_> { self.used.insert(n.clone()); } let at = src_at(n); - Code::new().at(n, at) + match self.rename.get(n) { + Some(r) => Code::of(r), + None => Code::new().at(n, at), + } } ExprKind::Pre { name, init } => { let mut from = sp.start as usize; @@ -899,11 +982,33 @@ impl Proj<'_> { ExprKind::Fn { params, body, stmts } => { let mut from = sp.start as usize; let ps = Code::join(params.iter().map(|p| self.name(p, sp, &mut from)).collect(), ", "); - let Some(ss) = stmts else { - return Code::of("((").c(ps).t(") => ").c(self.expr(body, imp, me)).t(")"); + let names = if imp { self.handler_snaps(params, body, stmts.as_deref()) } else { vec![] }; + let saved = self.rename.clone(); + if !names.is_empty() { + for n in &names { + self.rename.insert(n.clone(), format!("__s_{n}")); + } + } + let (inner, is_stmt, is_async) = if let Some(ss) = stmts { + (self.nested(|me| me.stmts(ss, " ")), true, has_await(ss)) + } else { + (self.expr(body, imp, me), false, false) }; - let inner = self.nested(|me| me.stmts(ss, " ")); - Code::of(if has_await(ss) { "(async (" } else { "((" }).c(ps).t(") => {\n").c(inner).t("\n})") + self.rename = saved; + if names.is_empty() { + return if is_stmt { + Code::of(if is_async { "(async (" } else { "((" }).c(ps).t(") => {\n").c(inner).t("\n})") + } else { + Code::of("((").c(ps).t(") => ").c(inner).t(")") + }; + } + let params_s = names.iter().map(|n| format!("__s_{n}: __W_{n}")).collect::>().join(", "); + let args = names.join(", "); + if is_stmt { + Code::of("((").c(ps).t(&format!(") => (({params_s}) => {{\n")).c(inner).t(&format!("\n}})({args}))")) + } else { + Code::of("((").c(ps).t(&format!(") => (({params_s}) => ")).c(inner).t(&format!(")({args}))")) + } } ExprKind::ServerFn { params, ptypes, ret, body } => { let mut from = sp.start as usize; diff --git a/guide/diagnostics.md b/guide/diagnostics.md index f2ddad76..f209a848 100644 --- a/guide/diagnostics.md +++ b/guide/diagnostics.md @@ -1253,6 +1253,26 @@ export default component App() { These come from the TypeScript layer, which checks the program's projection (13). +### A handler read is a snapshot + +`{if detail != null { … }}` narrows `detail` for a read in that branch. A handler +inside the branch runs later, and its read is a snapshot taken then — the +branch may no longer hold — so `detail` is still `Item | null` there +(`Object is possibly 'null'`). Snapshot it and narrow the local: + +```rx +{if detail != null { + +}} +``` + +`{detail.id}` is narrowed: that read is re-checked while the branch is live. +`d` is a local, so the `if` inside the handler sticks. + ### MISSING_AWAIT An equation's value is a promise or a stream, which Solid would consume as a value (R-1a, TY-5b). Write `await e`, or diff --git a/ref/types/project.ts b/ref/types/project.ts index 2eea5ccd..0ae6a67a 100644 --- a/ref/types/project.ts +++ b/ref/types/project.ts @@ -122,6 +122,8 @@ class Proj { private used = new Set(); // prelude names the module reads private declared = new Set(); // names the module declares (they shadow the prelude) private slots = new Set(); // sources and equations: a write checks this type, not a branch's narrowing (TY-2) + private snap = new Set(); // a handler read is a fresh snapshot of this name's type (TY-2) + private rename: Map | null = null; // inside a handler, a snap name reads as its snapshot binding private ambients = new Set(); // a JS module's `.d.rx`, emitted once as the types the import is checked against (TY-4b) constructor(w: W, set: ModuleSet, path: string, jsStubs: Map>) { this.w = w; this.set = set; this.path = path; this.jsStubs = jsStubs; } @@ -144,7 +146,7 @@ class Proj { decls(ds: Decl[], ind: string, top = false) { const ex = (d: Decl) => top && (d as { exported?: boolean }).exported ? "export " : ""; for (const d of ds) if ("name" in d) this.declared.add(d.name); - for (const d of ds) if (d.k === "source" || d.k === "eq") this.slots.add(d.name); // before actions, whose writes name them + for (const d of ds) if (d.k === "source" || d.k === "eq") { this.slots.add(d.name); this.snap.add(d.name); } // before actions, whose writes name them for (const d of ds) { if (d.k === "import") this.importDecl(d, ind); if (d.k === "typedecl") this.w.emit(`${ind}${ex(d)}${d.text ?? `type ${d.name} = any;`}`, d.line); @@ -201,6 +203,45 @@ class Proj { const parts = rest.filter(n => n.name !== "default").map(n => n.name === n.alias ? n.name : `${n.name} as ${n.alias}`); const def = rest.find(n => n.name === "default")?.alias; this.w.emit(`${ind}import ${def ? def + (parts.length ? ", " : "") : ""}${parts.length ? `{ ${parts.join(", ")} }` : ""} from "${from}";`, d.line); + for (const n of rest) if (!this.isTypeImport(d, n.name)) this.snapAlias(n.alias, ind, d.line); + } + /** A type export binds no value (MO-6c); `typeof` it is not a snapshot. */ + private isTypeImport(d: Extract, name: string): boolean { + if (!d.resolved) return false; + if (this.set.programs.get(d.resolved)?.decls.some(x => x.k === "typedecl" && x.name === name)) return true; + return this.set.signatures?.get(d.resolved)?.exports.get(name)?.kind === "type"; + } + /** Snap names a handler reads, not counting its parameters, its locals, or a nested arrow (that one snapshots itself). Sorted, so both projections agree. */ + private handlerSnaps(fn: Extract): string[] { + const bound = new Set(fn.params); + const out = new Set(); + const expr = (e: Expr) => { + if (!e?.k) return; + if (e.k === "fn" || e.k === "serverfn" || e.k === "draft") return; + if (e.k === "id") { if (this.snap.has(e.name) && !bound.has(e.name)) out.add(e.name); return; } + for (const v of Object.values(e)) { + if (Array.isArray(v)) { for (const x of v) if (x && typeof x === "object") { if ("k" in x) expr(x as Expr); else if ("v" in x) expr((x as { v: Expr }).v); else if ("spread" in x) expr((x as { spread: Expr }).spread); } } + else if (v && typeof v === "object" && "k" in v) expr(v as Expr); + } + }; + const stmts = (ss: Stmt[]) => { + for (const s of ss) { + if (s.k === "let") { expr(s.e); bound.add(s.name); continue; } + if (s.k === "write" || s.k === "optimistic") { for (const p of s.target.path) if (typeof p !== "string") expr(p); expr(s.e); continue; } + if (s.k === "sif") { expr(s.c); stmts(s.t); stmts(s.f); continue; } + if (s.k === "try") { stmts(s.body); if (s.handler) stmts(s.handler); if (s.fin) stmts(s.fin); continue; } + if (s.k === "action") { stmts(s.body); continue; } + if (s.k === "throw" || s.k === "expr") expr(s.k === "throw" ? s.e : s.e); + if (s.k === "return" && s.e) expr(s.e); + } + }; + if (fn.stmts) stmts(fn.stmts); else expr(fn.body); + return [...out].sort(); + } + /** A handler's read of this name is a snapshot of its type, not a branch's narrowing (TY-2). */ + private snapAlias(alias: string, ind: string, line: number) { + this.snap.add(alias); + this.w.emit(`${ind}type __W_${alias} = typeof ${alias};`, line); } /** TY-4b: check the import against its `.d.rx`, not whatever TypeScript would resolve the JS module to. */ private declaredImport(d: Extract, rest: { name: string; alias: string }[], decls: JsDecl[], ind: string) { @@ -220,7 +261,7 @@ class Proj { for (const n of rest) { const x = of(n.name); if (!x || x.kind === "type") this.w.emit(`${ind}type ${n.alias} = ${ns}.${n.name};`, d.line); - else this.w.emit(`${ind}const ${n.alias} = __js_${n.alias} as typeof ${ns}.${n.name};`, d.line); + else { this.w.emit(`${ind}const ${n.alias} = __js_${n.alias} as typeof ${ns}.${n.name};`, d.line); this.snapAlias(n.alias, ind, d.line); } if (x?.kind === "error") this.w.emit(`${ind}type ${n.alias} = ${ns}.${n.name};`, d.line); } } @@ -284,7 +325,7 @@ class Proj { const go = (x: Expr) => this.expr(x, imp, self); switch (e.k) { case "lit": return J(e.v); - case "id": if (BUILTINS.has(e.name) && !this.declared.has(e.name)) this.used.add(e.name); return e.name; + case "id": if (BUILTINS.has(e.name) && !this.declared.has(e.name)) this.used.add(e.name); return this.rename?.get(e.name) ?? e.name; case "pre": return e.name === self ? (e.init ? `__.pre(${go(e.init)})` : `__.pre()`) : `__.pre(${e.init ? go(e.init) : ""})`; case "peek": case "latest": return go(e.e); case "pending": return `__.pending(${go(e.e)})`; @@ -309,9 +350,17 @@ class Proj { 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/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 { +