solid-optimizer 0.3.0 → 1.0.0-next.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/src/memo.ts CHANGED
@@ -20,6 +20,30 @@
20
20
  * to run once each time the function holding the memo runs, so a read in a
21
21
  * callback, a loop, or a component's children stays a read of the memo.
22
22
  *
23
+ * A memo whose computation folds to a literal reads no signals, so it never
24
+ * runs again and its value never changes. Every read of it becomes the
25
+ * literal, however many there are:
26
+ *
27
+ * ```jsx
28
+ * const size = createMemo(() => 3);
29
+ * return <p>{size() * 2}</p>;
30
+ * ```
31
+ *
32
+ * becomes `<p>{3 * 2}</p>`, which the next fold turns into `6`.
33
+ *
34
+ * Solid's `children` helper is a memo too. It resolves the children once,
35
+ * caches them, and flattens them in a second memo. When the children are JSX,
36
+ * nothing they read at the top makes either memo run again, and inserting the
37
+ * JSX directly resolves it the same way. So a `children(() => <jsx />)` read
38
+ * once as an element's child becomes that JSX, which joins the template:
39
+ *
40
+ * ```jsx
41
+ * const c = children(() => <b>x</b>);
42
+ * return <div>{c()}</div>;
43
+ * ```
44
+ *
45
+ * becomes `<div><b>x</b></div>`.
46
+ *
23
47
  * # Accepted differences
24
48
  *
25
49
  * - The computation first runs when its reader first runs, instead of when
@@ -30,18 +54,19 @@
30
54
  */
31
55
  import type {
32
56
  ArrowFunctionExpression,
57
+ CallExpression,
33
58
  Expression,
34
59
  Function as FunctionNode,
60
+ JSXExpressionContainer,
35
61
  Node,
36
62
  VariableDeclarator,
37
63
  } from 'oxc-parser';
38
64
  import { isFunctionNode, isIntrinsicTag, unwrap } from './ast';
39
65
  import type { PassContext } from './context';
40
- import { solidExport, textOf } from './context';
66
+ import { recordSkip, solidExport, textOf } from './context';
41
67
  import { usesFunctionContext } from './inline';
42
68
  import type { Binding } from './scope';
43
69
  import { lookup, scopeAt } from './scope';
44
- import { isSideEffectFree } from './value';
45
70
 
46
71
  /**
47
72
  * Props of Solid's built-in components that are read inside a memo, once per update.
@@ -50,7 +75,7 @@ const TRACKED_PROPS = new Map([
50
75
  ['Show', 'when'],
51
76
  ['Match', 'when'],
52
77
  ['For', 'each'],
53
- ['Index', 'each'],
78
+ ['Repeat', 'count'],
54
79
  ]);
55
80
 
56
81
  /**
@@ -84,6 +109,31 @@ function isFresh(node: Node): boolean {
84
109
  /**
85
110
  * The expression a compute function returns, when that is all it does.
86
111
  */
