solid-optimizer 0.4.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,8 +54,10 @@
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';
@@ -41,7 +67,6 @@ 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;
@@ -107,36 +157,36 @@ class MemoInliner {
107
157
  /** Why the last memo was turned down, for the report. Empty for a call that is not a memo. */
108
158
  private reason = '';
109
159
 
110
- private isCreateMemo(callee: Node): boolean {
160
+ /** Whether a callee is Solid's `createMemo` or `children`. */
161
+ private memoKind(callee: Node): MemoKind | undefined {
111
162
  if (callee.type !== 'Identifier') {
112
- return false;
163
+ return undefined;
113
164
  }
114
165
  const binding = this.context.scopes.references.get(callee);
115
- 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;
116
168
  }
117
169
 
118
170
  /**
119
- * 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.
120
173
  */
121
- private unstableComputation(declarator: VariableDeclarator): Expression | undefined {
174
+ private computation(
175
+ declarator: VariableDeclarator,
176
+ ): { expression: Expression; alwaysNotifies: boolean; kind: MemoKind } | undefined {
122
177
  const init = declarator.init ? unwrap(declarator.init) : undefined;
123
- 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) {
124
180
  return undefined;
125
181
  }
126
- // Solid 1 takes `createMemo(compute, initialValue?, options?)`. The
127
- // initial value only reaches the computation as `prev`, which a
128
- // computation without parameters never reads.
129
182
  const args = init.arguments;
183
+ if (kind === 'children' && args.length > 1) {
184
+ this.reason = 'memo-options';
185
+ return undefined;
186
+ }
130
187
  const compute = args.at(0);
131
- const initialValue = args.at(1);
132
- const options = args.at(2);
133
- if (
134
- args.length > 3 ||
135
- compute === undefined ||
136
- compute.type === 'SpreadElement' ||
137
- initialValue?.type === 'SpreadElement' ||
138
- (initialValue !== undefined && !isSideEffectFree(initialValue))
139
- ) {
188
+ const options = args.at(1);
189
+ if (args.length > 2 || compute === undefined || compute.type === 'SpreadElement') {
140
190
  this.reason = 'memo-computation';
141
191
  return undefined;
142
192
  }
@@ -171,14 +221,53 @@ class MemoInliner {
171
221
  }
172
222
  alwaysNotifies = true;
173
223
  }
174
- if (alwaysNotifies || isFresh(expression)) {
175
- return expression;
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);
176
255
  }
177
- // A memo whose result can equal its last one stops updates, which is what it is for.
178
- if (unwrap(expression).type === 'Literal') {
179
- this.reason = 'memo-constant';
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})`);
180
267
  }
181
- return undefined;
268
+ this.context.s.remove(statement.start, statement.end);
269
+ this.changed = true;
270
+ return true;
182
271
  }
183
272
 
184
273
  /**
@@ -192,6 +281,15 @@ class MemoInliner {
192
281
  return current;
193
282
  }
194
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
+
195
293
  /**
196
294
  * Whether a call is the whole of an expression that Solid tracks, and that
197
295
  * runs once each time `fn` runs.
@@ -347,10 +445,28 @@ class MemoInliner {
347
445
  }
348
446
 
349
447
  private inline(declarator: VariableDeclarator, binding: Binding): true | undefined {
350
- const expression = this.unstableComputation(declarator);
351
- if (!expression) {
448
+ const found = this.computation(declarator);
449
+ if (!found) {
352
450
  return undefined;
353
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
+ }
354
470
  if (binding.references.length !== 1) {
355
471
  this.reason = 'memo-reads';
356
472
  return undefined;
@@ -371,6 +487,16 @@ class MemoInliner {
371
487
  this.reason = 'memo-read-place';
372
488
  return undefined;
373
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
+ }
374
500
  if (
375
501
  !this.resolvesSameAt(expression, call, binding) ||
376
502
  usesFunctionContext(this.context, expression)
@@ -378,8 +504,13 @@ class MemoInliner {
378
504
  this.reason = 'memo-scope';
379
505
  return undefined;
380
506
  }
381
- // The read sits in a JSX container, which takes any expression.
382
- this.context.s.overwrite(call.start, call.end, textOf(this.context, expression));
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));
513
+ }
383
514
  this.context.s.remove(statement.start, statement.end);
384
515
  this.changed = true;
385
516
  return true;
package/src/provider.ts CHANGED
@@ -1,17 +1,17 @@
1
1
  /**
2
2
  * The provider pass: removes context providers whose reads are all visible.
3
3
  *
4
- * In Solid 1, a context carries a provider component, `Ctx.Provider`. The
5
- * provider reads `props.value` once, untracked, when it is created, and
6
- * every `useContext(Ctx)` under it returns that value. When every code path
7
- * that can run under a provider is visible, each read can take the value
8
- * directly, and the provider only costs a component call, a render effect,
9
- * and a template boundary:
4
+ * In Solid 2.0, a context is its own provider component. The provider reads
5
+ * `props.value` once, untracked, when it is created, and every
6
+ * `useContext(Ctx)` under it returns that value. When every code path that
7
+ * can run under a provider is visible, each read can take the value
8
+ * directly, and the provider only costs a component call, a root owner, and
9
+ * a template boundary:
10
10
  *
11
11
  * ```jsx
12
- * <Theme.Provider value="dark">
12
+ * <Theme value="dark">
13
13
  * <span>{useContext(Theme)}</span>
14
- * </Theme.Provider>
14
+ * </Theme>
15
15
  * ```
16
16
  *
17
17
  * becomes `<><span>{"dark"}</span></>`.
@@ -23,9 +23,9 @@
23
23
  *
24
24
  * # Accepted differences
25
25
  *
26
- * - The provider's owner is gone, which shifts the hydration keys after
27
- * it. A server build and its client build must compile with the same
28
- * options.
26
+ * - The provider's root owner is gone, which shifts the hydration keys
27
+ * after it. A server build and its client build must compile with the
28
+ * same options.
29
29
  * - A getter defined by the app, other than on a component's props, that
30
30
  * calls `useContext` is not seen.
31
31
  */
@@ -54,20 +54,22 @@ export const CONTEXT_SAFE_PRIMITIVES = [
54
54
  'createMemo',
55
55
  'createEffect',
56
56
  'createRenderEffect',
57
- 'createComputed',
57
+ 'createStore',
58
+ 'createProjection',
59
+ 'createOptimistic',
58
60
  'onCleanup',
59
- 'onMount',
61
+ 'onSettled',
60
62
  'untrack',
61
- 'batch',
62
63
  'useContext',
64
+ 'flush',
63
65
  'mapArray',
64
- 'indexArray',
65
- 'mergeProps',
66
- 'splitProps',
66
+ 'repeat',
67
+ 'merge',
68
+ 'omit',
67
69
  ];
68
70
 
69
71
  /** Primitives that return a getter and a setter, as `[get, set]`. */
70
- const ACCESSOR_PAIRS = new Set(['createSignal']);
72
+ const ACCESSOR_PAIRS = new Set(['createSignal', 'createStore', 'createOptimistic']);
71
73
 
72
74
  export interface Provider {
73
75
  readonly element: JSXElement;
@@ -77,15 +79,15 @@ export interface Provider {
77
79
  }
78
80
 
79
81
  /**
80
- * The provider a JSX element creates: `Ctx.Provider`, where `Ctx` is a
81
- * top-level `createContext(...)` from Solid that nothing writes to, with one
82
- * `value` attribute holding a value that is never `undefined`.
82
+ * The provider a JSX element creates: a tag that refers to a top-level
83
+ * `createContext(...)` from Solid, nothing writes to, with one `value`
84
+ * attribute holding a value that is never `undefined`.
83
85
  *
84
- * `useContext` returns the default when the value is `undefined`, so a
85
- * value that could be `undefined` keeps its provider.
86
+ * `useContext` throws when the value and the default are both `undefined`,
87
+ * so a value that could be `undefined` keeps its provider.
86
88
  */
87
89
  export function providerOf(context: PassContext, element: JSXElement): Provider | undefined {
88
- const binding = providerContext(context, element.openingElement.name);
90
+ const binding = contextBinding(context, element.openingElement.name);
89
91
  if (!binding || element.openingElement.selfClosing) {
90
92
  return undefined;
91
93
  }
@@ -118,21 +120,7 @@ export function providerOf(context: PassContext, element: JSXElement): Provider
118
120
  }
119
121
 
120
122
  /**
121
- * The context a `Ctx.Provider` tag provides.
122
- */
123
- export function providerContext(context: PassContext, name: Node): Binding | undefined {
124
- if (
125
- name.type !== 'JSXMemberExpression' ||
126
- name.object.type !== 'JSXIdentifier' ||
127
- name.property.name !== 'Provider'
128
- ) {
129
- return undefined;
130
- }
131
- return contextBinding(context, name.object);
132
- }
133
-
134
- /**
135
- * The top-level context binding an identifier refers to.
123
+ * The top-level context binding a tag or identifier refers to.
136
124
  */
137
125
  export function contextBinding(context: PassContext, name: Node): Binding | undefined {
138
126
  if (name.type !== 'JSXIdentifier' && name.type !== 'Identifier') {
@@ -359,7 +347,7 @@ export function isClosed(context: PassContext, root: Node, options: ClosedOption
359
347
  break;
360
348
  case 'Identifier': {
361
349
  // Another component's props run its parent's code when read, and
362
- // passing them on, as to `mergeProps()`, reads them somewhere else. A
350
+ // passing them on, as to `merge()`, reads them somewhere else. A
363
351
  // binding declared under `root`, like a callback's parameter, is a value.
364
352
  const binding = context.scopes.references.get(node);
365
353
  if (binding && runsOutsideCode(context, binding, root, options, 0)) {
@@ -440,8 +428,8 @@ function runsOutsideCode(
440
428
  }
441
429
 
442
430
  /**
443
- * Whether an expression is a `mergeProps()` or `splitProps()` view of a
444
- * component's own props, with only literal objects and keys besides.
431
+ * Whether an expression is a `merge()` or `omit()` view of a component's
432
+ * own props, with only literal objects and keys besides.
445
433
  */
446
434
  function isOwnView(
447
435
  context: PassContext,
@@ -459,13 +447,14 @@ function isOwnView(
459
447
  if (binding === props) {
460
448
  return true;
461
449
  }
462
- call = binding ? viewInit(context, binding) : undefined;
450
+ const init = binding ? constantInit(context, binding) : undefined;
451
+ call = init ? unwrap(init) : undefined;
463
452
  }
464
453
  if (call?.type !== 'CallExpression') {
465
454
  return false;
466
455
  }
467
456
  const callee = solidCallee(context, call);
468
- if (callee !== 'mergeProps' && callee !== 'splitProps') {
457
+ if (callee !== 'merge' && callee !== 'omit') {
469
458
  return false;
470
459
  }
471
460
  return call.arguments.every((argument) => {
@@ -475,51 +464,27 @@ function isOwnView(
475
464
  const inner = unwrap(argument);
476
465
  return (
477
466
  inner.type === 'ObjectExpression' ||
478
- (inner.type === 'ArrayExpression' &&
479
- inner.elements.every((key) => key?.type === 'Literal' && typeof key.value === 'string')) ||
467
+ (inner.type === 'Literal' && typeof inner.value === 'string') ||
480
468
  isOwnView(context, inner, props, depth + 1)
481
469
  );
482
470
  });
483
471
  }
484
472
 
485
- /**
486
- * The call a view binding comes from: `const view = mergeProps(...)`, or
487
- * one of the names in `const [a, b] = splitProps(...)`.
488
- */
489
- function viewInit(context: PassContext, binding: Binding): Node | undefined {
490
- const init = constantInit(context, binding);
491
- if (init) {
492
- return unwrap(init);
493
- }
494
- const { declaration } = binding;
495
- if (
496
- binding.mutated ||
497
- binding.kind !== 'const' ||
498
- declaration.type !== 'VariableDeclarator' ||
499
- declaration.id.type !== 'ArrayPattern' ||
500
- !declaration.id.elements.some((element) => element === binding.identifier) ||
501
- !declaration.init
502
- ) {
503
- return undefined;
504
- }
505
- return unwrap(declaration.init);
506
- }
507
-
508
473
  function isVisibleElement(
509
474
  context: PassContext,
510
475
  element: JSXElement,
511
476
  options: ClosedOptions,
512
477
  ): boolean {
513
478
  const { name } = element.openingElement;
514
- if (providerContext(context, name)) {
515
- return true;
516
- }
517
479
  if (name.type !== 'JSXIdentifier') {
518
480
  return false;
519
481
  }
520
482
  if (isIntrinsicTag(name.name)) {
521
483
  return true;
522
484
  }
485
+ if (contextBinding(context, name)) {
486
+ return true;
487
+ }
523
488
  const binding = context.scopes.references.get(name);
524
489
  const identity = binding ? solidExport(binding, context.options) : name.name;
525
490
  // `<Dynamic>` renders a component it is given, which is not visible.
@@ -712,7 +677,7 @@ export function contextReads(context: PassContext, root: Node, target: Binding):
712
677
  if (
713
678
  node !== root &&
714
679
  node.type === 'JSXElement' &&
715
- providerContext(context, node.openingElement.name) === target
680
+ contextBinding(context, node.openingElement.name) === target
716
681
  ) {
717
682
  return;
718
683
  }
@@ -746,7 +711,7 @@ export function hasNestedProvider(context: PassContext, provider: Provider): boo
746
711
  if (
747
712
  node !== provider.element &&
748
713
  node.type === 'JSXElement' &&
749
- providerContext(context, node.openingElement.name) === provider.context
714
+ contextBinding(context, node.openingElement.name) === provider.context
750
715
  ) {
751
716
  nested = true;
752
717
  return;
@@ -817,7 +782,7 @@ class ProviderRemover {
817
782
  private reportShapes(): void {
818
783
  const visit = (node: Node): void => {
819
784
  if (node.type === 'JSXElement') {
820
- const binding = providerContext(this.context, node.openingElement.name);
785
+ const binding = contextBinding(this.context, node.openingElement.name);
821
786
  if (binding && !providerOf(this.context, node)) {
822
787
  // A lone `value` is turned down because it could be `undefined`.
823
788
  const { attributes } = node.openingElement;
package/src/scope.ts CHANGED
@@ -385,6 +385,11 @@ class Analyzer {
385
385
  this.reference(node, false);
386
386
  break;
387
387
  case 'VariableDeclaration': {
388
+ // `declare const` only tells TypeScript about a global. It is stripped
389
+ // with the types and declares nothing, so its name stays global.
390
+ if (node.declare) {
391
+ break;
392
+ }
388
393
  // `using` binds a disposable resource, so it is never a folding candidate.
389
394
  let kind: BindingKind = 'other';
390
395
  if (node.kind === 'var' || node.kind === 'let' || node.kind === 'const') {
@@ -399,12 +404,16 @@ class Analyzer {
399
404
  break;
400
405
  }
401
406
  case 'FunctionDeclaration':
402
- case 'TSDeclareFunction':
403
407
  if (node.id) {
404
408
  this.declare(node.id, 'function', node);
405
409
  }
406
410
  this.visitFunction(node);
407
411
  break;
412
+ // An overload signature or a `declare function` has no body and is
413
+ // stripped with the types. The implementation declares the name, if there is one.
414
+ case 'TSDeclareFunction':
415
+ this.visitFunction(node);
416
+ break;
408
417
  case 'FunctionExpression':
409
418
  this.visitFunction(node);
410
419
  break;
@@ -422,6 +431,10 @@ class Analyzer {
422
431
  });
423
432
  break;
424
433
  case 'ClassDeclaration':
434
+ // A `declare class` is stripped with the types, like `declare const`.
435
+ if (node.declare) {
436
+ break;
437
+ }
425
438
  if (node.id) {
426
439
  this.declare(node.id, 'class', node);
427
440
  }