solid-optimizer 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { a as readModuleConstants, c as SkipPass, i as compile, l as Primitive, n as CompileResult, o as ImportedConstants, r as ModuleConstants, s as Skip, t as CompileOptions } from "./compile-ioIkBKzR.mjs";
1
+ import { a as readModuleConstants, c as SkipPass, i as compile, l as Primitive, n as CompileResult, o as ImportedConstants, r as ModuleConstants, s as Skip, t as CompileOptions } from "./compile-BKA77zb8.mjs";
2
2
  export { type CompileOptions, type CompileResult, type ImportedConstants, type ModuleConstants, type Primitive, type Skip, type SkipPass, compile, readModuleConstants };
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { n as readModuleConstants, t as compile } from "./compile-Cvjy2e11.mjs";
1
+ import { n as readModuleConstants, t as compile } from "./compile-D2f8eXFk.mjs";
2
2
  export { compile, readModuleConstants };
package/dist/vite.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { s as Skip, t as CompileOptions } from "./compile-ioIkBKzR.mjs";
1
+ import { s as Skip, t as CompileOptions } from "./compile-BKA77zb8.mjs";
2
2
  import { Options as Options$1 } from "@solidjs/vite-plugin";
3
3
  import { Plugin } from "vite";
4
4
  //#region src/vite/report.d.ts
package/dist/vite.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { a as analyzeScopes, c as collectParents, d as parse, f as unwrap, i as runtimeImportSources, l as forEachChild, n as readModuleConstants, o as lookup, r as CONTEXT_SAFE_PRIMITIVES, s as scopeAt, t as compile, u as isIntrinsicTag } from "./compile-Cvjy2e11.mjs";
1
+ import { a as analyzeScopes, c as collectParents, d as parse, f as unwrap, i as runtimeImportSources, l as forEachChild, n as readModuleConstants, o as lookup, r as CONTEXT_SAFE_PRIMITIVES, s as scopeAt, t as compile, u as isIntrinsicTag } from "./compile-D2f8eXFk.mjs";
2
2
  import { createRequire } from "node:module";
3
3
  import remapping from "@jridgewell/remapping";
4
4
  import { parseSync } from "oxc-parser";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "solid-optimizer",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "Experimental compile-time optimizer for SolidJS",
