Skip to content

Commit cd6eb4f

Browse files
committed
Merge main (#65, #66, #86, #87, #88) into claude/project-thread-xp2irv
solid-next.sh takes #87's version (fetch the pin by hash, SOLID_BRANCH); the pin stays 99db9bce4. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0117BoWLtkg281f1NkGEDjCt
2 parents ca85aef + b470614 commit cd6eb4f

39 files changed

Lines changed: 373670 additions & 38 deletions

‎.github/workflows/editor.yml‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,9 @@ name: editor
1313
on:
1414
push:
1515
branches: [main]
16-
paths: ["compiler/**", "tooling/**", ".github/workflows/editor.yml"]
16+
paths: ["compiler/**", "tooling/**", "runtime/**", "ref/compile/rt-*.ts", ".github/workflows/editor.yml"]
1717
pull_request:
18-
paths: ["compiler/**", "tooling/**", ".github/workflows/editor.yml"]
18+
paths: ["compiler/**", "tooling/**", "runtime/**", "ref/compile/rt-*.ts", ".github/workflows/editor.yml"]
1919
workflow_dispatch:
2020

2121
jobs:
@@ -41,6 +41,8 @@ jobs:
4141
cargo build --lib --release --target wasm32-unknown-unknown --manifest-path compiler/Cargo.toml
4242
- name: Solid next (the types the tests check against)
4343
run: sh ref/scripts/solid-next.sh && npm --prefix ref install
44+
- name: The runtime (test/tsc.js checks an entry against its types)
45+
run: npm --prefix runtime ci && npm --prefix runtime run build
4446
- name: Language server tests
4547
working-directory: tooling/rx-language-server
4648
run: |

‎.github/workflows/tree-sitter.yml‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# The tree-sitter grammar (tooling/tree-sitter-rx): src/ is generated but committed, since Zed compiles src/parser.c
2+
# as it is, so check it is what grammar.js generates; then the corpus, and every tracked .rx file with no ERROR or
3+
# MISSING node.
4+
name: tree-sitter
5+
6+
on:
7+
push:
8+
branches: [main]
9+
paths: ["tooling/tree-sitter-rx/**", "**/*.rx", ".github/workflows/tree-sitter.yml"]
10+
pull_request:
11+
paths: ["tooling/tree-sitter-rx/**", "**/*.rx", ".github/workflows/tree-sitter.yml"]
12+
workflow_dispatch:
13+
14+
jobs:
15+
grammar:
16+
runs-on: ubuntu-latest
17+
defaults:
18+
run:
19+
working-directory: tooling/tree-sitter-rx
20+
steps:
21+
- uses: actions/checkout@v5
22+
- uses: pnpm/action-setup@v4
23+
with:
24+
version: 11.1.1 # as editor.yml
25+
- uses: actions/setup-node@v5
26+
with:
27+
node-version: 22
28+
- run: pnpm install --frozen-lockfile
29+
- name: src/ is what grammar.js generates
30+
run: |
31+
pnpm run generate
32+
git diff --exit-code -- src/
33+
- name: Corpus
34+
run: pnpm test
35+
- name: Every tracked .rx file
36+
run: pnpm run parse:repo
37+
- name: Queries
38+
run: pnpm run query -- ../../examples/*.rx > /dev/null

‎CONTRIBUTING.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ spec diverges from Solid, the divergence is recorded as a `DV-n` in
2323

2424
## Running the suite
2525

26-
Solid is built from its `next` branch at the pinned commit (needs pnpm and a
26+
Solid is built from its `main` branch at the pinned commit (needs pnpm and a
2727
Rust toolchain):
2828

2929
```sh

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,7 @@ node --experimental-strip-types ref/check.ts examples/todo.rx # check a progra
177177
node --experimental-strip-types ref/run.ts # run every scenario
178178
```
179179

180-
Running the scenarios on Solid itself needs Solid's `next` branch built from
180+
Running the scenarios on Solid itself needs Solid's `main` branch built from
181181
source (pnpm and a Rust toolchain); see [CONTRIBUTING.md](CONTRIBUTING.md) and
182182
[`ref/README.md`](ref/README.md). The compiler builds with Cargo
183183
([`compiler/README.md`](compiler/README.md)). To try an unreleased editor build, install a `.vsix` from a run of the

‎compiler/src/app.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ pub fn target(name: &str) -> Target {
2323
}
2424
}
2525

26-
/// `{entry, css, modules: {path: {code, map}}}`, or `{diagnostics: [...]}` / `{error}`. `entry` is an absolute path.
26+
/// `{entry, css, modules: {path: {code, map, css}}}` (the program's stylesheet, and each module's own), or `{diagnostics: [...]}` / `{error}`. `entry` is an absolute path.
2727
/// `spa`: a client-only build, checked under 08 CN-3d.
2828
pub fn app(entry: &str, target: Target, module_name: &str, spa: bool) -> Value {
2929
// module keys are POSIX paths (`modules::join_path`); Windows takes `D:/a/b.rx` as it takes `D:\a\b.rx`
@@ -49,7 +49,7 @@ pub fn app(entry: &str, target: Target, module_name: &str, spa: bool) -> Value {
4949
let path = &out.paths[name];
5050
let text = read_disk(path).unwrap_or_default();
5151
let l = lower_view(module, path, target, module_name, Some((path, &text))).map_err(|e| json!({ "error": e }))?;
52-
modules.insert(path.clone(), json!({ "code": l.code, "map": l.map }));
52+
modules.insert(path.clone(), json!({ "code": l.code, "map": l.map, "css": out.module_css[name] }));
5353
}
5454
Ok(json!({ "entry": set.entry, "css": out.css, "modules": modules }))
5555
})()

‎compiler/src/emit.rs‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,8 @@ pub struct Compiled {
185185
pub entry: String,
186186
/// CSS-4: the modules' stylesheets, beside their JavaScript
187187
pub css: String,
188+
/// CSS-4: each module's own stylesheet, by its output name
189+
pub module_css: IndexMap<String, String>,
188190
}
189191

190192
/// 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
@@ -202,8 +204,10 @@ pub fn compile_linked(set: &ModuleSet, extra: &[Vec<Stmt>], by_source: bool) ->
202204
g.by_source = by_source;
203205
let mut files = IndexMap::new();
204206
let mut paths = IndexMap::new();
207+
let mut module_css = IndexMap::new();
205208
for path in &set.order {
206209
let p = &set.programs[path];
210+
let css0 = g.css.len();
207211
g.begin_module(path, &p.decls);
208212
let mut deps: Vec<&str> = vec![];
209213
for d in &p.decls {
@@ -237,10 +241,11 @@ pub fn compile_linked(set: &ModuleSet, extra: &[Vec<Stmt>], by_source: bool) ->
237241
fbody.append(&mut inner);
238242
body.push(S::ExportDefault(Func { name: Some("module".into()), params: vec![P::Id("__rt".into())], directives: vec![], body: fbody, is_async: false, generator: false }));
239243
}
244+
module_css.insert(g.out(path), g.css[css0..].join("\n"));
240245
files.insert(g.out(path), body);
241246
paths.insert(g.out(path), path.clone());
242247
}
243-
Ok(Compiled { files, paths, entry: g.out(&set.entry), css: g.css.join("\n") })
248+
Ok(Compiled { files, paths, entry: g.out(&set.entry), css: g.css.join("\n"), module_css })
244249
}
245250

246251
struct Gen<'p> {

‎compiler/src/prelude.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ export declare function eq<T>(v: T, ok: Async<T> extends true ? "MISSING_AWAIT:
99
export declare function first<T, I>(v: T, init: I): T | I;
1010
export declare function pre<T>(init?: T): T;
1111
export declare function pending(v: unknown): boolean;
12-
/** RG-4b: an object rest, \`{ a, ...rest } = e\` (Solid's \`omit\`). */
12+
/** RG-4b: an object rest, `{ a, ...rest } = e` (Solid's `omit`). */
1313
export declare function omit<T, K extends string>(v: T, ...keys: K[]): Omit<T, K>;
1414
export declare function caught<T, R>(v: T, alt: (e: any) => R): T | R;
1515
export declare function raise(e: unknown): never;
@@ -30,6 +30,8 @@ export declare function wire<A extends unknown[], R>(f: (...a: A) => Promise<R>,
3030
/** 07 §6: a view (`props.children: View`); R-f-10: the class a panic is. */
3131
export type View = JSX.Element;
3232
export type Panic = Error;
33+
/** CP-4a: an entry's default export, a function of the app (`createApp`'s, either build) giving the view `app.mount` takes. */
34+
export type Main = (app: object) => () => View;
3335
export interface Ctx<T> { readonly __ctx: T }
3436
export declare function ctx<T>(d?: T): Ctx<T>;
3537
export declare function use<T>(c: Ctx<T>): T;

‎compiler/src/project.rs‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -349,6 +349,10 @@ impl Proj<'_> {
349349
self.markup(&p.view, " ");
350350
self.w.emit(Code::of(");"), p.view[p.view.len() - 1].line.unwrap_or(1));
351351
}
352+
if let Some(Decl::Component { line, .. }) = p.decls.iter().find(|d| matches!(d, Decl::Component { is_default: true, .. })) {
353+
// CP-4a: what JS imports from an entry
354+
self.w.emit(Code::of("declare const __main: __.Main; export default __main;"), *line);
355+
}
352356
let body = std::mem::replace(&mut self.w, saved);
353357
let prelude: Vec<String> = self.used.iter().filter(|n| !self.declared.contains(*n)).cloned().collect();
354358
let types: Vec<&str> = ["View", "Panic"].into_iter().filter(|n| !self.declared.contains(*n)).collect();
@@ -1002,3 +1006,32 @@ fn class_map(css: &str) -> String {
10021006
let fields: Vec<String> = r.class_map.into_iter().map(|c| format!("{}: \"\" as string", js_str(&c.class_name))).collect();
10031007
format!("({{ {} }} as const)", fields.join(", "))
10041008
}
1009+
1010+
#[cfg(test)]
1011+
mod tests {
1012+
use super::*;
1013+
use crate::modules::load_modules;
1014+
use std::collections::HashMap;
1015+
1016+
#[test]
1017+
fn an_entry_default_is_the_apps_main_and_its_component_keeps_its_mappings() {
1018+
let files: HashMap<&str, &str> = [
1019+
("app/main.rx", "import { Badge } from \"./badge.rx\"\nexport default component App() {\n source n := 0\n <Badge n={n} />\n}\n"),
1020+
("app/badge.rx", "export component Badge(props: { n: number }) {\n <b>{props.n}</b>\n}\n"),
1021+
]
1022+
.into_iter()
1023+
.collect();
1024+
let set = load_modules("app/main.rx", &|p| files.get(p).map(|s| s.to_string())).expect("loads");
1025+
let out = project_modules(&set);
1026+
let main = out.iter().find(|p| p.rx == "app/main.rx").unwrap();
1027+
assert!(main.code.ends_with("\ndeclare const __main: __.Main; export default __main;"), "{}", main.code);
1028+
assert_eq!(main.code.matches("export default").count(), 1);
1029+
assert_eq!(main.lines.len(), main.code.lines().count());
1030+
let at = main.code.find("export function App(").unwrap() + "export function ".len();
1031+
let src = files["app/main.rx"].find("App").unwrap();
1032+
assert!(main.mappings.iter().any(|m| m.gen as usize == at && m.src as usize == src && m.len == 3));
1033+
let dep = out.iter().find(|p| p.rx == "app/badge.rx").unwrap();
1034+
assert!(!dep.code.contains("export default"), "{}", dep.code);
1035+
assert!(PRELUDE.contains("export type Main = (app: object) => () => View;"));
1036+
}
1037+
}

‎compiler/test/vite.mjs‎

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,9 +118,51 @@ if (!filter || "shared".includes(filter)) { // two programs on one page, shari
118118
if (!filter || "todo".includes(filter)) { // the dev server: modules transformed on request
119119
const dir = project("todo-dev", "todo.rx");
120120
const server = await vite.createServer(config(dir, "todo.rx")); await server.listen(0);
121-
await drive("todo (dev)", `http://127.0.0.1:${server.httpServer.address().port}/`, todo);
121+
await drive("todo (dev)", server.resolvedUrls.local[0], todo);
122122
await server.close();
123123
}
124+
if (!filter || "styles".includes(filter)) { // CSS-4 under the dev server: a dependency's <style> edit reaches the page
125+
const dir = project("styles-dev", "styled/main.rx");
126+
mkdirSync(path.join(dir, "src/styled"));
127+
writeFileSync(path.join(dir, "src/styled/main.rx"), `import { Badge } from "./badge.rx"\n\nexport default component Main() {\n <main><Badge /></main>\n}\n`);
128+
const badge = path.join(dir, "src/styled/badge.rx");
129+
const style = color => `export component Badge() {\n <style>\n .badge { color: ${color} }\n </style>\n <p class="badge">badge</p>\n}\n`;
130+
writeFileSync(badge, style("rgb(0, 0, 255)"));
131+
const server = await vite.createServer(config(dir, "styled/main.rx")); await server.listen(0);
132+
const url = server.resolvedUrls.local[0];
133+
const color = page => page.$eval(".badge", e => getComputedStyle(e).color);
134+
const until = async (page, want, what) => {
135+
for (let i = 0; i < 40 && await color(page).catch(() => "") !== want; i++) await page.waitForTimeout(100);
136+
const got = await color(page).catch(e => e.message.split("\n")[0]); if (got !== want) throw new Error(`${what}: color ${got}, not ${want}`);
137+
};
138+
await drive("styles (dev)", url, async page => {
139+
await until(page, "rgb(0, 0, 255)", "first load");
140+
writeFileSync(badge, style("rgb(255, 0, 0)"));
141+
await until(page, "rgb(255, 0, 0)", "after the edit");
142+
await page.reload(); await until(page, "rgb(255, 0, 0)", "after a reload");
143+
const fresh = await browser.newPage();
144+
try { await fresh.goto(url); await until(fresh, "rgb(255, 0, 0)", "in a new page"); } finally { await fresh.close(); }
145+
});
146+
await server.close();
147+
}
148+
if (!filter || "cold".includes(filter)) { // a dependency asked for before its entry, as Vitest's `fsModuleCache` leaves it
149+
const { default: rx } = await import(pathToFileURL(path.join(pkg, "vite.mjs")).href);
150+
const root = project("cold", "shop/main.rx"), catalog = path.join(root, "src/shop/catalog.rx");
151+
const ctx = (id, moduleId) => ({ id, moduleId, root, ssr: false, solid: { generate: "dom", hydratable: false }, addWatchFile() {} });
152+
try {
153+
// a commented-out import is not an edge: read as one, it would make main.rx look imported and leave no entry
154+
writeFileSync(catalog, readFileSync(catalog, "utf8") + `\n// import { x } from "./main.rx"\n`);
155+
const warm = rx(); warm.compile("", ctx(path.join(root, "src/shop/main.rx"), path.join(root, "src/shop/main.rx")));
156+
const want = warm.compile("", ctx(catalog, `${catalog}?rx-dep`)).code;
157+
const got = rx().compile("", ctx(catalog, `${catalog}?rx-dep`)).code;
158+
if (got !== want) throw new Error("the dependency compiled cold differs from the one compiled after its entry");
159+
writeFileSync(catalog, readFileSync(catalog, "utf8") + "\nexport bad = missingName\n");
160+
let report = "";
161+
try { rx().compile("", ctx(catalog, `${catalog}?rx-dep`)); } catch (e) { report = e.message; }
162+
if (!/catalog\.rx:\d+(:\d+)?: error /.test(report)) throw new Error(`a cold dependency that does not compile reports ${JSON.stringify(report.slice(0, 200))}`);
163+
pass++; console.log("✓ cold dependency: compiled from the program that holds it, or that program's diagnostics");
164+
} catch (e) { fail++; console.log(`✗ cold dependency: ${e.message.split("\n")[0]}`); }
165+
}
124166
await browser.close();
125167
console.log(`\n${pass} pass, ${fail} fail (vite ${vite.version}, @solidjs/vite-plugin ${JSON.parse(readFileSync(path.join(pluginDir, "package.json"), "utf8")).version})`);
126168
process.exit(fail ? 1 : 0);

‎compiler/vite.mjs‎

Lines changed: 44 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@
33
// names it explicitly.
44
//
55
// The crate (its Node-API build, `src/node.rs`: what `rxc app` does) already hands each module to Solid's compiler
6-
// (spec/11 CP-1), so a `.rx` module comes back as Solid's output for the environment's `generate`, with its source map onto the `.rx` and, on a
7-
// program's entry, the program's stylesheet. Solid's plugin then takes it the way it takes lowered `.tsrx`: primitive
6+
// (spec/11 CP-1), so a `.rx` module comes back as Solid's output for the environment's `generate`, with its source map onto the `.rx` and
7+
// its own stylesheet. Solid's plugin then takes it the way it takes lowered `.tsrx`: primitive
88
// names, `lazy()`, the HMR refresh pass, server functions (12 SF-7a), the stylesheet as a CSS module.
99
//
1010
// Entries find themselves. JavaScript imports only a program's entry (its default export mounts the app); an `.rx`
@@ -13,7 +13,7 @@
1313
// changes. The crate's output imports its dependencies as `./x.rx?rx-dep`, and a dependency is served from the build
1414
// of a program that contains it. A module several programs share is one module: its instance is keyed by its factory
1515
// (11 CP-4b `module`), not by its place in a program.
16-
import { existsSync, statSync } from "node:fs";
16+
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
1717
import { createRequire } from "node:module";
1818
import path from "node:path";
1919
import { fileURLToPath } from "node:url";
@@ -35,6 +35,29 @@ const isDep = moduleId => new URLSearchParams(moduleId.split("?")[1] ?? "").has(
3535
// `import __m0 from "./catalog.rx";` → `"./catalog.rx?rx-dep"` (one line each: the module's map is by line, CP-1c)
3636
const tagDeps = code => code.replace(/^(import \w+ from ")(\.{1,2}\/[^"?]*\.rx)(";?)$/gm, `$1$2?${DEP}$3`);
3737

38+
const RX_IMPORT = /^import\b[^"']*?\bfrom\s+(["'])(\.{1,2}\/[^"'?]*\.rx)\1/gm;
39+
/** The `.rx` files under `root` from which `file` is reached by imports: first those no other `.rx` file imports. */
40+
function entriesOf(file, root) {
41+
const importers = new Map();
42+
const walk = dir => {
43+
for (const e of readdirSync(dir, { withFileTypes: true })) {
44+
if (e.name === "node_modules" || e.name.startsWith(".")) continue;
45+
const p = path.join(dir, e.name);
46+
if (e.isDirectory()) walk(p);
47+
else if (e.name.endsWith(".rx")) for (const [, , spec] of readFileSync(p, "utf8").matchAll(RX_IMPORT)) {
48+
const dep = path.resolve(path.dirname(p), spec);
49+
importers.set(dep, [...(importers.get(dep) ?? []), p]);
50+
}
51+
}
52+
};
53+
walk(root);
54+
const seen = new Set([file]);
55+
for (const f of seen) for (const i of importers.get(f) ?? []) seen.add(i);
56+
seen.delete(file);
57+
const top = f => !importers.has(f);
58+
return [...seen].sort().sort((a, b) => top(b) - top(a));
59+
}
60+
3861
/** @returns {import("@solidjs/vite-plugin").Frontend} */
3962
export default function rx() {
4063
const builds = new Map(); // entry\0target\0moduleName\0spa → { entry, target, moduleName, spa, out, stamps }
@@ -50,28 +73,38 @@ export default function rx() {
5073
builds.set(key, b);
5174
return b;
5275
}
76+
const built = (file, target, moduleName, spa) =>
77+
[...builds.values()].filter(b => b.target === target && b.moduleName === moduleName && b.spa === spa && b.out.modules?.[file]);
5378
/** A dependency: from a build of a program that has it, rebuilt if that program changed. */
54-
function containing(file, target, moduleName, spa) {
55-
const has = [...builds.values()].filter(b => b.target === target && b.moduleName === moduleName && b.spa === spa && b.out.modules?.[file]);
79+
function containing(file, target, moduleName, spa, root) {
80+
const has = built(file, target, moduleName, spa);
5681
const b = has.find(fresh) ?? has[0];
57-
if (!b) throw new Error(`${file} is imported as an .rx dependency, but no program built so far contains it`);
58-
return build(b.entry, target, moduleName, spa);
82+
if (b) return build(b.entry, target, moduleName, spa);
83+
// the entry's compile was skipped (Vitest's `fsModuleCache` served it), so find the program from the files
84+
let failed;
85+
for (const entry of entriesOf(file, root)) {
86+
const found = build(entry, target, moduleName, spa);
87+
if (found.out.modules?.[file]) return found;
88+
if (!failed && found.out.diagnostics) failed = found; // the program holds it but does not compile: report why
89+
}
90+
if (failed) return failed;
91+
throw new Error(`${file} is imported as an .rx dependency, but no program under ${root} contains it`);
5992
}
6093
return {
61-
compile(_source, { id, moduleId, solid, addWatchFile }) {
94+
compile(_source, { id, moduleId, root, solid, addWatchFile }) {
6295
const file = path.resolve(id);
6396
const target = solid.generate === "ssr" ? "ssr" : solid.generate === "universal" ? "universal" : "dom";
6497
const moduleName = solid.moduleName ?? "@solidjs/web";
6598
// 08 CN-3d: a client-only build (no SSR, nothing hydrates) has nothing to show on a first load nothing holds
6699
const spa = target === "dom" && solid.hydratable === false;
67100
const dep = isDep(moduleId);
68-
const { entry, out } = dep ? containing(file, target, moduleName, spa) : build(file, target, moduleName, spa);
101+
const { out } = dep ? containing(file, target, moduleName, spa, path.resolve(root ?? process.cwd())) : build(file, target, moduleName, spa);
69102
if (out.diagnostics) throw new Error(report(out.diagnostics));
70103
if (out.error) throw new Error(out.error);
71104
const m = out.modules[file];
72105
for (const p of Object.keys(out.modules)) if (p !== file) addWatchFile(p);
73-
// CSS-4: the program's stylesheet, linked once, from its entry
74-
return { code: tagDeps(m.code), map: m.map, css: !dep && file === entry ? out.css : "" };
106+
// CSS-4: each module links its own stylesheet, so a module several programs share links it once
107+
return { code: tagDeps(m.code), map: m.map, css: m.css ?? "" };
75108
},
76109
};
77110
}

0 commit comments

Comments
 (0)