112
+ type MemoKind = 'createMemo' | 'children';
113
+
114
+ /**
115
+ * The text of an expression that always gives the same primitive: a literal
116
+ * other than a regular expression, a template literal without expressions,
117
+ * or a negated number.
118
+ */
119
+ function constantText(context: PassContext, node: Expression): string | undefined {
120
+ const expression = unwrap(node);
121
+ switch (expression.type) {
122
+ case 'Literal':
123
+ return 'regex' in expression ? undefined : textOf(context, expression);
124
+ case 'TemplateLiteral':
125
+ return expression.expressions.length === 0 ? textOf(context, expression) : undefined;
126
+ case 'UnaryExpression':
127
+ return expression.operator === '-' &&
128
+ expression.argument.type === 'Literal' &&
129
+ typeof expression.argument.value === 'number'
130
+ ? textOf(context, expression)
131
+ : undefined;
132
+ default:
133
+ return undefined;
134
+ }
135
+ }
136
+
87
137
  function returnedExpression(fn: FunctionNode | ArrowFunctionExpression): Expression | undefined {
88
138
  if (fn.async || fn.generator || fn.params.length > 0 || !fn.body) {
89
139
  return undefined;
@@ -104,50 +154,57 @@ class MemoInliner {
104
154
 
105
155
  constructor(private readonly context: PassContext) {}
106
156
 
107
- private isCreateMemo(callee: Node): boolean {
157
+ /** Why the last memo was turned down, for the report. Empty for a call that is not a memo. */
158
+ private reason = '';
159
+
160
+ /** Whether a callee is Solid's `createMemo` or `children`. */
161
+ private memoKind(callee: Node): MemoKind | undefined {
108
162
  if (callee.type !== 'Identifier') {
109
- return false;
163
+ return undefined;
110
164
  }
111
165
  const binding = this.context.scopes.references.get(callee);
112
- return binding !== undefined && solidExport(binding, this.context.options) === 'createMemo';
166
+ const identity = binding ? solidExport(binding, this.context.options) : undefined;
167
+ return identity === 'createMemo' || identity === 'children' ? identity : undefined;
113
168
  }
114
169
 
115
170
  /**
116
- * The computation of a memo whose result is never equal to its last one.
171
+ * The expression a memo's computation returns, and whether `equals: false`
172
+ * makes it notify on every run.
117
173
  */
118
- private unstableComputation(declarator: VariableDeclarator): Expression | undefined {
174
+ private computation(
175
+ declarator: VariableDeclarator,
176
+ ): { expression: Expression; alwaysNotifies: boolean; kind: MemoKind } | undefined {
119
177
  const init = declarator.init ? unwrap(declarator.init) : undefined;
120
- if (init?.type !== 'CallExpression' || !this.isCreateMemo(init.callee)) {
178
+ const kind = init?.type === 'CallExpression' ? this.memoKind(init.callee) : undefined;
179
+ if (init?.type !== 'CallExpression' || kind === undefined) {
121
180
  return undefined;
122
181
  }
123
- // Solid 1 takes `createMemo(compute, initialValue?, options?)`. The
124
- // initial value only reaches the computation as `prev`, which a
125
- // computation without parameters never reads.
126
182
  const args = init.arguments;
183
+ if (kind === 'children' && args.length > 1) {
184
+ this.reason = 'memo-options';
185
+ return undefined;
186
+ }
127
187
  const compute = args.at(0);
128
- const initialValue = args.at(1);
129
- const options = args.at(2);
130
- if (
131
- args.length > 3 ||
132
- compute === undefined ||
133
- compute.type === 'SpreadElement' ||
134
- initialValue?.type === 'SpreadElement' ||
135
- (initialValue !== undefined && !isSideEffectFree(initialValue))
136
- ) {
188
+ const options = args.at(1);
189
+ if (args.length > 2 || compute === undefined || compute.type === 'SpreadElement') {
190
+ this.reason = 'memo-computation';
137
191
  return undefined;
138
192
  }
139
193
  const fn = unwrap(compute);
140
194
  if (fn.type !== 'ArrowFunctionExpression' && fn.type !== 'FunctionExpression') {
195
+ this.reason = 'memo-computation';
141
196
  return undefined;
142
197
  }
143
198
  const expression = returnedExpression(fn);
144
199
  if (!expression) {
200
+ this.reason = 'memo-computation';
145
201
  return undefined;
146
202
  }
147
203
  let alwaysNotifies = false;
148
204
  if (options !== undefined) {
149
205
  // Only `equals: false` is understood. Any other option changes what the memo does.
150
206
  if (options.type !== 'ObjectExpression' || options.properties.length !== 1) {
207
+ this.reason = 'memo-options';
151
208
  return undefined;
152
209
  }
153
210
  const property = options.properties.at(0);
@@ -159,11 +216,58 @@ class MemoInliner {
159
216
  property.value.type !== 'Literal' ||
160
217
  property.value.value !== false
161
218
  ) {
219
+ this.reason = 'memo-options';
162
220
  return undefined;
163
221
  }
164
222
  alwaysNotifies = true;
165
223
  }
166
- return alwaysNotifies || isFresh(expression) ? expression : undefined;
224
+ return { expression, alwaysNotifies, kind };
225
+ }
226
+
227
+ /**
228
+ * Replaces every read of a memo whose computation is a literal with the
229
+ * literal. Each reference has to be a call after the declaration, since a
230
+ * call before it would throw.
231
+ */
232
+ private inlineConstant(
233
+ declarator: VariableDeclarator,
234
+ binding: Binding,
235
+ text: string,
236
+ ): true | undefined {
237
+ const statement = this.context.parents.get(declarator);
238
+ if (statement?.type !== 'VariableDeclaration' || statement.declarations.length !== 1) {
239
+ this.reason = 'memo-declaration';
240
+ return undefined;
241
+ }
242
+ const calls: CallExpression[] = [];
243
+ for (const reference of binding.references) {
244
+ const call = this.context.parents.get(reference);
245
+ if (
246
+ call?.type !== 'CallExpression' ||
247
+ call.callee !== reference ||
248
+ call.arguments.length > 0 ||
249
+ call.start < declarator.end
250
+ ) {
251
+ this.reason = 'memo-constant';
252
+ return undefined;
253
+ }
254
+ calls.push(call);
255
+ }
256
+ for (const call of calls) {
257
+ // `3.toFixed()` and `-1 ** 2` do not parse, so a literal under an operator or a member gets parentheses.
258
+ const parent = this.context.parents.get(call);
259
+ const bare =
260
+ parent?.type === 'JSXExpressionContainer' ||
261
+ parent?.type === 'VariableDeclarator' ||
262
+ parent?.type === 'ReturnStatement' ||
263
+ parent?.type === 'ArrayExpression' ||
264
+ parent?.type === 'Property' ||
265
+ (parent?.type === 'CallExpression' && parent.callee !== call);
266
+ this.context.s.overwrite(call.start, call.end, bare ? text : `(${text})`);
267
+ }
268
+ this.context.s.remove(statement.start, statement.end);
269
+ this.changed = true;
270
+ return true;
167
271
  }
168
272
 
169
273
  /**
@@ -177,6 +281,15 @@ class MemoInliner {
177
281
  return current;
178
282
  }
179
283
 
284
+ /** The JSX expression container a call is the whole of. */
285
+ private containerOf(call: Node): JSXExpressionContainer | undefined {
286
+ let parent = this.context.parents.get(call);
287
+ while (parent?.type === 'ParenthesizedExpression') {
288
+ parent = this.context.parents.get(parent);
289
+ }
290
+ return parent?.type === 'JSXExpressionContainer' ? parent : undefined;
291
+ }
292
+
180
293
  /**
181
294
  * Whether a call is the whole of an expression that Solid tracks, and that
182
295
  * runs once each time `fn` runs.
@@ -325,31 +438,82 @@ class MemoInliner {
325
438
  }
326
439
 
327
440
  private tryInline(declarator: VariableDeclarator, binding: Binding): void {
328
- const expression = this.unstableComputation(declarator);
329
- if (!expression || binding.references.length !== 1) {
330
- return;
441
+ this.reason = '';
442
+ if (this.inline(declarator, binding) === undefined && this.reason !== '') {
443
+ recordSkip(this.context, 'memos', this.reason, binding.name);
444
+ }
445
+ }
446
+
447
+ private inline(declarator: VariableDeclarator, binding: Binding): true | undefined {
448
+ const found = this.computation(declarator);
449
+ if (!found) {
450
+ return undefined;
451
+ }
452
+ const { expression, alwaysNotifies, kind } = found;
453
+ if (kind === 'children') {
454
+ // Only JSX is resolved the same by `insert`, and never makes the helper run again.
455
+ const root = unwrap(expression);
456
+ if (root.type !== 'JSXElement' && root.type !== 'JSXFragment') {
457
+ this.reason = 'children-dynamic';
458
+ return undefined;
459
+ }
460
+ } else {
461
+ const constant = constantText(this.context, expression);
462
+ if (constant !== undefined) {
463
+ return this.inlineConstant(declarator, binding, constant);
464
+ }
465
+ // A memo whose result can equal its last one stops updates, which is what it is for.
466
+ if (!alwaysNotifies && !isFresh(expression)) {
467
+ return undefined;
468
+ }
469
+ }
470
+ if (binding.references.length !== 1) {
471
+ this.reason = 'memo-reads';
472
+ return undefined;
331
473
  }
332
474
  const statement = this.context.parents.get(declarator);
333
475
  const fn = this.functionOf(declarator);
334
476
  if (statement?.type !== 'VariableDeclaration' || statement.declarations.length !== 1 || !fn) {
335
- return;
477
+ this.reason = 'memo-declaration';
478
+ return undefined;
336
479
  }
337
480
  const reference = binding.references.at(0);
338
481
  const call = reference ? this.context.parents.get(reference) : undefined;
482
+ if (call?.type !== 'CallExpression' || call.callee !== reference || call.arguments.length > 0) {
483
+ this.reason = 'memo-read';
484
+ return undefined;
485
+ }
486
+ if (!this.isSingleTrackedRead(call, fn)) {
487
+ this.reason = 'memo-read-place';
488
+ return undefined;
489
+ }
490
+ // The resolved children are inserted, so the read has to be a child, not an attribute.
491
+ const container = this.containerOf(call);
492
+ const owner = container ? this.context.parents.get(container) : undefined;
493
+ if (
494
+ kind === 'children' &&
495
+ (!container || (owner?.type !== 'JSXElement' && owner?.type !== 'JSXFragment'))
496
+ ) {
497
+ this.reason = 'memo-read-place';
498
+ return undefined;
499
+ }
339
500
  if (
340
- call?.type !== 'CallExpression' ||
341
- call.callee !== reference ||
342
- call.arguments.length > 0 ||
343
- !this.isSingleTrackedRead(call, fn) ||
344
501
  !this.resolvesSameAt(expression, call, binding) ||
345
502
  usesFunctionContext(this.context, expression)
346
503
  ) {
347
- return;
504
+ this.reason = 'memo-scope';
505
+ return undefined;
506
+ }
507
+ if (kind === 'children' && container) {
508
+ // 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));
510
+ } else {
511
+ // The read sits in a JSX container, which takes any expression.
512
+ this.context.s.overwrite(call.start, call.end, textOf(this.context, expression));
348
513
  }
349
- // The read sits in a JSX container, which takes any expression.
350
- this.context.s.overwrite(call.start, call.end, textOf(this.context, expression));
351
514
  this.context.s.remove(statement.start, statement.end);
352
515
  this.changed = true;
516
+ return true;
353
517
  }
354
518
 
355
519
  run(): void {