solid-optimizer 1.0.0-next.5 → 1.0.0-next.6

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.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { n as readModuleConstants, t as compile } from "./compile-By9Fecbx.mjs";
1
+ import { n as readModuleConstants, t as compile } from "./compile-DnfP-Quf.mjs";
2
2
  export { compile, readModuleConstants };
package/dist/vite.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { a as lookup, c as forEachChild, d as unwrap, i as analyzeScopes, l as isIntrinsicTag, n as readModuleConstants, o as scopeAt, r as CONTEXT_SAFE_PRIMITIVES, s as collectParents, t as compile, u as parse } from "./compile-By9Fecbx.mjs";
1
+ import { a as lookup, c as forEachChild, d as unwrap, i as analyzeScopes, l as isIntrinsicTag, n as readModuleConstants, o as scopeAt, r as CONTEXT_SAFE_PRIMITIVES, s as collectParents, t as compile, u as parse } from "./compile-DnfP-Quf.mjs";
2
2
  import { createRequire } from "node:module";
3
3
  import remapping from "@jridgewell/remapping";
4
4
  import MagicString from "magic-string";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "solid-optimizer",
3
- "version": "1.0.0-next.5",
3
+ "version": "1.0.0-next.6",
4
4
  "description": "Experimental compile-time optimizer for SolidJS",
