solid-optimizer 1.0.0-next.0 → 1.0.0-next.10

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/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,
@@ -59,14 +87,18 @@ import type {
59
87
  Function as FunctionNode,
60
88
  JSXExpressionContainer,
61
89
  Node,
90
+ ObjectExpression,
62
91
  VariableDeclarator,
63
92
  } from 'oxc-parser';
64
- import { isFunctionNode, isIntrinsicTag, unwrap } from './ast';
93
+ import { isFunctionNode, isIntrinsicTag, isPrimary, unwrap } from './ast';
65
94
  import type { PassContext } from './context';
66
- import { recordSkip, solidExport, textOf } from './context';
95
+ import { getText, recordSkip, solidExport } from './context';
67
96
  import { usesFunctionContext } from './inline';
68
97
  import type { Binding } from './scope';
69
98
  import { lookup, scopeAt } from './scope';
99
+ import { compactLength } from './size';
100
+ import type { Text } from './text';
101
+ import { joinText } from './text';
70
102
 
71
103
  /**
72
104
  * Props of Solid's built-in components that are read inside a memo, once per update.
@@ -78,34 +110,107 @@ const TRACKED_PROPS = new Map([
78
110
  ['Repeat', 'count'],
79
111
  ]);
80
112
 
113
+ /**
114
+ * Global constructors whose instances are never thenable or async iterable.
115
+ */
116
+ const SYNC_CONSTRUCTORS = new Set([
117
+ 'Array',
118
+ 'Date',
119
+ 'Error',
120
+ 'Map',
121
+ 'RegExp',
122
+ 'Set',
123
+ 'URL',
124
+ 'URLSearchParams',
125
+ 'WeakMap',
126
+ 'WeakSet',
127
+ ]);
128
+
129
+ /**
130
+ * Whether an object literal can have a `then` method or `Symbol.asyncIterator`,
131
+ * its own or from a `__proto__` it sets.
132
+ */
133
+ function mayBeThenable(node: ObjectExpression): boolean {
134
+ for (const property of node.properties) {
135
+ if (property.type === 'SpreadElement' || property.computed) {
136
+ return true;
137
+ }
138
+ const { key } = property;
139
+ let name: unknown;
140
+ if (key.type === 'Identifier') {
141
+ name = key.name;
142
+ } else if ('value' in key) {
143
+ name = key.value;
144
+ }
145
+ if (name === 'then' || name === '__proto__') {
146
+ return true;
147
+ }
148
+ }
149
+ return false;
150
+ }
151
+
81
152
  /**
82
153
  * Whether evaluating `node` always creates a new value, which reference
83
- * equality never finds equal to the last one.
154
+ * equality never finds equal to the last one. The value is never a promise
155
+ * or an async iterable, which a memo waits for and an inlined read does not.
156
+ * `isGlobal` tells whether a name is one the module does not declare.
84
157
  */