5
5
  "keywords": [
6
6
  "compiler",
package/src/compile.ts CHANGED
@@ -15,6 +15,7 @@ import { lowerConditionals } from './conditional';
15
15
  import type { ScopeAnalysis } from './scope';
16
16
  import { analyzeScopes } from './scope';
17
17
  import { terminateStatements } from './terminate';
18
+ import { tidyJSX } from './tidy';
18
19
  import { Editor } from './text';
19
20
  import type { Primitive } from './value';
20
21
 
@@ -136,6 +137,15 @@ export interface CompileOptions {
136
137
  * @default 10
137
138
  */
138
139
  maxPasses?: number;
140
+ /**
141
+ * Tidy the JSX the passes write: drop empty braces, write strings in
142
+ * braces as plain JSX, and unwrap fragments that hold one element. It only
143
+ * changes how the output reads: Solid's JSX transform lowers it to the same
144
+ * code. It runs only on a module the passes changed.
145
+ *
146
+ * @default true
147
+ */
148
+ tidy?: boolean;
139
149
  /**
140
150
  * Generate a source map.
141
151
  *
@@ -364,6 +374,19 @@ export function compile(code: string, options: CompileOptions = {}): CompileResu
364
374
  maps.push(result.map);
365
375
  }
366
376
  }
377
+ // The passes leave empty braces, strings in braces and one-element
378
+ // fragments behind. Tidying them changes nothing Solid's JSX transform
379
+ // makes, but the output reads like code a person wrote.
380
+ const tidied =
381
+ (options.tidy ?? true)
382
+ ? runPass(parsedCurrent(), filename, resolved, sourceMap, tidyJSX, undefined)
383
+ : undefined;
384
+ if (tidied) {
385
+ current = tidied.code;
386
+ if (tidied.map !== undefined) {
387
+ maps.push(tidied.map);
388
+ }
389
+ }
367
390
  }
368
391
 
369
392
  const report = skipped ? { skipped } : {};
package/src/tidy.ts ADDED
@@ -0,0 +1,390 @@
1
+ /**
2
+ * Tidies the JSX the other passes wrote, without changing what it renders.
3
+ *
4
+ * - An empty `{}` child goes. The passes write one to keep two texts apart,
5
+ * so it only goes when the texts on both sides read the same without it.
6
+ * - A string in braces becomes plain JSX: `class={'card'}` becomes
7
+ * `class="card"`, and a `{'Hello'}` child becomes the text `Hello`.
8
+ * - A fragment that holds one element, with only line breaks around it,
9
+ * becomes that element.
10
+ *
11
+ * Each edit follows a model of how Solid's JSX transform reads JSX: its
12
+ * whitespace rule, which strings it writes as they are, and where a fragment
13
+ * around one element lowers the same as the element. Anything outside the
14
+ * model, such as unusual whitespace, stays as it is. The tests lower the
15
+ * tidied and untidied output and expect the same code.
16
+ */
17
+ import type {
18
+ JSXAttribute,
19
+ JSXElement,
20
+ JSXExpressionContainer,
21
+ JSXFragment,
22
+ Node,
23
+ } from 'oxc-parser';
24
+ import { forEachChild } from './ast';
25
+ import type { PassContext } from './context';
26
+
27
+ type Child = JSXElement['children'][number];
28
+
29
+ /**
30
+ * The text Solid's JSX transform makes of a raw text child: when the text
31
+ * has a line break, each line after the first loses its leading spaces, lines
32
+ * of only spaces drop out and the rest join with a space; then every run of
33
+ * spaces becomes one space. This differs from React's rule, which keeps runs
34
+ * of spaces on one line.
35
+ */
36
+ export function cleanText(raw: string): string {
37
+ let text = raw.replaceAll('\r', '');
38
+ if (text.includes('\n')) {
39
+ const kept: string[] = [];
40
+ for (const [index, line] of text.split('\n').entries()) {
41
+ const trimmed = index === 0 ? line : line.replace(/^[ \t]+/, '');
42
+ if (/[^ \t]/.test(trimmed)) {
43
+ kept.push(trimmed);
44
+ }
45
+ }
46
+ text = kept.join(' ');
47
+ }
48
+ return text.replaceAll(/[ \t\n]+/g, ' ');
49
+ }
50
+
51
+ /**
52
+ * Whether a text holds whitespace or format characters other than space,
53
+ * tab and line breaks, such as U+0085 or a byte order mark. Solid's JSX
54
+ * transform and JavaScript disagree on some of them, so such text stays as it is.
55
+ */
56
+ function hasUnusualSpace(text: string): boolean {
57
+ return /(?![ \t\n\r])[\s\p{White_Space}\p{Cf}]/u.test(text);
58
+ }
59
+
60
+ /**
61
+ * The string a container holds when it is a plain string written without
62
+ * escapes, such as `{'a'}` or `{`a`}`. The characters between the quotes are
63
+ * then the string itself, so tidying keeps them, and their source map
64
+ * positions, and only drops what is around them.
65
+ */
66
+ function readString(container: JSXExpressionContainer, code: string): string | undefined {
67
+ const { expression } = container;
68
+ let value: string | undefined;
69
+ if (expression.type === 'Literal' && typeof expression.value === 'string') {
70
+ value = expression.value;
71
+ } else if (
72
+ expression.type === 'TemplateLiteral' &&
73
+ expression.expressions.length === 0 &&
74
+ expression.quasis.length === 1
75
+ ) {
76
+ value = expression.quasis[0].value.cooked ?? undefined;
77
+ }
78
+ if (value === undefined || code.slice(expression.start + 1, expression.end - 1) !== value) {
79
+ return undefined;
80
+ }
81
+ // Braces that hold a comment beside the string keep it.
82
+ const around =
83
+ code.slice(container.start + 1, expression.start) +
84
+ code.slice(expression.end, container.end - 1);
85
+ if (around.trim() !== '') {
86
+ return undefined;
87
+ }
88
+ return value;
89
+ }
90
+
91
+ /**
92
+ * Replaces the braces and quotes around a string with `before` and `after`,
93
+ * keeping the string's own characters where they are.
94
+ */
95
+ function unwrapString(
96
+ container: JSXExpressionContainer,
97
+ before: string,
98
+ after: string,
99
+ context: PassContext,
100
+ ): void {
101
+ const { expression } = container;
102
+ const { code, s } = context;
103
+ // Removing keeps the mapping of the string's characters, and of quotes
104
+ // that stay. Only a quote that changes is written.
105
+ s.remove(container.start, expression.start);
106
+ s.remove(expression.end, container.end);
107
+ const open = code[expression.start];
108
+ const close = code[expression.end - 1];
109
+ if (before === open) {
110
+ // The quote stays.
111
+ } else if (before === '') {
112
+ s.remove(expression.start, expression.start + 1);
113
+ } else {
114
+ s.overwrite(expression.start, expression.start + 1, s.written(before, expression.start));
115
+ }
116
+ if (after === close) {
117
+ // The quote stays.
118
+ } else if (after === '') {
119
+ s.remove(expression.end - 1, expression.end);
120
+ } else {
121
+ s.overwrite(expression.end - 1, expression.end, s.written(after, expression.end - 1));
122
+ }
123
+ }
124
+
125
+ /** Whether a container holds nothing, not even a comment. */
126
+ function isEmpty(container: JSXExpressionContainer, code: string): boolean {
127
+ return (
128
+ container.expression.type === 'JSXEmptyExpression' &&
129
+ code.slice(container.start + 1, container.end - 1).trim() === ''
130
+ );
131
+ }
132
+
133
+ /**
134
+ * A child as it renders: raw text, which JSX cleans together with the raw
135
+ * text next to it; a literal string, which renders as it is and keeps the
136
+ * texts on its sides apart; or something else, such as an element.
137
+ */
138
+ type Part = { raw: string } | { literal: string } | { other: number };
139
+
140
+ /**
141
+ * The pieces a list of children renders: each text that is not empty, and a
142
+ * mark for each child that is not text.
143
+ */
144
+ function renderPieces(parts: readonly (Part | undefined)[]): string[] {
145
+ const pieces: string[] = [];
146
+ let raw: string | undefined;
147
+ const flush = (): void => {
148
+ if (raw !== undefined) {
149
+ const text = cleanText(raw);
150
+ if (text !== '') {
151
+ pieces.push(text);
152
+ }
153
+ raw = undefined;
154
+ }
155
+ };
156
+ for (const part of parts) {
157
+ if (!part) {
158
+ continue;
159
+ }
160
+ if ('raw' in part) {
161
+ raw = (raw ?? '') + part.raw;
162
+ } else if ('literal' in part) {
163
+ flush();
164
+ if (part.literal !== '') {
165
+ pieces.push(part.literal);
166
+ }
167
+ } else {
168
+ flush();
169
+ pieces.push(`\0${String(part.other)}`);
170
+ }
171
+ }
172
+ flush();
173
+ return pieces;
174
+ }
175
+
176
+ /**
177
+ * What a list of children renders. In an element, Solid's JSX transform
178
+ * writes the texts next to each other into the template as one text, so
179
+ * only the joined text counts. Anywhere else, such as a fragment, each text
180
+ * stays its own string, so the pieces must stay apart too.
181
+ */
182
+ function render(parts: readonly (Part | undefined)[], inElement: boolean): string {
183
+ const pieces = renderPieces(parts);
184
+ if (!inElement) {
185
+ return JSON.stringify(pieces);
186
+ }
187
+ let joined = '';
188
+ for (const piece of pieces) {
189
+ joined += piece.startsWith('\0') ? `${piece}\0` : piece;
190
+ }
191
+ return joined;
192
+ }
193
+
194
+ /** Whether an element is an HTML or SVG element, which Solid lowers into a template. */
195
+ function isIntrinsic(element: JSXElement): boolean {
196
+ const { name } = element.openingElement;
197
+ if (name.type === 'JSXNamespacedName') {
198
+ return true;
199
+ }
200
+ return name.type === 'JSXIdentifier' && /^[a-z]/.test(name.name);
201
+ }
202
+
203
+ /** A string that can be written as JSX text: no syntax, no entities, no line breaks. */
204
+ function isPlainText(value: string): boolean {
205
+ return (
206
+ value !== '' &&
207
+ !/[{}<>&\r\n\t]/.test(value) &&
208
+ !hasUnusualSpace(value) &&
209
+ value.trim() === value
210
+ );
211
+ }
212
+
213
+ /** A string that can be written as a JSX attribute in double quotes. */
214
+ function isPlainAttribute(value: string): boolean {
215
+ return !/["&\r\n]/.test(value) && !hasUnusualSpace(value);
216
+ }
217
+
218
+ /**
219
+ * Attributes whose string Solid's JSX transform treats differently once it
220
+ * is written as a plain value: it moves a static `style` last, and `ref`,
221
+ * `classList`, event handlers (`on` in any case) and namespaced attributes do
222
+ * not take a string.
223
+ */
224
+ function isTidyAttribute(attribute: JSXAttribute): boolean {
225
+ const { name } = attribute;
226
+ return (
227
+ name.type === 'JSXIdentifier' &&
228
+ name.name !== 'style' &&
229
+ name.name !== 'ref' &&
230
+ name.name !== 'classList' &&
231
+ !name.name.startsWith('on')
232
+ );
233
+ }
234
+
235
+ /**
236
+ * Whether an element can get children from an attribute: a `children`
237
+ * attribute or a spread. Its own children then decide whether those show, so
238
+ * even an empty `{}` among them counts, and they stay as they are.
239
+ */
240
+ function hasChildrenAttribute(element: JSXElement): boolean {
241
+ for (const attribute of element.openingElement.attributes) {
242
+ if (
243
+ attribute.type === 'JSXSpreadAttribute' ||
244
+ (attribute.name.type === 'JSXIdentifier' && attribute.name.name === 'children')
245
+ ) {
246
+ return true;
247
+ }
248
+ }
249
+ return false;
250
+ }
251
+
252
+ /**
253
+ * Removes empty braces and writes plain strings as text, one at a time. Each
254
+ * edit is kept only when the children still render the same with every edit
255
+ * kept so far.
256
+ */
257
+ function tidyChildren(
258
+ children: readonly Child[],
259
+ inElement: boolean,
260
+ context: PassContext,
261
+ ): boolean {
262
+ const { code, s } = context;
263
+ for (const child of children) {
264
+ if (child.type === 'JSXText' && hasUnusualSpace(code.slice(child.start, child.end))) {
265
+ return false;
266
+ }
267
+ }
268
+ const parts: (Part | undefined)[] = [];
269
+ for (const [index, child] of children.entries()) {
270
+ if (child.type === 'JSXText') {
271
+ parts.push({ raw: code.slice(child.start, child.end) });
272
+ } else if (child.type === 'JSXExpressionContainer' && isEmpty(child, code)) {
273
+ parts.push({ literal: '' });
274
+ } else if (child.type === 'JSXExpressionContainer' && readString(child, code) !== undefined) {
275
+ parts.push({ literal: readString(child, code) ?? '' });
276
+ } else {
277
+ parts.push({ other: index });
278
+ }
279
+ }
280
+ const expected = render(parts, inElement);
281
+ let changed = false;
282
+ for (const [index, child] of children.entries()) {
283
+ if (child.type !== 'JSXExpressionContainer') {
284
+ continue;
285
+ }
286
+ const empty = isEmpty(child, code);
287
+ const value = empty ? undefined : readString(child, code);
288
+ if (!empty && (value === undefined || !isPlainText(value))) {
289
+ continue;
290
+ }
291
+ // Without the braces, the texts on both sides meet, and a string joins them as text.
292
+ const before = parts[index];
293
+ parts[index] = empty ? undefined : { raw: value ?? '' };
294
+ if (render(parts, inElement) === expected) {
295
+ if (empty) {
296
+ s.remove(child.start, child.end);
297
+ } else {
298
+ unwrapString(child, '', '', context);
299
+ }
300
+ changed = true;
301
+ } else {
302
+ parts[index] = before;
303
+ }
304
+ }
305
+ return changed;
306
+ }
307
+
308
+ /** The one element a fragment holds, when everything else in it is line breaks or empty braces. */
309
+ function findOnlyElement(fragment: JSXFragment, code: string): JSXElement | undefined {
310
+ let only: JSXElement | undefined;
311
+ for (const child of fragment.children) {
312
+ if (child.type === 'JSXElement') {
313
+ if (only) {
314
+ return undefined;
315
+ }
316
+ only = child;
317
+ } else if (child.type === 'JSXText') {
318
+ // Spaces without a line break are text: `<> <b /></>` renders a space.
319
+ if (!/^[ \t\r\n]*$/.test(child.value) || cleanText(child.value) !== '') {
320
+ return undefined;
321
+ }
322
+ } else if (!(child.type === 'JSXExpressionContainer' && isEmpty(child, code))) {
323
+ return undefined;
324
+ }
325
+ }
326
+ return only;
327
+ }
328
+
329
+ function tidyAttribute(attribute: JSXAttribute, context: PassContext): boolean {
330
+ const { value } = attribute;
331
+ if (value?.type !== 'JSXExpressionContainer' || !isTidyAttribute(attribute)) {
332
+ return false;
333
+ }
334
+ const text = readString(value, context.code);
335
+ if (text === undefined || !isPlainAttribute(text)) {
336
+ return false;
337
+ }
338
+ unwrapString(value, '"', '"', context);
339
+ return true;
340
+ }
341
+
342
+ /**
343
+ * Whether a fragment is a branch of `? :`, or the right side of `&&`, `||`
344
+ * or `??`, where the lowering of `<Show>` and `<Switch>` leaves them. There a
345
+ * fragment around one element lowers the same as the element. Elsewhere,
346
+ * such as a function's return, Solid's JSX transform writes different code.
347
+ */
348
+ function isBranch(fragment: JSXFragment, context: PassContext): boolean {
349
+ let node: Node = fragment;
350
+ let parent = context.parents.get(node);
351
+ while (parent?.type === 'ParenthesizedExpression') {
352
+ node = parent;
353
+ parent = context.parents.get(node);
354
+ }
355
+ if (parent?.type === 'ConditionalExpression') {
356
+ return parent.consequent === node || parent.alternate === node;
357
+ }
358
+ return parent?.type === 'LogicalExpression' && parent.right === node;
359
+ }
360
+
361
+ export function tidyJSX(context: PassContext): boolean {
362
+ let changed = false;
363
+ const visit = (node: Node): void => {
364
+ if (node.type === 'JSXFragment' && isBranch(node, context)) {
365
+ const only = findOnlyElement(node, context.code);
366
+ if (only) {
367
+ // Everything around the element is line breaks or empty braces, so it all goes.
368
+ context.s.remove(node.start, only.start);
369
+ context.s.remove(only.end, node.end);
370
+ changed = true;
371
+ visit(only);
372
+ return;
373
+ }
374
+ }
375
+ const childrenFixed = node.type === 'JSXElement' && hasChildrenAttribute(node);
376
+ if ((node.type === 'JSXElement' || node.type === 'JSXFragment') && !childrenFixed) {
377
+ const inElement = node.type === 'JSXElement' && isIntrinsic(node);
378
+ if (tidyChildren(node.children, inElement, context)) {
379
+ changed = true;
380
+ }
381
+ }
382
+ if (node.type === 'JSXAttribute' && tidyAttribute(node, context)) {
383
+ changed = true;
384
+ return;
385
+ }
386
+ forEachChild(node, visit);
387
+ };
388
+ visit(context.program);
389
+ return changed;
390
+ }