Skip to content

Commit c8aac88

Browse files
fix(compiler): preserve TSRX expression and comment spans (#3787)
* fix(compiler): preserve TSRX expression and comment spans * chore(ci): rerun performance validation --------- Co-authored-by: Ryan Carniato <[email protected]>
1 parent ea5f1da commit c8aac88

6 files changed

Lines changed: 551 additions & 60 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@solidjs/compiler": patch
3+
---
4+
5+
Fix native TSRX compilation of parenthesized keys, iterables, and conditions, including annotated `@for` loops used directly in a component body. Map comments back to the authored source to prevent invalid JavaScript and Unicode panics when source maps are enabled.

‎packages/compiler/__tests__/tsrx-for-semantics.test.js‎

Lines changed: 64 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
const { compileBabel, compileOxc, modes } = require("./parity/harness");
1+
const { compileBabel, compileOxc, modes, normalize } = require("./parity/harness");
22

33
const source = `
44
export function Rows({ rows }) @{
@@ -53,3 +53,66 @@ describe("TSRX @for semantics", () => {
5353
);
5454
});
5555
});
56+
57+
// Keep the published parser's grammar: parenthesized key values are supported,
58+
// while index bindings still use a bare identifier.
59+
describe.each(["dom", "ssr", "universal"])("parenthesized @for keys (%s)", mode => {
60+
test.each([
61+
["(item.id)", 3],
62+
["(((item.id)))", 3],
63+
["( /* before */ (item.id) /* after */ )", 3],
64+
["((item.id + 1) * 2)", 8],
65+
["(item.id, item.other)", 7],
66+
["(item.id ? (item.other ?? 9) : 0)", 7]
67+
])("preserves emitted code and key evaluation for key%s", (key, expected) => {
68+
const source = `export function F(items) @{ @for(const item of items; key${key}) { <div/> } }`;
69+
const options = modes[`tsrx-${mode}`].options;
70+
const babel = compileBabel(source, options, "parenthesized-key.tsrx");
71+
const native = compileOxc(source, "parenthesized-key", options, ".tsrx");
72+
expect(normalize(native)).toBe(normalize(babel));
73+
for (const output of [babel, native]) {
74+
expect(output).not.toMatch(/__tsrx/);
75+
// Execute the emitted key callback independently of renderer helpers.
76+
const core = require("@babel/core");
77+
const callbacks = [];
78+
core.transformSync(output, {
79+
configFile: false,
80+
babelrc: false,
81+
plugins: [
82+
() => ({
83+
visitor: {
84+
ObjectProperty(path) {
85+
if (path.node.key.name !== "keyed") return;
86+
const expression = core.transformFromAstSync(
87+
core.types.file(
88+
core.types.program([core.types.expressionStatement(path.node.value)])
89+
),
90+
null,
91+
{ configFile: false, babelrc: false }
92+
).code;
93+
callbacks.push(new Function(`return (${expression.replace(/;$/, "")});`)());
94+
}
95+
}
96+
})
97+
]
98+
});
99+
expect(callbacks).toHaveLength(1);
100+
expect(callbacks[0]({ id: 3, other: 7 })).toBe(expected);
101+
}
102+
});
103+
});
104+
105+
describe.each(["dom", "ssr", "universal"])("deep parenthesized control anchors (%s)", mode => {
106+
test.each([
107+
"@for(const item of (((items))); key item.id) { <div/> }",
108+
"@for(const item of (((items)))) { <div/> }",
109+
"@if ((((ready)))) { <div/> }",
110+
"@if ((/* outer */ ((ready)))) { <div/> }"
111+
])("matches Babel for %s", control => {
112+
const source = `export function F(items, ready) @{ ${control} }`;
113+
const options = modes[`tsrx-${mode}`].options;
114+
expect(normalize(compileOxc(source, "deep-control", options, ".tsrx"))).toBe(
115+
normalize(compileBabel(source, options, "deep-control.tsrx"))
116+
);
117+
});
118+
});

‎packages/compiler/__tests__/tsrx-runtime.test.js‎

Lines changed: 89 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -54,15 +54,21 @@ function compileRuntime(source, compiler, generate) {
5454
// prod (signals' `DEV` export is undefined) and the first click throws. Every
5555
// flag the runtime packages gate on must be listed in BOTH places: a flag the
5656
// define misses is a ReferenceError at first use.
57-
const workspaceSourceRoots = ["solid", "web", "signals"].map(
57+
const workspaceSourceRoots = ["solid", "web", "signals", "universal"].map(
5858
name => path.join(repoRoot, "packages", name, "src") + path.sep
5959
);
6060

6161
async function loadRuntimeModule(code, generate) {
6262
const aliases = new Map([
6363
[
6464
"@solidjs/web",
65-
path.join(repoRoot, "packages/web/src", generate === "ssr" ? "index.server.ts" : "index.ts")
65+
generate === "universal"
66+
? path.join(repoRoot, "packages/universal/test/custom.js")
67+
: path.join(
68+
repoRoot,
69+
"packages/web/src",
70+
generate === "ssr" ? "index.server.ts" : "index.ts"
71+
)
6672
],
6773
["solid-js", path.join(repoRoot, "packages/solid/src/index.ts")],
6874
// The web runtime reaches solid-js's seams through this subpath (#3470).
@@ -99,6 +105,11 @@ async function loadRuntimeModule(code, generate) {
99105
path: aliases.get(args.path)
100106
})
101107
);
108+
esbuild.onLoad({ filter: /\/universal\/test\/custom\.js$/ }, args => ({
109+
contents: fs.readFileSync(args.path, "utf8") + '\nexport * from "solid-js";',
110+
loader: "js",
111+
resolveDir: path.dirname(args.path)
112+
}));
102113
esbuild.onLoad({ filter: /\.ts$/ }, args => {
103114
if (!workspaceSourceRoots.some(root => args.path.startsWith(root))) return;
104115
return {
@@ -215,7 +226,11 @@ describe.each(["babel", "oxc"])("%s TSRX runtime behavior", compiler => {
215226
dispose();
216227
});
217228

218-
test("passes For and Errored accessor bindings through as authored", async () => {
229+
test.each(
230+
["dom", "universal"].flatMap(mode =>
231+
[" row.id", "(row.id)", "(/* key */ ((row.id)))"].map(key => [mode, key])
232+
)
233+
)("passes For and Errored accessor bindings through in %s with key%s", async (mode, key) => {
219234
// #3474: the bindings are the accessors Solid hands out. `row()` and `i()`
220235
// read live under a custom key, `err()` is the ErrorAccessor.
221236
const source = `
@@ -236,7 +251,7 @@ describe.each(["babel", "oxc"])("%s TSRX runtime behavior", compiler => {
236251
export function App() @{
237252
<section>
238253
<ul>
239-
@for (const row of rows(); index i; key row.id) {
254+
@for (const row of rows(); index i; key${key}) {
240255
const snapshot = row;
241256
<li data-id={snapshot().id}>{i()}:{row().label ?? row().id}:{row().extra}</li>
242257
}
@@ -258,7 +273,7 @@ describe.each(["babel", "oxc"])("%s TSRX runtime behavior", compiler => {
258273
flush();
259274
}
260275
`;
261-
const runtime = await loadRuntimeModule(compileRuntime(source, compiler, "dom"), "dom");
276+
const runtime = await loadRuntimeModule(compileRuntime(source, compiler, mode), mode);
262277
const root = document.createElement("div");
263278
const dispose = runtime.mount(root);
264279

@@ -281,6 +296,54 @@ describe.each(["babel", "oxc"])("%s TSRX runtime behavior", compiler => {
281296
dispose();
282297
});
283298

299+
test.each(
300+
["dom", "ssr", "universal"].flatMap(mode =>
301+
["key item.id", "index i", "index i; key item.id"].map(annotation => [mode, annotation])
302+
)
303+
)("renders a statement-position annotated loop in %s with %s", async (mode, annotation) => {
304+
const source = `
305+
import { createSignal, flush } from "solid-js";
306+
import { ${mode === "ssr" ? "renderToString" : "render"} } from "@solidjs/web";
307+
const [items, setItems] = createSignal([
308+
{ id: 1, label: "one" }, { id: 2, label: "two" }
309+
]);
310+
export function App() @{
311+
@for (const item of items(); ${annotation}) {
312+
<span data-id={item().id}>{item().label}</span>
313+
}
314+
}
315+
export function run(target) {
316+
return ${mode === "ssr" ? "renderToString(App)" : "render(App, target)"};
317+
}
318+
export function replaceItems(next) {
319+
setItems(next);
320+
flush();
321+
}
322+
`;
323+
const output = compileRuntime(source, compiler, mode);
324+
expect(output).not.toMatch(/__tsrx/);
325+
const runtime = await loadRuntimeModule(output, mode);
326+
if (mode === "ssr") {
327+
expect(runtime.run()).toBe('<span data-id="1">one</span><span data-id="2">two</span>');
328+
return;
329+
}
330+
const root = document.createElement("div");
331+
const dispose = runtime.run(root);
332+
expect(root.textContent).toBe("onetwo");
333+
const retained = root.querySelector('[data-id="2"]');
334+
runtime.replaceItems([
335+
{ id: 2, label: "TWO" },
336+
{ id: 3, label: "three" }
337+
]);
338+
expect(root.textContent).toBe("TWOthree");
339+
if (annotation.includes("key")) {
340+
expect(root.querySelector('[data-id="2"]')).toBe(retained);
341+
}
342+
runtime.replaceItems([]);
343+
expect(root.textContent).toBe("");
344+
dispose();
345+
});
346+
284347
test("rejects destructuring where Solid passes an accessor", () => {
285348
const cases = [
286349
[
@@ -348,22 +411,25 @@ describe.each(["babel", "oxc"])("%s TSRX runtime behavior", compiler => {
348411
dispose();
349412
});
350413

351-
test("renders SSR branches, keyed lists, and empty fallbacks", async () => {
352-
const source = readRuntimeFixture("ssr");
353-
const runtime = await loadRuntimeModule(compileRuntime(source, compiler, "ssr"), "ssr");
354-
355-
expect(
356-
runtime.renderPage({
357-
show: true,
358-
items: [
359-
{ id: 1, label: "one" },
360-
{ id: 2, label: "two" }
361-
]
362-
})
363-
).toBe("<main><ul><li>one</li><li>two</li></ul></main>");
364-
expect(runtime.renderPage({ show: true, items: [] })).toBe(
365-
"<main><ul><li>empty</li></ul></main>"
366-
);
367-
expect(runtime.renderPage({ show: false, items: [] })).toBe("<main><p>hidden</p></main>");
368-
});
414+
test.each([" item.id", "(item.id)", "(/* key */ ((item.id)))"])(
415+
"renders SSR branches, keyed lists, and empty fallbacks with key%s",
416+
async key => {
417+
const source = readRuntimeFixture("ssr").replace("key item.id", `key${key}`);
418+
const runtime = await loadRuntimeModule(compileRuntime(source, compiler, "ssr"), "ssr");
419+
420+
expect(
421+
runtime.renderPage({
422+
show: true,
423+
items: [
424+
{ id: 1, label: "one" },
425+
{ id: 2, label: "two" }
426+
]
427+
})
428+
).toBe("<main><ul><li>one</li><li>two</li></ul></main>");
429+
expect(runtime.renderPage({ show: true, items: [] })).toBe(
430+
"<main><ul><li>empty</li></ul></main>"
431+
);
432+
expect(runtime.renderPage({ show: false, items: [] })).toBe("<main><p>hidden</p></main>");
433+
}
434+
);
369435
});
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
const babel = require("@babel/core");
2+
const { compileBabel, compileOxc, modes } = require("./parity/harness");
3+
4+
function assertValid(code) {
5+
expect(() => babel.parseSync(code, { babelrc: false, configFile: false })).not.toThrow();
6+
expect(code).not.toMatch(/_t\d+_(?:R|K|I|H)\d/);
7+
}
8+
9+
describe.each(["dom", "ssr", "universal"])("TSRX authored comments (%s)", mode => {
10+
const options = { ...modes[`tsrx-${mode}`].options, sourceMap: true };
11+
test("emits valid JavaScript across projected comment offsets", () => {
12+
for (let width = 0; width <= 32; width++) {
13+
const key = `item.id + "${"a".repeat(width)}"`;
14+
const sources = [
15+
`export function F(items, ready) @{ @for(const item of items; key(${key})) { <div/> } }`,
16+
`export function F(items, ready) @{ @for(const item of items; key ${key}) { <div/> } }`,
17+
`const v = @for(const item of items; key ${key}) { <div/> };`,
18+
`const v = @for(const item of items; key(${key})) { <div/> };`,
19+
`const v = @for(const item of items; index i; key ${key}) { <div>{i()}</div> };`,
20+
`export function F(items) @{ <ul>@for(const item of items; key ${key}) { <li/> }</ul> }`,
21+
`export function F(ready) @{ @if (ready === "${"a".repeat(width)}") { <div/> } }`,
22+
`const v = @switch (value) { @case "${"a".repeat(width)}": { <div/> } @default: { <span/> } };`
23+
];
24+
for (const source of sources) assertValid(compileOxc(source, "comments", options, ".tsrx"));
25+
}
26+
});
27+
28+
test("emits a valid conditional key after LF", () => {
29+
const source =
30+
"export function F(items) @{ @for(const item of items;\nkey(item.active ? item.id : item.other)) { <div/> } }";
31+
assertValid(compileBabel(source, options, "comments.tsrx"));
32+
assertValid(compileOxc(source, "comments", options, ".tsrx"));
33+
});
34+
35+
test("preserves authored comments and annotations after projection", () => {
36+
const source = `
37+
/*! authored license */
38+
export function F(items) @{
39+
// authored setup
40+
const local = /* @__PURE__ */ factory();
41+
@for(const item of items; key(/* authored key */ item.id)) { <div>{local}</div> }
42+
}
43+
/* @__NO_SIDE_EFFECTS__ */
44+
function helper() { return 1; }
45+
// authored tail
46+
export const result = /* #__PURE__ */ helper();
47+
`;
48+
const output = compileOxc(source, "comments", options, ".tsrx");
49+
assertValid(output);
50+
for (const comment of [
51+
"authored license",
52+
"authored setup",
53+
"authored tail",
54+
"@__NO_SIDE_EFFECTS__",
55+
"#__PURE__"
56+
]) {
57+
expect(output).toContain(comment);
58+
}
59+
// Babel also drops the key comment; it must not leak authored source instead.
60+
expect(output).not.toMatch(/item\.id\)\) \{/);
61+
expect(output).toMatch(/@__PURE__[\s\S]*factory\(\)/);
62+
});
63+
});

0 commit comments

Comments
 (0)