solid-optimizer 0.2.0 → 0.4.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.
Files changed (53) hide show
  1. package/README.md +294 -14
  2. package/dist/compile-BQuBDA0Q.d.mts +199 -0
  3. package/dist/compile-BQuBDA0Q.d.mts.map +1 -0
  4. package/dist/compile-D3caSUtw.mjs +4244 -0
  5. package/dist/compile-D3caSUtw.mjs.map +1 -0
  6. package/dist/index.d.mts +2 -0
  7. package/dist/index.mjs +2 -0
  8. package/dist/vite.d.mts +53 -0
  9. package/dist/vite.d.mts.map +1 -0
  10. package/dist/vite.mjs +1743 -0
  11. package/dist/vite.mjs.map +1 -0
  12. package/package.json +60 -58
  13. package/src/ast.ts +271 -0
  14. package/src/compile.ts +355 -0
  15. package/src/constants.ts +249 -0
  16. package/src/context.ts +116 -0
  17. package/src/fold.ts +850 -0
  18. package/src/index.ts +5 -107
  19. package/src/inline.ts +2237 -0
  20. package/src/jsx.ts +170 -0
  21. package/src/memo.ts +416 -0
  22. package/src/provider.ts +899 -0
  23. package/src/scope.ts +588 -0
  24. package/src/server.ts +275 -0
  25. package/src/size.ts +309 -0
  26. package/src/value.ts +386 -0
  27. package/src/vite/index.ts +1378 -0
  28. package/src/vite/inject.ts +350 -0
  29. package/src/vite/namespace.ts +66 -0
  30. package/src/vite/refs.ts +99 -0
  31. package/src/vite/report.ts +74 -0
  32. package/src/vite/runtime.ts +370 -0
  33. package/src/vite/usage.ts +405 -0
  34. package/dist/cjs/development/index.cjs +0 -228
  35. package/dist/cjs/development/index.cjs.map +0 -7
  36. package/dist/cjs/production/index.cjs +0 -1
  37. package/dist/esm/development/index.mjs +0 -197
  38. package/dist/esm/development/index.mjs.map +0 -7
  39. package/dist/esm/production/index.mjs +0 -1
  40. package/dist/types/checks.d.ts +0 -9
  41. package/dist/types/checks.d.ts.map +0 -1
  42. package/dist/types/index.d.ts +0 -3
  43. package/dist/types/index.d.ts.map +0 -1
  44. package/dist/types/path-references-import.d.ts +0 -3
  45. package/dist/types/path-references-import.d.ts.map +0 -1
  46. package/dist/types/unwrap-node.d.ts +0 -7
  47. package/dist/types/unwrap-node.d.ts.map +0 -1
  48. package/dist/types/unwrap-path.d.ts +0 -6
  49. package/dist/types/unwrap-path.d.ts.map +0 -1
  50. package/src/checks.ts +0 -42
  51. package/src/path-references-import.ts +0 -82
  52. package/src/unwrap-node.ts +0 -27
  53. package/src/unwrap-path.ts +0 -18
