solid-optimizer 0.2.0 → 0.3.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 (51) hide show
  1. package/README.md +269 -14
  2. package/dist/compile-BroGlagZ.d.mts +172 -0
  3. package/dist/compile-BroGlagZ.d.mts.map +1 -0
  4. package/dist/compile-ocDYvJUW.mjs +3910 -0
  5. package/dist/compile-ocDYvJUW.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 +35 -0
  9. package/dist/vite.d.mts.map +1 -0
  10. package/dist/vite.mjs +1465 -0
  11. package/dist/vite.mjs.map +1 -0
  12. package/package.json +60 -58
  13. package/src/ast.ts +263 -0
  14. package/src/compile.ts +304 -0
  15. package/src/constants.ts +249 -0
  16. package/src/context.ts +87 -0
  17. package/src/fold.ts +850 -0
  18. package/src/index.ts +4 -107
  19. package/src/inline.ts +2028 -0
  20. package/src/jsx.ts +170 -0
  21. package/src/memo.ts +383 -0
  22. package/src/provider.ts +842 -0
  23. package/src/scope.ts +588 -0
  24. package/src/server.ts +275 -0
  25. package/src/size.ts +307 -0
  26. package/src/value.ts +386 -0
  27. package/src/vite/index.ts +1135 -0
  28. package/src/vite/inject.ts +311 -0
  29. package/src/vite/namespace.ts +66 -0
  30. package/src/vite/runtime.ts +390 -0
  31. package/src/vite/usage.ts +405 -0
  32. package/dist/cjs/development/index.cjs +0 -228
  33. package/dist/cjs/development/index.cjs.map +0 -7
  34. package/dist/cjs/production/index.cjs +0 -1
  35. package/dist/esm/development/index.mjs +0 -197
  36. package/dist/esm/development/index.mjs.map +0 -7
  37. package/dist/esm/production/index.mjs +0 -1
  38. package/dist/types/checks.d.ts +0 -9
  39. package/dist/types/checks.d.ts.map +0 -1
  40. package/dist/types/index.d.ts +0 -3
  41. package/dist/types/index.d.ts.map +0 -1
  42. package/dist/types/path-references-import.d.ts +0 -3
  43. package/dist/types/path-references-import.d.ts.map +0 -1
  44. package/dist/types/unwrap-node.d.ts +0 -7
  45. package/dist/types/unwrap-node.d.ts.map +0 -1
  46. package/dist/types/unwrap-path.d.ts +0 -6
  47. package/dist/types/unwrap-path.d.ts.map +0 -1
  48. package/src/checks.ts +0 -42
  49. package/src/path-references-import.ts +0 -82
  50. package/src/unwrap-node.ts +0 -27
  51. package/src/unwrap-path.ts +0 -18