5
5
  "keywords": [
6
6
  "compiler",
package/src/fold.ts CHANGED
@@ -119,6 +119,15 @@ const EMPTY: Fold = { kind: 'empty' };
119
119
  /** Solid's calls that only create a value, so the bundler can drop an unused one. */
120
120
  const PURE_CALLS = new Set(['lazy', 'createContext']);
121
121
 
122
+ /**
123
+ * Solid's calls that only create a value when their first argument is not a
124
+ * function. Given a function, they create a computation, which runs it.
125
+ */
126
+ const PURE_VALUE_CALLS = new Set(['createSignal', 'createStore']);
127
+
128
+ /** Expression types that are never a function. */
129
+ const NOT_FUNCTION = new Set(['Literal', 'TemplateLiteral', 'ObjectExpression', 'ArrayExpression']);
130
+
122
131
  /**
123
132
  * The globals worth folding. They only apply to a reference that binds to
124
133
  * nothing, which is when the global is what runs.
@@ -267,6 +276,15 @@ function keyName(node: Node): string | undefined {
267
276
  return node.type === 'Literal' && typeof node.value === 'string' ? node.value : undefined;
268
277
  }
269
278
 
279
+ /** Whether a call has no first argument, or one that is never a function. */
280
+ function isValueArgument(call: CallExpression): boolean {
281
+ if (call.arguments.length === 0) {
282
+ return true;
283
+ }
284
+ const first = call.arguments[0];
285
+ return first.type !== 'SpreadElement' && NOT_FUNCTION.has(unwrap(first).type);
286
+ }
287
+
270
288
  type ConstantItem =
271
289
  | { readonly kind: 'primitive'; readonly text: string }
272
290
  | { readonly kind: 'object'; readonly keys: ReadonlyMap<string, string> };
@@ -432,6 +450,10 @@ class Folder {
432
450
  * branch can leave it unused, and the annotation lets the bundler drop it
433
451
  * along with its dynamic import. `createContext` only creates the context,
434
452
  * which inlining can leave unused.
453
+ *
454
+ * `createSignal` and `createStore` with a first argument that is not a
455
+ * function only create a node. It takes no owner and no hydration id, so
456
+ * dropping an unused one changes nothing else.
435
457
  */
436
458
  private annotatePure(call: CallExpression): void {
437
459
  if (call.callee.type !== 'Identifier') {
@@ -439,7 +461,10 @@ class Folder {
439
461
  }
440
462
  const binding = this.context.scopes.references.get(call.callee);
441
463
  const identity = binding ? solidExport(binding, this.context.options) : undefined;
442
- if (identity === undefined || !PURE_CALLS.has(identity)) {
464
+ if (identity === undefined) {
465
+ return;
466
+ }
467
+ if (!PURE_CALLS.has(identity) && !(PURE_VALUE_CALLS.has(identity) && isValueArgument(call))) {
443
468
  return;
444
469
  }
445
470
  const before = this.context.code.slice(0, call.start).trimEnd();
package/src/memo.ts CHANGED
@@ -44,6 +44,31 @@
44
44
  *
45
45
  * becomes `<div><b>x</b></div>`.
46
46
  *
47
+ * A signal that nothing writes is a constant too. When its setter is left
48
+ * out or never referenced, and its initial value is a literal, every read
49
+ * becomes the literal:
50
+ *
51
+ * ```jsx
52
+ * const [size] = createSignal(3);
53
+ * return <p>{size()}</p>;
54
+ * ```
55
+ *
56
+ * becomes `<p>{3}</p>`. A signal with a value that is not a function takes no
57
+ * owner and no hydration id, so removing it changes nothing else.
58
+ *
59
+ * A plain arrow that only returns an expression, like a derived accessor,
60
+ * has no cache and no owner, so each call already runs its body again. The
61
+ * calls can become the body:
62
+ *
63
+ * ```jsx
64
+ * const label = () => (props.open ? 'Close' : 'Open');
65
+ * return <button>{label()}</button>;
66
+ * ```
67
+ *
68
+ * becomes `<button>{(props.open ? 'Close' : 'Open')}</button>`. With more than
69
+ * one call, the body is copied only when the copies are no larger than the
70
+ * arrow and its calls.
71
+ *
47
72
  * # Accepted differences
48
73
  *
49
74
  * - The computation first runs when its reader first runs, instead of when
@@ -51,6 +76,9 @@
51
76
  * - The memo no longer takes a slot in the owner tree, which shifts the
52
77
  * hydration keys after it. A server build and its client build must
53
78
  * compile with the same options.
79
+ * - A call that runs before the declaration, from a hoisted function the
80
+ * declaration comes before, throws on the original and returns the value
81
+ * on the output.
54
82
  */
55
83
  import type {
56
84
  ArrowFunctionExpression,
@@ -61,12 +89,13 @@ import type {
61
89
  Node,
62
90
  VariableDeclarator,
63
91
  } from 'oxc-parser';
64
- import { isFunctionNode, isIntrinsicTag, unwrap } from './ast';
92
+ import { isFunctionNode, isIntrinsicTag, isPrimary, unwrap } from './ast';
65
93
  import type { PassContext } from './context';
66
94
  import { getText, recordSkip, solidExport } from './context';
67
95
  import { usesFunctionContext } from './inline';
68
96
  import type { Binding } from './scope';
69
97
  import { lookup, scopeAt } from './scope';
98
+ import { compactLength } from './size';
70
99
 
71
100
  /**
72
101
  * Props of Solid's built-in components that are read inside a memo, once per update.
@@ -152,6 +181,9 @@ function returnedExpression(fn: FunctionNode | ArrowFunctionExpression): Express
152
181
  class MemoInliner {
153
182
  changed = false;
154
183
 
184
+ /** Ranges of the source rewritten so far in this run. */
185
+ private readonly edited: [number, number][] = [];
186
+
155
187
  constructor(private readonly context: PassContext) {}
156
188
 
157
189
  /** Why the last memo was turned down, for the report. Empty for a call that is not a memo. */
@@ -225,7 +257,7 @@ class MemoInliner {
225
257
  }
226
258
 
227
259
  /**
228
- * Replaces every read of a memo whose computation is a literal with the
260
+ * Replaces every read of a memo or signal whose value is a literal with the
229
261
  * literal. Each reference has to be a call after the declaration, since a
230
262
  * call before it would throw.
231
263
  */
@@ -233,10 +265,11 @@ class MemoInliner {
233
265
  declarator: VariableDeclarator,
234
266
  binding: Binding,
235
267
  text: string,
268
+ kind: 'memo' | 'signal' = 'memo',
236
269
  ): true | undefined {
237
270
  const statement = this.context.parents.get(declarator);
238
271
  if (statement?.type !== 'VariableDeclaration' || statement.declarations.length !== 1) {
239
- this.reason = 'memo-declaration';
272
+ this.reason = `${kind}-declaration`;
240
273
  return undefined;
241
274
  }
242
275
  const calls: CallExpression[] = [];
@@ -248,7 +281,7 @@ class MemoInliner {
248
281
  call.arguments.length > 0 ||
249
282
  call.start < declarator.end
250
283
  ) {
251
- this.reason = 'memo-constant';
284
+ this.reason = `${kind}-constant`;
252
285
  return undefined;
253
286
  }
254
287
  calls.push(call);
@@ -264,8 +297,10 @@ class MemoInliner {
264
297
  parent?.type === 'Property' ||
265
298
  (parent?.type === 'CallExpression' && parent.callee !== call);
266
299
  this.context.s.overwrite(call.start, call.end, bare ? text : `(${text})`);
300
+ this.edited.push([call.start, call.end]);
267
301
  }
268
302
  this.context.s.remove(statement.start, statement.end);
303
+ this.edited.push([statement.start, statement.end]);
269
304
  this.changed = true;
270
305
  return true;
271
306
  }
@@ -507,30 +542,178 @@ class MemoInliner {
507
542
  if (kind === 'children' && container) {
508
543
  // The JSX takes the place of its container, so it joins the template around it.
509
544
  this.context.s.overwrite(container.start, container.end, getText(this.context, expression));
545
+ this.edited.push([container.start, container.end]);
510
546
  } else {
511
547
  // The read sits in a JSX container, which takes any expression.
512
548
  this.context.s.overwrite(call.start, call.end, getText(this.context, expression));
549
+ this.edited.push([call.start, call.end]);
513
550
  }
514
551
  this.context.s.remove(statement.start, statement.end);
552
+ this.edited.push([statement.start, statement.end]);
515
553
  this.changed = true;
516
554
  return true;
517
555
  }
518
556
 
557
+ /**
558
+ * The literal a signal always holds: `const [get] = createSignal(literal)`,
559
+ * or `const [get, set] = ...` with nothing referencing `set`. Options can
560
+ * change what a read does, such as `unobserved`, so a signal with options
561
+ * stays.
562
+ */
563
+ private signalConstant(declarator: VariableDeclarator, binding: Binding): string | undefined {
564
+ const pattern = declarator.id;
565
+ const init = declarator.init ? unwrap(declarator.init) : undefined;
566
+ if (
567
+ pattern.type !== 'ArrayPattern' ||
568
+ pattern.elements.at(0) !== binding.identifier ||
569
+ pattern.elements.length > 2 ||
570
+ init?.type !== 'CallExpression' ||
571
+ init.callee.type !== 'Identifier' ||
572
+ init.arguments.length !== 1
573
+ ) {
574
+ return undefined;
575
+ }
576
+ const callee = this.context.scopes.references.get(init.callee);
577
+ if (!callee || solidExport(callee, this.context.options) !== 'createSignal') {
578
+ return undefined;
579
+ }
580
+ const value = init.arguments.at(0);
581
+ if (!value || value.type === 'SpreadElement') {
582
+ return undefined;
583
+ }
584
+ // Other modules can read an exported getter.
585
+ const statement = this.context.parents.get(declarator);
586
+ if (statement && this.context.parents.get(statement)?.type === 'ExportNamedDeclaration') {
587
+ return undefined;
588
+ }
589
+ const setter = pattern.elements.at(1);
590
+ if (setter) {
591
+ const setterBinding =
592
+ setter.type === 'Identifier' ? binding.scope.bindings.get(setter.name) : undefined;
593
+ if (setterBinding?.identifier !== setter || setterBinding.references.length > 0) {
594
+ return undefined;
595
+ }
596
+ }
597
+ return constantText(this.context, value);
598
+ }
599
+
600
+ private tryInlineSignal(declarator: VariableDeclarator, binding: Binding): void {
601
+ const text = this.signalConstant(declarator, binding);
602
+ if (text === undefined) {
603
+ return;
604
+ }
605
+ this.reason = '';
606
+ if (this.inlineConstant(declarator, binding, text, 'signal') === undefined) {
607
+ recordSkip(this.context, 'memos', this.reason, binding.name);
608
+ }
609
+ }
610
+
611
+ /**
612
+ * Replaces every call of `const name = () => expression` with the
613
+ * expression. Each reference has to be a call with no arguments after the
614
+ * declaration, and every name in the body has to mean the same at the call.
615
+ */
616
+ private tryInlineArrow(declarator: VariableDeclarator, binding: Binding): void {
617
+ const fn = declarator.init ? unwrap(declarator.init) : undefined;
618
+ if (fn?.type !== 'ArrowFunctionExpression' || fn.async || fn.params.length > 0) {
619
+ return;
620
+ }
621
+ const body = returnedExpression(fn);
622
+ const statement = this.context.parents.get(declarator);
623
+ if (
624
+ !body ||
625
+ statement?.type !== 'VariableDeclaration' ||
626
+ statement.declarations.length !== 1 ||
627
+ // Other modules can call an exported arrow.
628
+ this.context.parents.get(statement)?.type === 'ExportNamedDeclaration'
629
+ ) {
630
+ return;
631
+ }
632
+ const calls: CallExpression[] = [];
633
+ for (const reference of binding.references) {
634
+ const call = this.context.parents.get(reference);
635
+ if (
636
+ call?.type !== 'CallExpression' ||
637
+ call.callee !== reference ||
638
+ call.optional ||
639
+ call.arguments.length > 0 ||
640
+ call.start < declarator.end
641
+ ) {
642
+ // The arrow is used as a value, like an event handler. That is not a derivation.
643
+ return;
644
+ }
645
+ // `l()()` calls the result with no `this`, but `(a.b)()` passes `a`, and
646
+ // `delete (a.b)` deletes what `delete l()` leaves alone.
647
+ const parent = this.context.parents.get(call);
648
+ if (
649
+ (parent?.type === 'CallExpression' && parent.callee === call) ||
650
+ (parent?.type === 'TaggedTemplateExpression' && parent.tag === call) ||
651
+ (parent?.type === 'UnaryExpression' && parent.operator === 'delete')
652
+ ) {
653
+ return;
654
+ }
655
+ calls.push(call);
656
+ }
657
+ if (calls.length === 0) {
658
+ return;
659
+ }
660
+ // The body is copied from the source, so it must not hold an edit from this run.
661
+ // The next round sees the edit.
662
+ for (const [start, end] of this.edited) {
663
+ if (start < statement.end && end > statement.start) {
664
+ return;
665
+ }
666
+ }
667
+ const text = getText(this.context, body);
668
+ // Minified, the arrow costs `const a=()=>body;`, 13 characters besides the
669
+ // body, and each call `a()` costs 3. Copying adds the body to every call
670
+ // but one, and removes the rest.
671
+ const length = compactLength(text);
672
+ if ((calls.length - 1) * length > calls.length * 3 + 13) {
673
+ return;
674
+ }
675
+ if (usesFunctionContext(this.context, fn)) {
676
+ return;
677
+ }
678
+ for (const call of calls) {
679
+ if (!this.resolvesSameAt(body, call, binding)) {
680
+ return;
681
+ }
682
+ }
683
+ const bare = isPrimary(body);
684
+ for (const call of calls) {
685
+ const parent = this.context.parents.get(call);
686
+ const inContainer =
687
+ parent?.type === 'JSXExpressionContainer' && body.type !== 'SequenceExpression';
688
+ this.context.s.overwrite(call.start, call.end, bare || inContainer ? text : `(${text})`);
689
+ this.edited.push([call.start, call.end]);
690
+ }
691
+ this.context.s.remove(statement.start, statement.end);
692
+ this.edited.push([statement.start, statement.end]);
693
+ this.changed = true;
694
+ }
695
+
519
696
  run(): void {
520
697
  for (const scope of new Set(this.context.scopes.scopes.values())) {
521
- // A memo outside any function has no owner, and disposes differently.
522
- if (scope.parent === undefined) {
523
- continue;
524
- }
525
698
  for (const binding of scope.bindings.values()) {
526
699
  const { declaration } = binding;
527
700
  if (
528
- binding.kind === 'const' &&
529
- !binding.mutated &&
530
- declaration.type === 'VariableDeclarator' &&
531
- declaration.id === binding.identifier
701
+ binding.kind !== 'const' ||
702
+ binding.mutated ||
703
+ declaration.type !== 'VariableDeclarator'
532
704
  ) {
533
- this.tryInline(declaration, binding);
705
+ continue;
706
+ }
707
+ if (declaration.id.type === 'ArrayPattern') {
708
+ // A signal takes no owner, so one outside any function works the same.
709
+ this.tryInlineSignal(declaration, binding);
710
+ } else if (declaration.id === binding.identifier) {
711
+ // An arrow has no owner, so one outside any function works the same.
712
+ this.tryInlineArrow(declaration, binding);
713
+ // A memo outside any function has no owner, and disposes differently.
714
+ if (scope.parent !== undefined) {
715
+ this.tryInline(declaration, binding);
716
+ }
534
717
  }
535
718
  }
536
719
  }