85
- function isFresh(node: Node): boolean {
158
+ function isFresh(node: Node, isGlobal: (node: Node) => boolean): boolean {
86
159
  switch (node.type) {
87
- case 'ObjectExpression':
88
160
  case 'ArrayExpression':
89
161
  case 'ArrowFunctionExpression':
90
162
  case 'FunctionExpression':
91
- case 'ClassExpression':
92
- case 'NewExpression':
93
163
  case 'JSXElement':
94
164
  case 'JSXFragment':
95
165
  return true;
166
+ case 'ObjectExpression':
167
+ return !mayBeThenable(node);
168
+ case 'NewExpression':
169
+ return (
170
+ node.callee.type === 'Identifier' &&
171
+ SYNC_CONSTRUCTORS.has(node.callee.name) &&
172
+ isGlobal(node.callee)
173
+ );
96
174
  case 'ParenthesizedExpression':
97
- return isFresh(node.expression);
175
+ return isFresh(node.expression, isGlobal);
98
176
  case 'ConditionalExpression':
99
- return isFresh(node.consequent) && isFresh(node.alternate);
177
+ return isFresh(node.consequent, isGlobal) && isFresh(node.alternate, isGlobal);
100
178
  case 'SequenceExpression': {
101
179
  const last = node.expressions.at(-1);
102
- return last !== undefined && isFresh(last);
180
+ return last !== undefined && isFresh(last, isGlobal);
103
181
  }
104
182
  default:
105
183
  return false;
106
184
  }
107
185
  }
108
186
 
187
+ /**
188
+ * Whether `node` evaluates to a value that is never a promise or an async
189
+ * iterable. A memo waits for one of those, and an inlined read does not.
190
+ */
191
+ function isSync(node: Node, isGlobal: (node: Node) => boolean): boolean {
192
+ switch (node.type) {
193
+ case 'Literal':
194
+ case 'TemplateLiteral':
195
+ case 'UnaryExpression':
196
+ case 'UpdateExpression':
197
+ case 'BinaryExpression':
198
+ return true;
199
+ case 'ParenthesizedExpression':
200
+ return isSync(node.expression, isGlobal);
201
+ case 'ConditionalExpression':
202
+ return isSync(node.consequent, isGlobal) && isSync(node.alternate, isGlobal);
203
+ case 'LogicalExpression':
204
+ return isSync(node.left, isGlobal) && isSync(node.right, isGlobal);
205
+ case 'SequenceExpression': {
206
+ const last = node.expressions.at(-1);
207
+ return last !== undefined && isSync(last, isGlobal);
208
+ }
209
+ default:
210
+ return isFresh(node, isGlobal);
211
+ }
212
+ }
213
+
109
214
  /**
110
215
  * The expression a compute function returns, when that is all it does.
111
216
  */
@@ -116,18 +221,18 @@ type MemoKind = 'createMemo' | 'children';
116
221
  * other than a regular expression, a template literal without expressions,
117
222
  * or a negated number.
118
223
  */
119
- function constantText(context: PassContext, node: Expression): string | undefined {
224
+ function constantText(context: PassContext, node: Expression): Text | undefined {
120
225
  const expression = unwrap(node);
121
226
  switch (expression.type) {
122
227
  case 'Literal':
123
- return 'regex' in expression ? undefined : textOf(context, expression);
228
+ return 'regex' in expression ? undefined : getText(context, expression);
124
229
  case 'TemplateLiteral':
125
- return expression.expressions.length === 0 ? textOf(context, expression) : undefined;
230
+ return expression.expressions.length === 0 ? getText(context, expression) : undefined;
126
231
  case 'UnaryExpression':
127
232
  return expression.operator === '-' &&
128
233
  expression.argument.type === 'Literal' &&
129
234
  typeof expression.argument.value === 'number'
130
- ? textOf(context, expression)
235
+ ? getText(context, expression)
131
236
  : undefined;
132
237
  default:
133
238
  return undefined;
@@ -152,6 +257,9 @@ function returnedExpression(fn: FunctionNode | ArrowFunctionExpression): Express
152
257
  class MemoInliner {
153
258
  changed = false;
154
259
 
260
+ /** Ranges of the source rewritten so far in this run. */
261
+ private readonly edited: [number, number][] = [];
262
+
155
263
  constructor(private readonly context: PassContext) {}
156
264
 
157
265
  /** Why the last memo was turned down, for the report. Empty for a call that is not a memo. */
@@ -225,18 +333,19 @@ class MemoInliner {
225
333
  }
226
334
 
227
335
  /**
228
- * Replaces every read of a memo whose computation is a literal with the
336
+ * Replaces every read of a memo or signal whose value is a literal with the
229
337
  * literal. Each reference has to be a call after the declaration, since a
230
338
  * call before it would throw.
231
339
  */
232
340
  private inlineConstant(
233
341
  declarator: VariableDeclarator,
234
342
  binding: Binding,
235
- text: string,
343
+ text: Text,
344
+ kind: 'memo' | 'signal' = 'memo',
236
345
  ): true | undefined {
237
346
  const statement = this.context.parents.get(declarator);
238
347
  if (statement?.type !== 'VariableDeclaration' || statement.declarations.length !== 1) {
239
- this.reason = 'memo-declaration';
348
+ this.reason = `${kind}-declaration`;
240
349
  return undefined;
241
350
  }
242
351
  const calls: CallExpression[] = [];
@@ -248,7 +357,7 @@ class MemoInliner {
248
357
  call.arguments.length > 0 ||
249
358
  call.start < declarator.end
250
359
  ) {
251
- this.reason = 'memo-constant';
360
+ this.reason = `${kind}-constant`;
252
361
  return undefined;
253
362
  }
254
363
  calls.push(call);
@@ -263,9 +372,11 @@ class MemoInliner {
263
372
  parent?.type === 'ArrayExpression' ||
264
373
  parent?.type === 'Property' ||
265
374
  (parent?.type === 'CallExpression' && parent.callee !== call);
266
- this.context.s.overwrite(call.start, call.end, bare ? text : `(${text})`);
375
+ this.context.s.overwrite(call.start, call.end, bare ? text : joinText`(${text})`);
376
+ this.edited.push([call.start, call.end]);
267
377
  }
268
378
  this.context.s.remove(statement.start, statement.end);
379
+ this.edited.push([statement.start, statement.end]);
269
380
  this.changed = true;
270
381
  return true;
271
382
  }
@@ -273,7 +384,7 @@ class MemoInliner {
273
384
  /**
274
385
  * The function a node runs in.
275
386
  */
276
- private functionOf(node: Node): Node | undefined {
387
+ private findEnclosingFunction(node: Node): Node | undefined {
277
388
  let current = this.context.parents.get(node);
278
389
  while (current && !isFunctionNode(current)) {
279
390
  current = this.context.parents.get(current);
@@ -282,7 +393,7 @@ class MemoInliner {
282
393
  }
283
394
 
284
395
  /** The JSX expression container a call is the whole of. */
285
- private containerOf(call: Node): JSXExpressionContainer | undefined {
396
+ private findContainer(call: Node): JSXExpressionContainer | undefined {
286
397
  let parent = this.context.parents.get(call);
287
398
  while (parent?.type === 'ParenthesizedExpression') {
288
399
  parent = this.context.parents.get(parent);
@@ -331,7 +442,7 @@ class MemoInliner {
331
442
  return false;
332
443
  }
333
444
  } else if (
334
- this.builtInOf(element.openingElement.name) !== tag ||
445
+ this.getBuiltIn(element.openingElement.name) !== tag ||
335
446
  TRACKED_PROPS.get(tag) !== attribute
336
447
  ) {
337
448
  // A component can read a prop any number of times.
@@ -343,7 +454,7 @@ class MemoInliner {
343
454
  return this.isStaticJSX(element, fn);
344
455
  }
345
456
 
346
- private builtInOf(name: Node): string | undefined {
457
+ private getBuiltIn(name: Node): string | undefined {
347
458
  if (name.type !== 'JSXIdentifier') {
348
459
  return undefined;
349
460
  }
@@ -382,7 +493,7 @@ class MemoInliner {
382
493
  case 'ParenthesizedExpression':
383
494
  break;
384
495
  case 'ReturnStatement':
385
- return this.functionOf(parent) === fn && !this.inLoop(parent, fn);
496
+ return this.findEnclosingFunction(parent) === fn && !this.inLoop(parent, fn);
386
497
  default:
387
498
  return false;
388
499
  }
@@ -462,8 +573,16 @@ class MemoInliner {
462
573
  if (constant !== undefined) {
463
574
  return this.inlineConstant(declarator, binding, constant);
464
575
  }
576
+ const isGlobal = (node: Node): boolean =>
577
+ this.context.scopes.references.get(node) === undefined;
465
578
  // A memo whose result can equal its last one stops updates, which is what it is for.
466
- if (!alwaysNotifies && !isFresh(expression)) {
579
+ if (!alwaysNotifies && !isFresh(expression, isGlobal)) {
580
+ return undefined;
581
+ }
582
+ // A memo waits for a promise or an async iterable. The insert an inlined
583
+ // read becomes takes the value as it is.
584
+ if (alwaysNotifies && !isSync(expression, isGlobal)) {
585
+ this.reason = 'memo-async';
467
586
  return undefined;
468
587
  }
469
588
  }
@@ -472,7 +591,7 @@ class MemoInliner {
472
591
  return undefined;
473
592
  }
474
593
  const statement = this.context.parents.get(declarator);
475
- const fn = this.functionOf(declarator);
594
+ const fn = this.findEnclosingFunction(declarator);
476
595
  if (statement?.type !== 'VariableDeclaration' || statement.declarations.length !== 1 || !fn) {
477
596
  this.reason = 'memo-declaration';
478
597
  return undefined;
@@ -488,7 +607,7 @@ class MemoInliner {
488
607
  return undefined;
489
608
  }
490
609
  // The resolved children are inserted, so the read has to be a child, not an attribute.
491
- const container = this.containerOf(call);
610
+ const container = this.findContainer(call);
492
611
  const owner = container ? this.context.parents.get(container) : undefined;
493
612
  if (
494
613
  kind === 'children' &&
@@ -506,31 +625,183 @@ class MemoInliner {
506
625
  }
507
626
  if (kind === 'children' && container) {
508
627
  // The JSX takes the place of its container, so it joins the template around it.
509
- this.context.s.overwrite(container.start, container.end, textOf(this.context, expression));
628
+ this.context.s.overwrite(container.start, container.end, getText(this.context, expression));
629
+ this.edited.push([container.start, container.end]);
510
630
  } else {
511
631
  // The read sits in a JSX container, which takes any expression.
512
- this.context.s.overwrite(call.start, call.end, textOf(this.context, expression));
632
+ this.context.s.overwrite(call.start, call.end, getText(this.context, expression));
633
+ this.edited.push([call.start, call.end]);
513
634
  }
514
635
  this.context.s.remove(statement.start, statement.end);
636
+ this.edited.push([statement.start, statement.end]);
515
637
  this.changed = true;
516
638
  return true;
517
639
  }
518
640
 
641
+ /**
642
+ * The literal a signal always holds: `const [get] = createSignal(literal)`,
643
+ * or `const [get, set] = ...` with nothing referencing `set`. Options can
644
+ * change what a read does, such as `unobserved`, so a signal with options
645
+ * stays.
646
+ */
647
+ private signalConstant(declarator: VariableDeclarator, binding: Binding): Text | undefined {
648
+ const pattern = declarator.id;
649
+ const init = declarator.init ? unwrap(declarator.init) : undefined;
650
+ if (
651
+ pattern.type !== 'ArrayPattern' ||
652
+ pattern.elements.at(0) !== binding.identifier ||
653
+ pattern.elements.length > 2 ||
654
+ init?.type !== 'CallExpression' ||
655
+ init.callee.type !== 'Identifier' ||
656
+ init.arguments.length !== 1
657
+ ) {
658
+ return undefined;
659
+ }
660
+ const callee = this.context.scopes.references.get(init.callee);
661
+ if (!callee || solidExport(callee, this.context.options) !== 'createSignal') {
662
+ return undefined;
663
+ }
664
+ const value = init.arguments.at(0);
665
+ if (!value || value.type === 'SpreadElement') {
666
+ return undefined;
667
+ }
668
+ // Other modules can read an exported getter.
669
+ const statement = this.context.parents.get(declarator);
670
+ if (statement && this.context.parents.get(statement)?.type === 'ExportNamedDeclaration') {
671
+ return undefined;
672
+ }
673
+ const setter = pattern.elements.at(1);
674
+ if (setter) {
675
+ const setterBinding =
676
+ setter.type === 'Identifier' ? binding.scope.bindings.get(setter.name) : undefined;
677
+ if (setterBinding?.identifier !== setter || setterBinding.references.length > 0) {
678
+ return undefined;
679
+ }
680
+ }
681
+ return constantText(this.context, value);
682
+ }
683
+
684
+ private tryInlineSignal(declarator: VariableDeclarator, binding: Binding): void {
685
+ const text = this.signalConstant(declarator, binding);
686
+ if (text === undefined) {
687
+ return;
688
+ }
689
+ this.reason = '';
690
+ if (this.inlineConstant(declarator, binding, text, 'signal') === undefined) {
691
+ recordSkip(this.context, 'memos', this.reason, binding.name);
692
+ }
693
+ }
694
+
695
+ /**
696
+ * Replaces every call of `const name = () => expression` with the
697
+ * expression. Each reference has to be a call with no arguments after the
698
+ * declaration, and every name in the body has to mean the same at the call.
699
+ */
700
+ private tryInlineArrow(declarator: VariableDeclarator, binding: Binding): void {
701
+ const fn = declarator.init ? unwrap(declarator.init) : undefined;
702
+ if (fn?.type !== 'ArrowFunctionExpression' || fn.async || fn.params.length > 0) {
703
+ return;
704
+ }
705
+ const body = returnedExpression(fn);
706
+ const statement = this.context.parents.get(declarator);
707
+ if (
708
+ !body ||
709
+ statement?.type !== 'VariableDeclaration' ||
710
+ statement.declarations.length !== 1 ||
711
+ // Other modules can call an exported arrow.
712
+ this.context.parents.get(statement)?.type === 'ExportNamedDeclaration'
713
+ ) {
714
+ return;
715
+ }
716
+ const calls: CallExpression[] = [];
717
+ for (const reference of binding.references) {
718
+ const call = this.context.parents.get(reference);
719
+ if (
720
+ call?.type !== 'CallExpression' ||
721
+ call.callee !== reference ||
722
+ call.optional ||
723
+ call.arguments.length > 0 ||
724
+ call.start < declarator.end
725
+ ) {
726
+ // The arrow is used as a value, like an event handler. That is not a derivation.
727
+ return;
728
+ }
729
+ // `l()()` calls the result with no `this`, but `(a.b)()` passes `a`, and
730
+ // `delete (a.b)` deletes what `delete l()` leaves alone.
731
+ const parent = this.context.parents.get(call);
732
+ if (
733
+ (parent?.type === 'CallExpression' && parent.callee === call) ||
734
+ (parent?.type === 'TaggedTemplateExpression' && parent.tag === call) ||
735
+ (parent?.type === 'UnaryExpression' && parent.operator === 'delete')
736
+ ) {
737
+ return;
738
+ }
739
+ calls.push(call);
740
+ }
741
+ if (calls.length === 0) {
742
+ return;
743
+ }
744
+ // The body is copied from the source, so it must not hold an edit from this run.
745
+ // The next round sees the edit.
746
+ for (const [start, end] of this.edited) {
747
+ if (start < statement.end && end > statement.start) {
748
+ return;
749
+ }
750
+ }
751
+ const text = getText(this.context, body);
752
+ // Minified, the arrow costs `const a=()=>body;`, 13 characters besides the
753
+ // body, and each call `a()` costs 3. Copying adds the body to every call
754
+ // but one, and removes the rest.
755
+ const length = compactLength(text.code);
756
+ if ((calls.length - 1) * length > calls.length * 3 + 13) {
757
+ return;
758
+ }
759
+ if (usesFunctionContext(this.context, fn)) {
760
+ return;
761
+ }
762
+ for (const call of calls) {
763
+ if (!this.resolvesSameAt(body, call, binding)) {
764
+ return;
765
+ }
766
+ }
767
+ const bare = isPrimary(body);
768
+ for (const call of calls) {
769
+ const parent = this.context.parents.get(call);
770
+ const inContainer =
771
+ parent?.type === 'JSXExpressionContainer' && body.type !== 'SequenceExpression';
772
+ this.context.s.overwrite(
773
+ call.start,
774
+ call.end,
775
+ bare || inContainer ? text : joinText`(${text})`,
776
+ );
777
+ this.edited.push([call.start, call.end]);
778
+ }
779
+ this.context.s.remove(statement.start, statement.end);
780
+ this.edited.push([statement.start, statement.end]);
781
+ this.changed = true;
782
+ }
783
+
519
784
  run(): void {
520
785
  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
786
  for (const binding of scope.bindings.values()) {
526
787
  const { declaration } = binding;
527
788
  if (
528
- binding.kind === 'const' &&
529
- !binding.mutated &&
530
- declaration.type === 'VariableDeclarator' &&
531
- declaration.id === binding.identifier
789
+ binding.kind !== 'const' ||
790
+ binding.mutated ||
791
+ declaration.type !== 'VariableDeclarator'
532
792
  ) {
533
- this.tryInline(declaration, binding);
793
+ continue;
794
+ }
795
+ if (declaration.id.type === 'ArrayPattern') {
796
+ // A signal takes no owner, so one outside any function works the same.
797
+ this.tryInlineSignal(declaration, binding);
798
+ } else if (declaration.id === binding.identifier) {
799
+ // An arrow has no owner, so one outside any function works the same.
800
+ this.tryInlineArrow(declaration, binding);
801
+ // A memo outside any function has no owner, and disposes differently.
802
+ if (scope.parent !== undefined) {
803
+ this.tryInline(declaration, binding);
804
+ }
534
805
  }
535
806
  }
536
807
  }