@@ -0,0 +1,842 @@
1
+ /**
2
+ * The provider pass: removes context providers whose reads are all visible.
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:
10
+ *
11
+ * ```jsx
12
+ * <Theme.Provider value="dark">
13
+ * <span>{useContext(Theme)}</span>
14
+ * </Theme.Provider>
15
+ * ```
16
+ *
17
+ * becomes `<><span>{"dark"}</span></>`.
18
+ *
19
+ * Most reads sit in a consumer component's statements. The inline pass
20
+ * moves those consumers out through a closed provider and replaces their
21
+ * reads, and this pass removes the provider once nothing under it is a
22
+ * component anymore.
23
+ *
24
+ * # Accepted differences
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.
29
+ * - A getter defined by the app, other than on a component's props, that
30
+ * calls `useContext` is not seen.
31
+ */
32
+ import type {
33
+ CallExpression,
34
+ Expression,
35
+ JSXAttribute,
36
+ JSXElement,
37
+ MemberExpression,
38
+ Node,
39
+ ObjectExpression,
40
+ } from 'oxc-parser';
41
+ import { forEachChild, isFunctionNode, isIntrinsicTag, unwrap } from './ast';
42
+ import type { PassContext } from './context';
43
+ import { isConstantDeclaration, solidExport } from './context';
44
+ import type { Binding } from './scope';
45
+ import { lookup, scopeAt } from './scope';
46
+ import { evaluate, isSideEffectFree, literalText } from './value';
47
+
48
+ /**
49
+ * Solid's primitives that run no code of the app, except the functions
50
+ * passed to them. Those functions are checked like any other code.
51
+ */
52
+ export const CONTEXT_SAFE_PRIMITIVES = [
53
+ 'createSignal',
54
+ 'createMemo',
55
+ 'createEffect',
56
+ 'createRenderEffect',
57
+ 'createComputed',
58
+ 'onCleanup',
59
+ 'onMount',
60
+ 'untrack',
61
+ 'batch',
62
+ 'useContext',
63
+ 'mapArray',
64
+ 'indexArray',
65
+ 'mergeProps',
66
+ 'splitProps',
67
+ ];
68
+
69
+ /** Primitives that return a getter and a setter, as `[get, set]`. */
70
+ const ACCESSOR_PAIRS = new Set(['createSignal']);
71
+
72
+ export interface Provider {
73
+ readonly element: JSXElement;
74
+ /** The top-level `createContext()` binding the tag refers to. */
75
+ readonly context: Binding;
76
+ readonly value: Expression;
77
+ }
78
+
79
+ /**
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`.
83
+ *
84
+ * `useContext` returns the default when the value is `undefined`, so a
85
+ * value that could be `undefined` keeps its provider.
86
+ */
87
+ export function providerOf(context: PassContext, element: JSXElement): Provider | undefined {
88
+ const binding = providerContext(context, element.openingElement.name);
89
+ if (!binding || element.openingElement.selfClosing) {
90
+ return undefined;
91
+ }
92
+ const { attributes } = element.openingElement;
93
+ const attribute = attributes.at(0);
94
+ if (
95
+ attributes.length !== 1 ||
96
+ attribute?.type !== 'JSXAttribute' ||
97
+ attribute.name.type !== 'JSXIdentifier' ||
98
+ attribute.name.name !== 'value' ||
99
+ !attribute.value
100
+ ) {
101
+ return undefined;
102
+ }
103
+ let value: Expression;
104
+ if (attribute.value.type === 'Literal') {
105
+ value = attribute.value;
106
+ } else if (
107
+ attribute.value.type === 'JSXExpressionContainer' &&
108
+ attribute.value.expression.type !== 'JSXEmptyExpression'
109
+ ) {
110
+ value = attribute.value.expression;
111
+ } else {
112
+ return undefined;
113
+ }
114
+ if (!isDefined(context, value, 0)) {
115
+ return undefined;
116
+ }
117
+ return { element, context: binding, value };
118
+ }
119
+
120
+ /**
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.
136
+ */
137
+ export function contextBinding(context: PassContext, name: Node): Binding | undefined {
138
+ if (name.type !== 'JSXIdentifier' && name.type !== 'Identifier') {
139
+ return undefined;
140
+ }
141
+ const binding = context.scopes.references.get(name);
142
+ if (!binding || binding.mutated || binding.scope.parent !== undefined) {
143
+ return undefined;
144
+ }
145
+ if (binding.kind === 'import') {
146
+ const { source, imported } = binding;
147
+ const known =
148
+ source !== undefined &&
149
+ imported !== undefined &&
150
+ context.options.importedContexts.get(source)?.has(imported) === true;
151
+ return known ? binding : undefined;
152
+ }
153
+ const { declaration } = binding;
154
+ if (
155
+ declaration.type !== 'VariableDeclarator' ||
156
+ declaration.id !== binding.identifier ||
157
+ !isConstantDeclaration(binding, context.options) ||
158
+ !declaration.init
159
+ ) {
160
+ return undefined;
161
+ }
162
+ const init = unwrap(declaration.init);
163
+ return init.type === 'CallExpression' && solidCallee(context, init) === 'createContext'
164
+ ? binding
165
+ : undefined;
166
+ }
167
+
168
+ /**
169
+ * The Solid export a call calls, like `createSignal`.
170
+ */
171
+ export function solidCallee(context: PassContext, call: CallExpression): string | undefined {
172
+ const callee = unwrap(call.callee);
173
+ if (callee.type !== 'Identifier') {
174
+ return undefined;
175
+ }
176
+ const binding = context.scopes.references.get(callee);
177
+ return binding ? solidExport(binding, context.options) : undefined;
178
+ }
179
+
180
+ /**
181
+ * Whether evaluating `node` never gives `undefined`.
182
+ */
183
+ function isDefined(context: PassContext, node: Expression, depth: number): boolean {
184
+ const expression = unwrap(node);
185
+ switch (expression.type) {
186
+ case 'ObjectExpression':
187
+ case 'ArrayExpression':
188
+ case 'ArrowFunctionExpression':
189
+ case 'FunctionExpression':
190
+ case 'ClassExpression':
191
+ case 'NewExpression':
192
+ case 'TemplateLiteral':
193
+ case 'JSXElement':
194
+ case 'JSXFragment':
195
+ return true;
196
+ case 'Identifier': {
197
+ const binding = context.scopes.references.get(expression);
198
+ if (!binding || binding.mutated || depth > 2) {
199
+ return false;
200
+ }
201
+ if (binding.kind === 'function' || binding.kind === 'class' || isAccessor(context, binding)) {
202
+ return true;
203
+ }
204
+ const { declaration } = binding;
205
+ return (
206
+ isConstantDeclaration(binding, context.options) &&
207
+ declaration.type === 'VariableDeclarator' &&
208
+ declaration.id === binding.identifier &&
209
+ declaration.init !== null &&
210
+ isDefined(context, declaration.init, depth + 1)
211
+ );
212
+ }
213
+ default: {
214
+ return evaluate(expression, () => undefined)?.value !== undefined;
215
+ }
216
+ }
217
+ }
218
+
219
+ /**
220
+ * The text a read of a provider's value can be replaced with at `site`: a
221
+ * literal, or a binding that never changes and means the same there.
222
+ * `undefined` when the value has to be stored first.
223
+ */
224
+ export function stableValueText(
225
+ context: PassContext,
226
+ provider: Provider,
227
+ site: Node,
228
+ ): string | undefined {
229
+ const value = unwrap(provider.value);
230
+ const constant = evaluate(value, () => undefined);
231
+ if (constant) {
232
+ return literalText(constant.value);
233
+ }
234
+ if (value.type !== 'Identifier') {
235
+ return undefined;
236
+ }
237
+ const binding = context.scopes.references.get(value);
238
+ if (!binding || binding.mutated) {
239
+ return undefined;
240
+ }
241
+ const unchanging =
242
+ binding.kind === 'function' ||
243
+ binding.kind === 'class' ||
244
+ binding.kind === 'import' ||
245
+ isConstantDeclaration(binding, context.options);
246
+ if (!unchanging) {
247
+ return undefined;
248
+ }
249
+ const scope = scopeAt(context.scopes, context.parents, site);
250
+ return lookup(scope, value.name) === binding ? value.name : undefined;
251
+ }
252
+
253
+ /**
254
+ * Whether an attribute is an event handler given as a function. The
255
+ * function runs with no owner, so a `useContext` in it throws whether or
256
+ * not a provider is above it.
257
+ */
258
+ function isHandlerFunction(attribute: JSXAttribute): boolean {
259
+ const { name, value } = attribute;
260
+ const text =
261
+ name.type === 'JSXIdentifier' ? name.name : `${name.namespace.name}:${name.name.name}`;
262
+ if (!/^on(?:[A-Z]|:)/.test(text) || value?.type !== 'JSXExpressionContainer') {
263
+ return false;
264
+ }
265
+ const expression = value.expression.type === 'JSXEmptyExpression' ? undefined : value.expression;
266
+ return expression !== undefined && isFunctionNode(unwrap(expression));
267
+ }
268
+
269
+ /**
270
+ * Whether a binding is a signal or store getter or setter, or a memo, which
271
+ * run no code of the app when called.
272
+ */
273
+ function isAccessor(context: PassContext, binding: Binding): boolean {
274
+ if (binding.mutated) {
275
+ return false;
276
+ }
277
+ const { declaration } = binding;
278
+ if (declaration.type !== 'VariableDeclarator') {
279
+ return false;
280
+ }
281
+ const { id, init } = declaration;
282
+ const call = init ? unwrap(init) : undefined;
283
+ if (call?.type !== 'CallExpression') {
284
+ return false;
285
+ }
286
+ const callee = solidCallee(context, call);
287
+ if (id === binding.identifier) {
288
+ return callee === 'createMemo';
289
+ }
290
+ if (id.type !== 'ArrayPattern' || callee === undefined || !ACCESSOR_PAIRS.has(callee)) {
291
+ return false;
292
+ }
293
+ const index = id.elements.findIndex((element) => element === binding.identifier);
294
+ return index === 0 || index === 1;
295
+ }
296
+
297
+ export interface ClosedOptions {
298
+ /** Whether a component element can be treated as visible code. */
299
+ readonly component: (element: JSXElement) => boolean;
300
+ /** A component's own props, whose reads are replaced when it is inlined. */
301
+ readonly props?: Binding;
302
+ /** The value a read of a context gets, when the provider is known. */
303
+ readonly contextValue?: (target: Binding) => Expression | undefined;
304
+ }
305
+
306
+ /**
307
+ * Whether all code that can run under `root` is visible, so a provider
308
+ * above it has no reader that is not in it.
309
+ *
310
+ * Calls are limited to Solid's primitives, signal and memo accessors, and
311
+ * methods of known object literals. A use of another component's props
312
+ * runs code of its parent, so it counts as a call. A component's own props
313
+ * are replaced when it is inlined.
314
+ */
315
+ export function isClosed(context: PassContext, root: Node, options: ClosedOptions): boolean {
316
+ let closed = true;
317
+ const visit = (node: Node): void => {
318
+ if (!closed) {
319
+ return;
320
+ }
321
+ switch (node.type) {
322
+ case 'JSXAttribute':
323
+ if (isHandlerFunction(node)) {
324
+ return;
325
+ }
326
+ break;
327
+ case 'JSXSpreadAttribute':
328
+ // A view of the component's own props is expanded when it inlines.
329
+ if (!isOwnView(context, node.argument, options.props, 0)) {
330
+ closed = false;
331
+ return;
332
+ }
333
+ break;
334
+ case 'JSXSpreadChild':
335
+ case 'NewExpression':
336
+ case 'TaggedTemplateExpression':
337
+ case 'ImportExpression':
338
+ closed = false;
339
+ return;
340
+ case 'JSXElement':
341
+ if (!isVisibleElement(context, node, options)) {
342
+ closed = false;
343
+ return;
344
+ }
345
+ break;
346
+ case 'CallExpression':
347
+ if (!isVisibleCall(context, node, options)) {
348
+ closed = false;
349
+ return;
350
+ }
351
+ break;
352
+ case 'Identifier': {
353
+ // Another component's props run its parent's code when read, and
354
+ // passing them on, as to `mergeProps()`, reads them somewhere else. A
355
+ // binding declared under `root`, like a callback's parameter, is a value.
356
+ const binding = context.scopes.references.get(node);
357
+ if (binding && runsOutsideCode(context, binding, root, options, 0)) {
358
+ closed = false;
359
+ return;
360
+ }
361
+ break;
362
+ }
363
+ default:
364
+ break;
365
+ }
366
+ forEachChild(node, visit);
367
+ };
368
+ visit(root);
369
+ return closed;
370
+ }
371
+
372
+ /**
373
+ * Whether using a binding declared outside `root` can run code that is not
374
+ * under `root`:
375
+ *
376
+ * - another component's props, whose getters run its parent's code;
377
+ * - a value built from them, like `mergeDefaultProps(defaults, props)`,
378
+ * whose getters do the same;
379
+ * - a function, which `root` can call or pass on to be called.
380
+ *
381
+ * A component's own props, and values built from them, are replaced when
382
+ * it is inlined.
383
+ */
384
+ function runsOutsideCode(
385
+ context: PassContext,
386
+ binding: Binding,
387
+ root: Node,
388
+ options: ClosedOptions,
389
+ depth: number,
390
+ ): boolean {
391
+ const { identifier, declaration } = binding;
392
+ if (
393
+ binding === options.props ||
394
+ (identifier.start >= root.start && identifier.end <= root.end) ||
395
+ isAccessor(context, binding) ||
396
+ // Calls of Solid's own functions are checked where they are made.
397
+ solidExport(binding, context.options) !== undefined
398
+ ) {
399
+ return false;
400
+ }
401
+ if (binding.kind === 'param' || binding.kind === 'function' || depth > 4) {
402
+ return true;
403
+ }
404
+ if (declaration.type !== 'VariableDeclarator' || !declaration.init) {
405
+ return false;
406
+ }
407
+ const init = unwrap(declaration.init);
408
+ if (isFunctionNode(init)) {
409
+ return true;
410
+ }
411
+ let found = false;
412
+ const visit = (node: Node): void => {
413
+ if (found) {
414
+ return;
415
+ }
416
+ if (node.type === 'Identifier') {
417
+ const target = context.scopes.references.get(node);
418
+ if (
419
+ target &&
420
+ target !== binding &&
421
+ (target.kind === 'param' || target.kind === 'const' || target.kind === 'let') &&
422
+ runsOutsideCode(context, target, root, options, depth + 1)
423
+ ) {
424
+ found = true;
425
+ return;
426
+ }
427
+ }
428
+ forEachChild(node, visit);
429
+ };
430
+ visit(init);
431
+ return found;
432
+ }
433
+
434
+ /**
435
+ * Whether an expression is a `mergeProps()` or `splitProps()` view of a
436
+ * component's own props, with only literal objects and keys besides.
437
+ */
438
+ function isOwnView(
439
+ context: PassContext,
440
+ node: Expression,
441
+ props: Binding | undefined,
442
+ depth: number,
443
+ ): boolean {
444
+ const expression = unwrap(node);
445
+ if (props === undefined || depth > 4) {
446
+ return false;
447
+ }
448
+ let call: Node | undefined = expression;
449
+ if (expression.type === 'Identifier') {
450
+ const binding = context.scopes.references.get(expression);
451
+ if (binding === props) {
452
+ return true;
453
+ }
454
+ call = binding ? viewInit(context, binding) : undefined;
455
+ }
456
+ if (call?.type !== 'CallExpression') {
457
+ return false;
458
+ }
459
+ const callee = solidCallee(context, call);
460
+ if (callee !== 'mergeProps' && callee !== 'splitProps') {
461
+ return false;
462
+ }
463
+ return call.arguments.every((argument) => {
464
+ if (argument.type === 'SpreadElement') {
465
+ return false;
466
+ }
467
+ const inner = unwrap(argument);
468
+ return (
469
+ inner.type === 'ObjectExpression' ||
470
+ (inner.type === 'ArrayExpression' &&
471
+ inner.elements.every((key) => key?.type === 'Literal' && typeof key.value === 'string')) ||
472
+ isOwnView(context, inner, props, depth + 1)
473
+ );
474
+ });
475
+ }
476
+
477
+ /**
478
+ * The call a view binding comes from: `const view = mergeProps(...)`, or
479
+ * one of the names in `const [a, b] = splitProps(...)`.
480
+ */
481
+ function viewInit(context: PassContext, binding: Binding): Node | undefined {
482
+ const init = constantInit(context, binding);
483
+ if (init) {
484
+ return unwrap(init);
485
+ }
486
+ const { declaration } = binding;
487
+ if (
488
+ binding.mutated ||
489
+ binding.kind !== 'const' ||
490
+ declaration.type !== 'VariableDeclarator' ||
491
+ declaration.id.type !== 'ArrayPattern' ||
492
+ !declaration.id.elements.some((element) => element === binding.identifier) ||
493
+ !declaration.init
494
+ ) {
495
+ return undefined;
496
+ }
497
+ return unwrap(declaration.init);
498
+ }
499
+
500
+ function isVisibleElement(
501
+ context: PassContext,
502
+ element: JSXElement,
503
+ options: ClosedOptions,
504
+ ): boolean {
505
+ const { name } = element.openingElement;
506
+ if (providerContext(context, name)) {
507
+ return true;
508
+ }
509
+ if (name.type !== 'JSXIdentifier') {
510
+ return false;
511
+ }
512
+ if (isIntrinsicTag(name.name)) {
513
+ return true;
514
+ }
515
+ const binding = context.scopes.references.get(name);
516
+ const identity = binding ? solidExport(binding, context.options) : name.name;
517
+ // `<Dynamic>` renders a component it is given, which is not visible.
518
+ if (identity !== undefined && identity !== 'Dynamic' && context.options.builtIns.has(identity)) {
519
+ return true;
520
+ }
521
+ return options.component(element);
522
+ }
523
+
524
+ function isVisibleCall(
525
+ context: PassContext,
526
+ call: CallExpression,
527
+ options: ClosedOptions,
528
+ ): boolean {
529
+ const callee = unwrap(call.callee);
530
+ if (callee.type === 'MemberExpression') {
531
+ return isVisibleMethod(context, callee, options);
532
+ }
533
+ if (callee.type !== 'Identifier') {
534
+ return false;
535
+ }
536
+ const binding = context.scopes.references.get(callee);
537
+ if (!binding) {
538
+ return false;
539
+ }
540
+ const identity = solidExport(binding, context.options);
541
+ if (identity !== undefined) {
542
+ return CONTEXT_SAFE_PRIMITIVES.includes(identity);
543
+ }
544
+ return isAccessorValue(context, callee, options, 0);
545
+ }
546
+
547
+ /**
548
+ * Whether an expression evaluates to a signal, store, or memo accessor,
549
+ * through bindings that never change and reads of a context whose value is
550
+ * known.
551
+ */
552
+ function isAccessorValue(
553
+ context: PassContext,
554
+ node: Expression,
555
+ options: ClosedOptions,
556
+ depth: number,
557
+ ): boolean {
558
+ const expression = unwrap(node);
559
+ if (depth > 4) {
560
+ return false;
561
+ }
562
+ if (expression.type === 'CallExpression') {
563
+ const value = contextValueOf(context, expression, options);
564
+ return value !== undefined && isAccessorValue(context, value, options, depth + 1);
565
+ }
566
+ if (expression.type !== 'Identifier') {
567
+ return false;
568
+ }
569
+ const binding = context.scopes.references.get(expression);
570
+ if (!binding) {
571
+ return false;
572
+ }
573
+ if (isAccessor(context, binding)) {
574
+ return true;
575
+ }
576
+ const init = constantInit(context, binding);
577
+ return init !== undefined && isAccessorValue(context, init, options, depth + 1);
578
+ }
579
+
580
+ /**
581
+ * The initializer of a binding that never changes, declared on its own.
582
+ */
583
+ function constantInit(context: PassContext, binding: Binding): Expression | undefined {
584
+ const { declaration } = binding;
585
+ if (
586
+ !isConstantDeclaration(binding, context.options) ||
587
+ declaration.type !== 'VariableDeclarator' ||
588
+ declaration.id !== binding.identifier ||
589
+ !declaration.init
590
+ ) {
591
+ return undefined;
592
+ }
593
+ return declaration.init;
594
+ }
595
+
596
+ /**
597
+ * The value `useContext(Ctx)` returns, when the provider is known.
598
+ */
599
+ function contextValueOf(
600
+ context: PassContext,
601
+ call: CallExpression,
602
+ options: ClosedOptions,
603
+ ): Expression | undefined {
604
+ const argument = call.arguments.at(0);
605
+ if (
606
+ solidCallee(context, call) !== 'useContext' ||
607
+ call.arguments.length !== 1 ||
608
+ argument === undefined ||
609
+ argument.type === 'SpreadElement'
610
+ ) {
611
+ return undefined;
612
+ }
613
+ const target = contextBinding(context, unwrap(argument));
614
+ return target ? options.contextValue?.(target) : undefined;
615
+ }
616
+
617
+ /**
618
+ * Whether calling `object.name()` runs only visible code: the object is an
619
+ * object literal, directly or through bindings that never change or a
620
+ * context read, and the property is an accessor or a visible function.
621
+ */
622
+ function isVisibleMethod(
623
+ context: PassContext,
624
+ member: MemberExpression,
625
+ options: ClosedOptions,
626
+ ): boolean {
627
+ if (member.computed || member.property.type !== 'Identifier' || member.optional) {
628
+ return false;
629
+ }
630
+ const object = objectLiteralOf(context, member.object, options, 0);
631
+ if (!object || object.properties.some((property) => property.type !== 'Property')) {
632
+ return false;
633
+ }
634
+ const { name } = member.property;
635
+ const matches = object.properties.filter(
636
+ (property) =>
637
+ property.type === 'Property' &&
638
+ !property.computed &&
639
+ property.key.type === 'Identifier' &&
640
+ property.key.name === name,
641
+ );
642
+ const property = matches.at(0);
643
+ if (matches.length !== 1 || property?.type !== 'Property' || property.kind !== 'init') {
644
+ return false;
645
+ }
646
+ const value = unwrap(property.value);
647
+ if (isFunctionNode(value)) {
648
+ return isClosed(context, value, options);
649
+ }
650
+ if (value.type !== 'Identifier') {
651
+ return false;
652
+ }
653
+ const binding = context.scopes.references.get(value);
654
+ if (!binding) {
655
+ return false;
656
+ }
657
+ const identity = solidExport(binding, context.options);
658
+ return identity === undefined
659
+ ? isAccessorValue(context, value, options, 0)
660
+ : CONTEXT_SAFE_PRIMITIVES.includes(identity);
661
+ }
662
+
663
+ /**
664
+ * The object literal an expression evaluates to, through bindings that
665
+ * never change and reads of a context whose value is known.
666
+ */
667
+ function objectLiteralOf(
668
+ context: PassContext,
669
+ node: Expression,
670
+ options: ClosedOptions,
671
+ depth: number,
672
+ ): ObjectExpression | undefined {
673
+ const expression = unwrap(node);
674
+ if (depth > 4) {
675
+ return undefined;
676
+ }
677
+ if (expression.type === 'ObjectExpression') {
678
+ return expression;
679
+ }
680
+ if (expression.type === 'CallExpression') {
681
+ const value = contextValueOf(context, expression, options);
682
+ return value ? objectLiteralOf(context, value, options, depth + 1) : undefined;
683
+ }
684
+ if (expression.type !== 'Identifier') {
685
+ return undefined;
686
+ }
687
+ const binding = context.scopes.references.get(expression);
688
+ const init = binding ? constantInit(context, binding) : undefined;
689
+ return init ? objectLiteralOf(context, init, options, depth + 1) : undefined;
690
+ }
691
+
692
+ /**
693
+ * The `useContext(Ctx)` calls under `root` that run under its owner, so
694
+ * not in an event handler, and that no other provider of `Ctx` under
695
+ * `root` answers.
696
+ */
697
+ export function contextReads(context: PassContext, root: Node, target: Binding): CallExpression[] {
698
+ const reads: CallExpression[] = [];
699
+ const visit = (node: Node): void => {
700
+ if (node.type === 'JSXAttribute' && isHandlerFunction(node)) {
701
+ return;
702
+ }
703
+ // A read under another provider of the same context belongs to that one.
704
+ if (
705
+ node !== root &&
706
+ node.type === 'JSXElement' &&
707
+ providerContext(context, node.openingElement.name) === target
708
+ ) {
709
+ return;
710
+ }
711
+ if (node.type === 'CallExpression' && solidCallee(context, node) === 'useContext') {
712
+ const argument = node.arguments.at(0);
713
+ if (
714
+ node.arguments.length === 1 &&
715
+ argument?.type !== 'SpreadElement' &&
716
+ argument !== undefined &&
717
+ contextBinding(context, unwrap(argument)) === target
718
+ ) {
719
+ reads.push(node);
720
+ }
721
+ }
722
+ forEachChild(node, visit);
723
+ };
724
+ visit(root);
725
+ return reads;
726
+ }
727
+
728
+ /**
729
+ * Whether a provider of the same context sits under `element`. A read under
730
+ * it belongs to it, so the inner one is rewritten first.
731
+ */
732
+ export function hasNestedProvider(context: PassContext, provider: Provider): boolean {
733
+ let nested = false;
734
+ const visit = (node: Node): void => {
735
+ if (nested) {
736
+ return;
737
+ }
738
+ if (
739
+ node !== provider.element &&
740
+ node.type === 'JSXElement' &&
741
+ providerContext(context, node.openingElement.name) === provider.context
742
+ ) {
743
+ nested = true;
744
+ return;
745
+ }
746
+ forEachChild(node, visit);
747
+ };
748
+ for (const child of provider.element.children) {
749
+ visit(child);
750
+ }
751
+ return nested;
752
+ }
753
+
754
+ /**
755
+ * Every provider in the program, outermost first.
756
+ */
757
+ export function findProviders(context: PassContext): Provider[] {
758
+ const providers: Provider[] = [];
759
+ const visit = (node: Node): void => {
760
+ if (node.type === 'JSXElement') {
761
+ const provider = providerOf(context, node);
762
+ if (provider) {
763
+ providers.push(provider);
764
+ }
765
+ }
766
+ forEachChild(node, visit);
767
+ };
768
+ visit(context.program);
769
+ return providers;
770
+ }
771
+
772
+ class ProviderRemover {
773
+ changed = false;
774
+
775
+ constructor(private readonly context: PassContext) {}
776
+
777
+ private readonly removed: JSXElement[] = [];
778
+
779
+ run(): void {
780
+ for (const provider of findProviders(this.context)) {
781
+ // A provider inside one removed in this pass waits for the next pass,
782
+ // so their edits do not overlap.
783
+ const { element } = provider;
784
+ const overlaps = this.removed.some(
785
+ (other) => element.start < other.end && other.start < element.end,
786
+ );
787
+ if (!overlaps && !hasNestedProvider(this.context, provider) && this.tryRemove(provider)) {
788
+ this.removed.push(element);
789
+ }
790
+ }
791
+ }
792
+
793
+ private tryRemove(provider: Provider): boolean {
794
+ const { element } = provider;
795
+ const children = element.children;
796
+ const closed = children.every((child) =>
797
+ isClosed(this.context, child, {
798
+ component: () => false,
799
+ contextValue: (target) => (target === provider.context ? provider.value : undefined),
800
+ }),
801
+ );
802
+ if (!closed) {
803
+ return false;
804
+ }
805
+ const reads = children.flatMap((child) => contextReads(this.context, child, provider.context));
806
+ const texts: string[] = [];
807
+ for (const read of reads) {
808
+ const text = stableValueText(this.context, provider, read);
809
+ if (text === undefined) {
810
+ return false;
811
+ }
812
+ texts.push(text);
813
+ }
814
+ // With no reads, the value is only dropped when evaluating it does nothing.
815
+ if (reads.length === 0 && !isSideEffectFree(provider.value)) {
816
+ const stable = stableValueText(this.context, provider, element);
817
+ if (stable === undefined) {
818
+ return false;
819
+ }
820
+ }
821
+ const { s } = this.context;
822
+ for (const [index, read] of reads.entries()) {
823
+ s.overwrite(read.start, read.end, texts[index] ?? '');
824
+ }
825
+ const { openingElement, closingElement } = element;
826
+ s.overwrite(openingElement.start, openingElement.end, '<>');
827
+ if (closingElement) {
828
+ s.overwrite(closingElement.start, closingElement.end, '</>');
829
+ }
830
+ this.changed = true;
831
+ return true;
832
+ }
833
+ }
834
+
835
+ /**
836
+ * Runs the provider pass over a parsed program. Returns whether anything changed.
837
+ */
838
+ export function removeProviders(context: PassContext): boolean {
839
+ const remover = new ProviderRemover(context);
840
+ remover.run();
841
+ return remover.changed;
842
+ }