package/src/fold.ts ADDED
@@ -0,0 +1,850 @@
1
+ /**
2
+ * The fold pass: constant folding, dead-code elimination, and static
3
+ * resolution of Solid's control-flow components.
4
+ *
5
+ * It runs on JSX before it is lowered, so whatever it resolves never reaches
6
+ * the JSX transform. A `<Show>` whose condition is a constant becomes its
7
+ * branch, and the branch joins the surrounding template instead of paying for
8
+ * a component call, a memo, and an insert.
9
+ *
10
+ * It follows the `optimize` option of Solid 2.0's `@solidjs/compiler`
11
+ * (https://github.com/solidjs/solid/pull/3231), applied to Solid 1's
12
+ * control-flow components.
13
+ *
14
+ * # What folds
15
+ *
16
+ * - Constant expressions: literals, template literals, and the unary, binary,
17
+ * logical, and conditional operators over them.
18
+ * - `const` bindings, and `let` bindings nothing writes to, at any scope.
19
+ * - Statements a constant condition makes unreachable: `if`/`else` branches,
20
+ * `while (false)` loops, and anything after a `return`, `throw`, `break`,
21
+ * or `continue`.
22
+ * - `<Show when>`, `<For each>`, `<Index each>`, `<Switch>`/`<Match when>`,
23
+ * and `<Dynamic component>` with a static intrinsic tag name.
24
+ *
25
+ * # What does not fold
26
+ *
27
+ * `<Portal>`, `<Suspense>`, `<SuspenseList>`, and `<ErrorBoundary>` exist for
28
+ * a runtime condition no static analysis can decide. A control-flow component with a
29
+ * spread attribute is left alone, since the spread can supply or override the
30
+ * prop the fold reads. Function children also stop a fold, since the runtime
31
+ * decides from their arity whether to call them.
32
+ */
33
+ import type {
34
+ CallExpression,
35
+ ConditionalExpression,
36
+ Directive,
37
+ Expression,
38
+ IfStatement,
39
+ JSXChild,
40
+ JSXElement,
41
+ JSXFragment,
42
+ LogicalExpression,
43
+ Node,
44
+ Statement,
45
+ WhileStatement,
46
+ } from 'oxc-parser';
47
+ import type { Parents } from './ast';
48
+ import {
49
+ forEachChild,
50
+ isInsignificant,
51
+ isIntrinsicTag,
52
+ isJSXChild,
53
+ isPrimary,
54
+ needsParensAt,
55
+ startsLikeStatement,
56
+ } from './ast';
57
+ import type { PassContext } from './context';
58
+ import { ConstantTable } from './constants';
59
+ import { solidExport, textOf } from './context';
60
+ import type { Piece } from './jsx';
61
+ import {
62
+ findAttribute,
63
+ hasCallbackChild,
64
+ hasSpreadAttribute,
65
+ innerText,
66
+ keptPiece,
67
+ replacedPiece,
68
+ splicePiece,
69
+ writePieces,
70
+ } from './jsx';
71
+ import type { ConstantLookup } from './value';
72
+ import {
73
+ arrayLiteralLength,
74
+ effectfulParts,
75
+ evaluate,
76
+ isLiteralForm,
77
+ isSideEffectFree,
78
+ literalText,
79
+ truthiness,
80
+ } from './value';
81
+
82
+ /**
83
+ * The control-flow components this pass resolves.
84
+ * `Match` is absent: it only has meaning inside a `<Switch>`, which folds it.
85
+ */
86
+ const FOLDABLE_FLOW = new Set(['Show', 'For', 'Index', 'Switch', 'Dynamic']);
87
+
88
+ /**
89
+ * What a resolved control-flow element renders in its place.
90
+ */
91
+ type Fold =
92
+ /** JSX children, spliced in. */
93
+ | { readonly kind: 'children'; readonly children: readonly JSXChild[] }
94
+ /** An element or fragment, as source text. */
95
+ | { readonly kind: 'jsx'; readonly text: string }
96
+ /** An expression, such as a `fallback` prop's value. */
97
+ | {
98
+ readonly kind: 'expression';
99
+ readonly text: string;
100
+ readonly primary: boolean;
101
+ }
102
+ | { readonly kind: 'empty' };
103
+
104
+ const EMPTY: Fold = { kind: 'empty' };
105
+
106
+ /** Solid's calls that only create a value, so the bundler can drop an unused one. */
107
+ const PURE_CALLS = new Set(['lazy', 'createContext']);
108
+
109
+ /**
110
+ * The globals worth folding. They only apply to a reference that binds to
111
+ * nothing, which is when the global is what runs.
112
+ */
113
+ /**
114
+ * Whether `node` is written to: assigned, updated, deleted, or destructured into.
115
+ */
116
+ function isWriteTarget(node: Node, parents: Parents): boolean {
117
+ let current = node;
118
+ let parent = parents.get(current);
119
+ // A destructuring pattern writes to every target inside it.
120
+ while (
121
+ parent &&
122
+ (parent.type === 'ArrayPattern' ||
123
+ parent.type === 'ObjectPattern' ||
124
+ parent.type === 'RestElement' ||
125
+ parent.type === 'AssignmentPattern' ||
126
+ (parent.type === 'Property' && parents.get(parent)?.type === 'ObjectPattern'))
127
+ ) {
128
+ if (parent.type === 'AssignmentPattern' && parent.left !== current) {
129
+ return false;
130
+ }
131
+ current = parent;
132
+ parent = parents.get(current);
133
+ }
134
+ if (!parent) {
135
+ return false;
136
+ }
137
+ switch (parent.type) {
138
+ case 'AssignmentExpression':
139
+ return parent.left === current;
140
+ case 'UpdateExpression':
141
+ return true;
142
+ case 'UnaryExpression':
143
+ return parent.operator === 'delete';
144
+ case 'ForInStatement':
145
+ case 'ForOfStatement':
146
+ return parent.left === current;
147
+ default:
148
+ return current !== node;
149
+ }
150
+ }
151
+
152
+ function isTerminator(statement: Node): boolean {
153
+ return (
154
+ statement.type === 'ReturnStatement' ||
155
+ statement.type === 'ThrowStatement' ||
156
+ statement.type === 'BreakStatement' ||
157
+ statement.type === 'ContinueStatement'
158
+ );
159
+ }
160
+
161
+ /**
162
+ * Whether removing `statement` would remove a `var` or function declaration
163
+ * that is hoisted out of it. Nested functions are their own scope.
164
+ */
165
+ function containsHoistedDeclaration(statement: Node): boolean {
166
+ let found = false;
167
+ const visit = (node: Node): void => {
168
+ if (found) {
169
+ return;
170
+ }
171
+ if (node.type === 'VariableDeclaration' && node.kind === 'var') {
172
+ found = true;
173
+ return;
174
+ }
175
+ if (node.type === 'FunctionDeclaration') {
176
+ found = true;
177
+ return;
178
+ }
179
+ if (
180
+ node.type === 'FunctionExpression' ||
181
+ node.type === 'ArrowFunctionExpression' ||
182
+ node.type === 'ClassDeclaration' ||
183
+ node.type === 'ClassExpression'
184
+ ) {
185
+ return;
186
+ }
187
+ forEachChild(node, visit);
188
+ };
189
+ visit(statement);
190
+ return found;
191
+ }
192
+
193
+ /**
194
+ * Whether a statement starting with `text` could join the statement before
195
+ * it when that one has no semicolon.
196
+ */
197
+ function continuesPreviousStatement(text: string): boolean {
198
+ return /^[([`+\-/]/.test(text);
199
+ }
200
+
201
+ class Folder {
202
+ changed = false;
203
+
204
+ private readonly lookup: ConstantLookup;
205
+
206
+ constructor(private readonly context: PassContext) {
207
+ this.lookup = new ConstantTable(context.scopes, context.options).lookup;
208
+ }
209
+
210
+ // ---------------------------------------------------------------------------
211
+ // Traversal
212
+ // ---------------------------------------------------------------------------
213
+
214
+ walk(node: Node): void {
215
+ forEachChild(node, (child) => {
216
+ this.walk(child);
217
+ });
218
+ this.exit(node);
219
+ }
220
+
221
+ private exit(node: Node): void {
222
+ switch (node.type) {
223
+ case 'Program':
224
+ case 'BlockStatement':
225
+ case 'StaticBlock':
226
+ this.eliminateDeadStatements(node.body);
227
+ break;
228
+ case 'SwitchCase':
229
+ this.eliminateDeadStatements(node.consequent);
230
+ break;
231
+ case 'JSXElement':
232
+ this.foldChildren(node);
233
+ if (!this.isJSXChildOrAttribute(node)) {
234
+ this.foldFlowExpression(node);
235
+ }
236
+ break;
237
+ case 'JSXFragment':
238
+ this.foldChildren(node);
239
+ break;
240
+ case 'LogicalExpression':
241
+ this.foldLogical(node);
242
+ break;
243
+ case 'ConditionalExpression':
244
+ this.foldConditional(node);
245
+ break;
246
+ case 'Identifier':
247
+ if (this.context.scopes.references.has(node)) {
248
+ this.foldConstant(node);
249
+ }
250
+ break;
251
+ case 'TemplateLiteral':
252
+ // A tagged template passes its strings to the tag, so they are not constants.
253
+ if (this.context.parents.get(node)?.type !== 'TaggedTemplateExpression') {
254
+ this.foldConstant(node);
255
+ }
256
+ break;
257
+ case 'UnaryExpression':
258
+ case 'BinaryExpression':
259
+ case 'ParenthesizedExpression':
260
+ this.foldConstant(node);
261
+ break;
262
+ case 'MemberExpression':
263
+ // Only a read folds. Writing to a namespace member throws, so it stays.
264
+ if (!isWriteTarget(node, this.context.parents)) {
265
+ this.foldConstant(node);
266
+ }
267
+ break;
268
+ case 'CallExpression':
269
+ this.annotatePure(node);
270
+ break;
271
+ default:
272
+ break;
273
+ }
274
+ }
275
+
276
+ private isJSXChildOrAttribute(node: Node): boolean {
277
+ return (
278
+ isJSXChild(node, this.context.parents) ||
279
+ this.context.parents.get(node)?.type === 'JSXAttribute'
280
+ );
281
+ }
282
+
283
+ private replace(node: Node, text: string): void {
284
+ if (textOf(this.context, node) === text) {
285
+ return;
286
+ }
287
+ this.context.s.overwrite(node.start, node.end, text);
288
+ this.changed = true;
289
+ }
290
+
291
+ // ---------------------------------------------------------------------------
292
+ // Expressions
293
+ // ---------------------------------------------------------------------------
294
+
295
+ /**
296
+ * Marks a call to Solid's `lazy` or `createContext` as pure. `lazy` only
297
+ * creates the component, and loads nothing until it renders. A folded
298
+ * branch can leave it unused, and the annotation lets the bundler drop it
299
+ * along with its dynamic import. `createContext` only creates the context,
300
+ * which inlining can leave unused.
301
+ */
302
+ private annotatePure(call: CallExpression): void {
303
+ if (call.callee.type !== 'Identifier') {
304
+ return;
305
+ }
306
+ const binding = this.context.scopes.references.get(call.callee);
307
+ const identity = binding ? solidExport(binding, this.context.options) : undefined;
308
+ if (identity === undefined || !PURE_CALLS.has(identity)) {
309
+ return;
310
+ }
311
+ const before = this.context.code.slice(0, call.start).trimEnd();
312
+ if (/(#|@)__PURE__\s*\*\/$/.test(before)) {
313
+ return;
314
+ }
315
+ this.context.s.prependLeft(call.start, '/* @__PURE__ */ ');
316
+ this.changed = true;
317
+ }
318
+
319
+ private foldConstant(node: Node): void {
320
+ if (isLiteralForm(node)) {
321
+ return;
322
+ }
323
+ const value = evaluate(node, this.lookup);
324
+ if (!value) {
325
+ return;
326
+ }
327
+ let text = literalText(value.value);
328
+ if (text === undefined) {
329
+ return;
330
+ }
331
+ const parent = this.context.parents.get(node);
332
+ if (node.type === 'Identifier') {
333
+ // `export { A }` names the binding, not its value.
334
+ if (parent?.type === 'ExportSpecifier') {
335
+ return;
336
+ }
337
+ // `{ enabled }` cannot stay shorthand once its value is a literal.
338
+ if (parent?.type === 'Property' && parent.shorthand) {
339
+ this.replace(node, `${node.name}: ${text}`);
340
+ return;
341
+ }
342
+ }
343
+ if (
344
+ parent?.type === 'MemberExpression' &&
345
+ parent.object === node &&
346
+ typeof value.value === 'number' &&
347
+ !text.startsWith('(')
348
+ ) {
349
+ // `1.toFixed()` does not parse.
350
+ text = `(${text})`;
351
+ }
352
+ if (parent?.type === 'ExpressionStatement' && typeof value.value === 'string') {
353
+ // A string at the start of a statement can turn into a directive.
354
+ text = `(${text})`;
355
+ }
356
+ this.replace(node, text);
357
+ }
358
+
359
+ /**
360
+ * Keeps `value`, evaluating `discarded` first when it has side effects.
361
+ * `(discarded, value)` runs it in the same order and yields the same result.
362
+ */
363
+ private keepAfter(target: Node, discarded: Expression | undefined, value: Expression): string {
364
+ const parts = discarded ? effectfulParts(discarded) : [];
365
+ if (parts.length === 0) {
366
+ const text = textOf(this.context, value);
367
+ return needsParensAt(target, value, this.context.parents) ? `(${text})` : text;
368
+ }
369
+ const texts = parts.map((part) => textOf(this.context, part));
370
+ texts.push(textOf(this.context, value));
371
+ return `(${texts.join(', ')})`;
372
+ }
373
+
374
+ private foldLogical(node: LogicalExpression): void {
375
+ const left = truthiness(node.left, this.lookup);
376
+ if (left === undefined) {
377
+ return;
378
+ }
379
+ let takesLeft: boolean;
380
+ if (node.operator === '&&') {
381
+ takesLeft = !left;
382
+ } else if (node.operator === '||') {
383
+ takesLeft = left;
384
+ } else {
385
+ // `??` depends on nullishness, not truthiness, so it only folds against a constant.
386
+ const value = evaluate(node.left, this.lookup);
387
+ if (!value) {
388
+ return;
389
+ }
390
+ takesLeft = value.value != null;
391
+ }
392
+ // The side a short-circuit never reaches never runs, so dropping it is free.
393
+ // The side that does run has to be skippable before the other replaces it.
394
+ if (takesLeft) {
395
+ this.replace(node, this.keepAfter(node, undefined, node.left));
396
+ } else {
397
+ const discarded = this.isSkippable(node.left) ? undefined : node.left;
398
+ this.replace(node, this.keepAfter(node, discarded, node.right));
399
+ }
400
+ }
401
+
402
+ /**
403
+ * Whether dropping `node` changes nothing. An expression that evaluates to
404
+ * a constant only reads bindings and runs operators on primitives.
405
+ */
406
+ private isSkippable(node: Expression): boolean {
407
+ return isSideEffectFree(node) || evaluate(node, this.lookup) !== undefined;
408
+ }
409
+
410
+ private foldConditional(node: ConditionalExpression): void {
411
+ const test = truthiness(node.test, this.lookup);
412
+ if (test === undefined) {
413
+ return;
414
+ }
415
+ const discarded = this.isSkippable(node.test) ? undefined : node.test;
416
+ this.replace(node, this.keepAfter(node, discarded, test ? node.consequent : node.alternate));
417
+ }
418
+
419
+ // ---------------------------------------------------------------------------
420
+ // Control-flow components
421
+ // ---------------------------------------------------------------------------
422
+
423
+ /**
424
+ * The Solid built-in a tag refers to.
425
+ *
426
+ * Being in `builtIns` only makes a name a candidate. The tag has to resolve
427
+ * to Solid's own component: a tag that binds to nothing is the built-in the
428
+ * JSX transform imports, and an import from a Solid module is decided by
429
+ * the name the module exports, so `<Cond>` from `import { Show as Cond }` is
430
+ * `Show`. A local `Show` or one from another module is a different component.
431
+ */
432
+ private builtInTag(element: JSXElement): string | undefined {
433
+ const { name } = element.openingElement;
434
+ if (name.type !== 'JSXIdentifier') {
435
+ return undefined;
436
+ }
437
+ const { references } = this.context.scopes;
438
+ if (!references.has(name)) {
439
+ return undefined;
440
+ }
441
+ const binding = references.get(name);
442
+ const identity = binding ? solidExport(binding, this.context.options) : name.name;
443
+ if (identity === undefined || !this.context.options.builtIns.has(identity)) {
444
+ return undefined;
445
+ }
446
+ return identity;
447
+ }
448
+
449
+ private flowTag(element: JSXElement): string | undefined {
450
+ const tag = this.builtInTag(element);
451
+ return tag !== undefined && FOLDABLE_FLOW.has(tag) ? tag : undefined;
452
+ }
453
+
454
+ private foldFlow(element: JSXElement): Fold | undefined {
455
+ const tag = this.flowTag(element);
456
+ if (tag === undefined || hasSpreadAttribute(element)) {
457
+ return undefined;
458
+ }
459
+ switch (tag) {
460
+ case 'Show':
461
+ return this.foldShow(element);
462
+ case 'For':
463
+ case 'Index':
464
+ return this.foldFor(element);
465
+ case 'Switch':
466
+ return this.foldSwitch(element);
467
+ case 'Dynamic':
468
+ return this.foldDynamic(element);
469
+ default:
470
+ return undefined;
471
+ }
472
+ }
473
+
474
+ /**
475
+ * Whether a prop is statically truthy or falsy. A bare attribute is `true`.
476
+ * The prop is discarded by the fold, so it also has to be skippable.
477
+ */
478
+ private attributeTruthiness(element: JSXElement, name: string): boolean | undefined {
479
+ const attribute = findAttribute(element, name);
480
+ if (!attribute) {
481
+ return undefined;
482
+ }
483
+ const { value } = attribute;
484
+ if (value === null) {
485
+ return true;
486
+ }
487
+ switch (value.type) {
488
+ case 'Literal':
489
+ return value.value !== '';
490
+ case 'JSXElement':
491
+ case 'JSXFragment':
492
+ return true;
493
+ default:
494
+ if (value.expression.type === 'JSXEmptyExpression' || !isSideEffectFree(value.expression)) {
495
+ return undefined;
496
+ }
497
+ return truthiness(value.expression, this.lookup);
498
+ }
499
+ }
500
+
501
+ /**
502
+ * What the element renders when its condition fails: its `fallback` prop, or nothing.
503
+ */
504
+ private fallback(element: JSXElement): Fold | undefined {
505
+ const attribute = findAttribute(element, 'fallback');
506
+ if (!attribute?.value) {
507
+ // A bare `fallback` is `fallback={true}`, which renders nothing.
508
+ return EMPTY;
509
+ }
510
+ const { value } = attribute;
511
+ switch (value.type) {
512
+ case 'Literal':
513
+ // An attribute string can hold HTML entities, which are not decoded here.
514
+ if (value.value.includes('&')) {
515
+ return undefined;
516
+ }
517
+ return {
518
+ kind: 'expression',
519
+ text: JSON.stringify(value.value),
520
+ primary: true,
521
+ };
522
+ case 'JSXElement':
523
+ case 'JSXFragment':
524
+ return { kind: 'jsx', text: textOf(this.context, value) };
525
+ default:
526
+ if (value.expression.type === 'JSXEmptyExpression') {
527
+ return EMPTY;
528
+ }
529
+ // JSX in a container splices like JSX, so it can join the surrounding template.
530
+ if (value.expression.type === 'JSXElement' || value.expression.type === 'JSXFragment') {
531
+ return { kind: 'jsx', text: textOf(this.context, value.expression) };
532
+ }
533
+ return {
534
+ kind: 'expression',
535
+ text: textOf(this.context, value.expression),
536
+ primary: isPrimary(value.expression),
537
+ };
538
+ }
539
+ }
540
+
541
+ private foldShow(element: JSXElement): Fold | undefined {
542
+ const when = this.attributeTruthiness(element, 'when');
543
+ if (when === undefined) {
544
+ return undefined;
545
+ }
546
+ if (!when) {
547
+ return this.fallback(element);
548
+ }
549
+ if (hasCallbackChild(element.children)) {
550
+ return undefined;
551
+ }
552
+ return { kind: 'children', children: element.children };
553
+ }
554
+
555
+ private foldFor(element: JSXElement): Fold | undefined {
556
+ const each = findAttribute(element, 'each');
557
+ if (
558
+ each?.value?.type !== 'JSXExpressionContainer' ||
559
+ each.value.expression.type === 'JSXEmptyExpression'
560
+ ) {
561
+ return undefined;
562
+ }
563
+ const { expression } = each.value;
564
+ // `each={[]}` renders the fallback, and so does a statically falsy `each`,
565
+ // which `mapArray` and `indexArray` treat as an empty list. Either way the expression is
566
+ // dropped, so it has to be skippable.
567
+ const empty =
568
+ arrayLiteralLength(expression) === 0 || truthiness(expression, this.lookup) === false;
569
+ if (!empty || !isSideEffectFree(expression)) {
570
+ return undefined;
571
+ }
572
+ return this.fallback(element);
573
+ }
574
+
575
+ /**
576
+ * Resolves a `<Switch>` as far as its `<Match when>` conditions allow.
577
+ * Statically false matches are dropped, a statically true match with no
578
+ * undecided match before it wins, and a switch whose every match is false
579
+ * renders its fallback.
580
+ */
581
+ private foldSwitch(element: JSXElement): Fold | undefined {
582
+ const matches: { element: JSXElement; when: boolean | undefined }[] = [];
583
+ for (const child of element.children) {
584
+ if (isInsignificant(child)) {
585
+ continue;
586
+ }
587
+ // Anything else in a `<Switch>` is outside what this pass models.
588
+ if (
589
+ child.type !== 'JSXElement' ||
590
+ this.builtInTag(child) !== 'Match' ||
591
+ hasSpreadAttribute(child) ||
592
+ !findAttribute(child, 'when')
593
+ ) {
594
+ return undefined;
595
+ }
596
+ matches.push({ element: child, when: this.attributeTruthiness(child, 'when') });
597
+ }
598
+ if (matches.length === 0) {
599
+ return undefined;
600
+ }
601
+
602
+ const winner = matches.findIndex((item) => item.when === true);
603
+ if (winner !== -1 && matches.slice(0, winner).every((item) => item.when === false)) {
604
+ const match = matches.at(winner);
605
+ if (!match || hasCallbackChild(match.element.children)) {
606
+ return undefined;
607
+ }
608
+ return { kind: 'children', children: match.element.children };
609
+ }
610
+
611
+ if (matches.every((item) => item.when === false)) {
612
+ return this.fallback(element);
613
+ }
614
+
615
+ // No outcome yet. A statically false match never renders, but the runtime
616
+ // would still evaluate it each time the switch updates, so it is removed.
617
+ for (const item of matches) {
618
+ if (item.when === false) {
619
+ this.context.s.remove(item.element.start, item.element.end);
620
+ this.changed = true;
621
+ }
622
+ }
623
+ return undefined;
624
+ }
625
+
626
+ /**
627
+ * `<Dynamic component="div">` is just `<div>`, which the JSX transform can
628
+ * put in a template instead of creating the element at runtime.
629
+ */
630
+ private foldDynamic(element: JSXElement): Fold | undefined {
631
+ const component = findAttribute(element, 'component');
632
+ if (!component?.value) {
633
+ return undefined;
634
+ }
635
+ let tag: string | undefined;
636
+ const { value } = component;
637
+ if (value.type === 'Literal') {
638
+ tag = value.value;
639
+ } else if (
640
+ value.type === 'JSXExpressionContainer' &&
641
+ value.expression.type !== 'JSXEmptyExpression'
642
+ ) {
643
+ const result = evaluate(value.expression, this.lookup);
644
+ if (typeof result?.value === 'string') {
645
+ tag = result.value;
646
+ }
647
+ }
648
+ if (tag === undefined || !isIntrinsicTag(tag)) {
649
+ return undefined;
650
+ }
651
+ const attributes = element.openingElement.attributes
652
+ .filter((attribute) => attribute !== component)
653
+ .map((attribute) => textOf(this.context, attribute));
654
+ const opening = [tag, ...attributes].join(' ');
655
+ const text = element.closingElement
656
+ ? `<${opening}>${innerText(this.context.s, element)}</${tag}>`
657
+ : `<${opening} />`;
658
+ return { kind: 'jsx', text };
659
+ }
660
+
661
+ /**
662
+ * Replaces a control-flow element that is not a JSX child.
663
+ */
664
+ private foldFlowExpression(element: JSXElement): void {
665
+ const resolved = this.foldFlow(element);
666
+ if (!resolved) {
667
+ return;
668
+ }
669
+ this.replace(element, this.expressionText(resolved));
670
+ }
671
+
672
+ private expressionText(resolved: Fold): string {
673
+ switch (resolved.kind) {
674
+ case 'empty':
675
+ return 'null';
676
+ case 'jsx':
677
+ return resolved.text;
678
+ case 'expression':
679
+ return resolved.primary ? resolved.text : `(${resolved.text})`;
680
+ default: {
681
+ const significant = resolved.children.filter((child) => !isInsignificant(child));
682
+ const only = significant.at(0);
683
+ if (only === undefined) {
684
+ return 'null';
685
+ }
686
+ if (
687
+ significant.length === 1 &&
688
+ (only.type === 'JSXElement' || only.type === 'JSXFragment')
689
+ ) {
690
+ return textOf(this.context, only);
691
+ }
692
+ const first = resolved.children.at(0);
693
+ const last = resolved.children.at(-1);
694
+ if (!first || !last) {
695
+ return 'null';
696
+ }
697
+ return `<>${this.context.s.slice(first.start, last.end)}</>`;
698
+ }
699
+ }
700
+ }
701
+
702
+ /**
703
+ * Replaces every resolvable control-flow child with what it renders.
704
+ */
705
+ private foldChildren(parent: JSXElement | JSXFragment): void {
706
+ const pieces: Piece[] = [];
707
+ let folded = false;
708
+ for (const child of parent.children) {
709
+ // A fragment among JSX children is the same as its children, and Solid's
710
+ // JSX transform only compiles the spliced form.
711
+ if (child.type === 'JSXFragment') {
712
+ folded = true;
713
+ pieces.push(splicePiece(this.context.s, child, child.children));
714
+ continue;
715
+ }
716
+ const resolved = child.type === 'JSXElement' ? this.foldFlow(child) : undefined;
717
+ if (!resolved) {
718
+ pieces.push(keptPiece(child));
719
+ continue;
720
+ }
721
+ folded = true;
722
+ switch (resolved.kind) {
723
+ case 'children':
724
+ pieces.push(splicePiece(this.context.s, child, resolved.children));
725
+ break;
726
+ case 'jsx':
727
+ pieces.push(replacedPiece(child, resolved.text));
728
+ break;
729
+ case 'expression':
730
+ pieces.push(replacedPiece(child, `{${resolved.text}}`));
731
+ break;
732
+ default:
733
+ pieces.push(replacedPiece(child, ''));
734
+ break;
735
+ }
736
+ }
737
+ if (folded && writePieces(this.context.s, pieces)) {
738
+ this.changed = true;
739
+ }
740
+ }
741
+
742
+ // ---------------------------------------------------------------------------
743
+ // Dead statements
744
+ // ---------------------------------------------------------------------------
745
+
746
+ private eliminateDeadStatements(statements: (Statement | Directive)[]): void {
747
+ let terminator = -1;
748
+ for (const [index, statement] of statements.entries()) {
749
+ let terminates = isTerminator(statement);
750
+ if (statement.type === 'IfStatement') {
751
+ const kept = this.resolveIf(statement);
752
+ if (kept !== undefined) {
753
+ terminates = kept !== null && isTerminator(kept);
754
+ }
755
+ } else if (statement.type === 'WhileStatement') {
756
+ this.resolveWhile(statement);
757
+ }
758
+ if (terminates && terminator === -1) {
759
+ terminator = index;
760
+ }
761
+ }
762
+
763
+ // Everything after the first terminator is unreachable, but a `var` or
764
+ // function declaration in it is still hoisted, so the list stays intact.
765
+ if (terminator === -1) {
766
+ return;
767
+ }
768
+ const unreachable = statements.slice(terminator + 1);
769
+ const first = unreachable.at(0);
770
+ const last = unreachable.at(-1);
771
+ if (first && last && !unreachable.some(containsHoistedDeclaration)) {
772
+ this.context.s.remove(first.start, last.end);
773
+ this.changed = true;
774
+ }
775
+ }
776
+
777
+ private replaceStatement(statement: Node, text: string): void {
778
+ if (text === '') {
779
+ this.context.s.remove(statement.start, statement.end);
780
+ this.changed = true;
781
+ return;
782
+ }
783
+ this.replace(statement, continuesPreviousStatement(text) ? `;${text}` : text);
784
+ }
785
+
786
+ /**
787
+ * A statement that keeps a discarded test's side effects, or `undefined`
788
+ * when skipping the test changes nothing.
789
+ */
790
+ private discardedTest(test: Expression): string | undefined {
791
+ const parts = effectfulParts(test);
792
+ const first = parts.at(0);
793
+ if (first === undefined) {
794
+ return undefined;
795
+ }
796
+ const text = parts.map((part) => textOf(this.context, part)).join(', ');
797
+ return startsLikeStatement(first) ? `(${text});` : `${text};`;
798
+ }
799
+
800
+ /**
801
+ * Resolves an `if` with a constant test. Returns the kept branch, `null`
802
+ * when no branch is kept, or `undefined` when the statement stays.
803
+ */
804
+ private resolveIf(statement: IfStatement): Statement | null | undefined {
805
+ const test = truthiness(statement.test, this.lookup);
806
+ if (test === undefined) {
807
+ return undefined;
808
+ }
809
+ const dropped = test ? statement.alternate : statement.consequent;
810
+ if (dropped && containsHoistedDeclaration(dropped)) {
811
+ return undefined;
812
+ }
813
+ const kept = test ? statement.consequent : statement.alternate;
814
+ // A bare function declaration as a branch is web-compatibility semantics,
815
+ // not something to move into the enclosing list.
816
+ if (kept?.type === 'FunctionDeclaration') {
817
+ return undefined;
818
+ }
819
+ const parts: string[] = [];
820
+ const effect = this.discardedTest(statement.test);
821
+ if (effect !== undefined) {
822
+ parts.push(effect);
823
+ }
824
+ if (kept) {
825
+ parts.push(textOf(this.context, kept));
826
+ }
827
+ this.replaceStatement(statement, parts.join(' '));
828
+ return kept;
829
+ }
830
+
831
+ private resolveWhile(statement: WhileStatement): void {
832
+ if (truthiness(statement.test, this.lookup) !== false) {
833
+ return;
834
+ }
835
+ if (containsHoistedDeclaration(statement.body)) {
836
+ return;
837
+ }
838
+ // A `while` with a falsy test evaluates the test once and never enters the body.
839
+ this.replaceStatement(statement, this.discardedTest(statement.test) ?? '');
840
+ }
841
+ }
842
+
843
+ /**
844
+ * Runs the fold pass over a parsed program. Returns whether anything changed.
845
+ */
846
+ export function fold(context: PassContext): boolean {
847
+ const folder = new Folder(context);
848
+ folder.walk(context.program);
849
+ return folder.changed;
850
+ }