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
package/src/inline.ts ADDED
@@ -0,0 +1,2028 @@
1
+ /**
2
+ * The inline pass: replaces a component call with the component's body.
3
+ *
4
+ * `<Card title="Hi" />` with `function Card(props) { return <div>{props.title}</div>; }`
5
+ * becomes `<div>{"Hi"}</div>`. The JSX transform then sees one tree instead of
6
+ * two, so it emits one template, one clone, and fewer hydration markers.
7
+ *
8
+ * A component inlines when its shape keeps the result equivalent:
9
+ *
10
+ * - It is declared once at the top level of the module, with a capitalized
11
+ * name, as a function declaration or a `const` bound to a function.
12
+ * - It takes no parameter, or one identifier that is only read as `props.name`.
13
+ * - Its body is statements followed by one final `return` of JSX, or an arrow
14
+ * function whose body is JSX.
15
+ * - It does not use `this`, `arguments`, `new.target`, or `super`.
16
+ *
17
+ * A call site inlines when it passes plain attributes: no spread, no `ref`,
18
+ * and no namespaced attribute.
19
+ *
20
+ * # How props keep their meaning
21
+ *
22
+ * Solid passes a dynamic prop as a getter, so every read of `props.name`
23
+ * evaluates the attribute's expression again. Inlining replaces each read
24
+ * with the expression itself, which does the same.
25
+ *
26
+ * A static prop, such as an identifier or a function, is evaluated once when
27
+ * the component is created. Its expression is substituted directly when that
28
+ * gives the same value, such as a literal or a binding nothing reassigns, or
29
+ * when the prop is read exactly once. Otherwise its value is stored in a
30
+ * `const` before the component body runs.
31
+ *
32
+ * # Where a component body can go
33
+ *
34
+ * A component whose body is only JSX inlines anywhere JSX can go.
35
+ *
36
+ * Statements, and stored props, have to run where the component would have
37
+ * been created. Solid runs a component untracked, so the statements move into
38
+ * the function whose returned JSX holds the call: a component itself, which
39
+ * also runs untracked. The call has to be in that returned JSX with only
40
+ * intrinsic elements and fragments around it, so it is created exactly once
41
+ * each time that function runs.
42
+ *
43
+ * A context provider is a component, so statements do not move out of it,
44
+ * and `useContext` still runs under it. The exception is a provider whose
45
+ * subtree only runs visible code. Statements move out through it, and each
46
+ * `useContext` of its context in a copy becomes its value. See `provider.ts`.
47
+ *
48
+ * The props can also be read through `mergeProps()` and `splitProps()` views
49
+ * declared in the component. Each call site knows which props it passes, so
50
+ * a read of a view resolves to a prop, a prop with a literal default, a
51
+ * default, or `undefined`, and a spread of a view becomes the attributes it
52
+ * holds.
53
+ *
54
+ * # Accepted differences
55
+ *
56
+ * - A prop that is a function and is called as `props.name()` runs with
57
+ * `this` set to its own receiver instead of the props object.
58
+ * - Statements moved into the host run before the host's JSX is created,
59
+ * instead of while it is created. The order of `onMount` and effect
60
+ * registration across siblings can change.
61
+ */
62
+ import MagicString from 'magic-string';
63
+ import type {
64
+ ArrowFunctionExpression,
65
+ CallExpression,
66
+ Expression,
67
+ Function as FunctionNode,
68
+ JSXAttribute,
69
+ JSXChild,
70
+ JSXElement,
71
+ JSXExpressionContainer,
72
+ JSXFragment,
73
+ JSXSpreadAttribute,
74
+ MemberExpression,
75
+ Node,
76
+ ReturnStatement,
77
+ Statement,
78
+ } from 'oxc-parser';
79
+ import {
80
+ forEachChild,
81
+ isFunctionNode,
82
+ isInsignificant,
83
+ isIntrinsicTag,
84
+ isJSXChild,
85
+ isPrimary,
86
+ unwrap,
87
+ } from './ast';
88
+ import type { PassContext, ResolvedOptions } from './context';
89
+ import { isConstantDeclaration, textOf } from './context';
90
+ import type { Piece } from './jsx';
91
+ import type { ClosedOptions, Provider } from './provider';
92
+ import {
93
+ contextReads,
94
+ findProviders,
95
+ isClosed,
96
+ providerContext,
97
+ solidCallee,
98
+ stableValueText,
99
+ } from './provider';
100
+ import { keptPiece, replacedPiece, writePieces } from './jsx';
101
+ import type { Binding, Scope } from './scope';
102
+ import { isWithinScope, lookup, scopeAt } from './scope';
103
+ import { SizeEstimator, copySize } from './size';
104
+ import { evaluate, literalText } from './value';
105
+
106
+ type ComponentFunction = FunctionNode | ArrowFunctionExpression;
107
+
108
+ interface ReadCount {
109
+ /** Whether the read can run more than once per component instance. */
110
+ readonly repeated: boolean;
111
+ }
112
+
113
+ interface PropRead extends ReadCount {
114
+ readonly member: MemberExpression;
115
+ readonly name: string;
116
+ }
117
+
118
+ /**
119
+ * One source of a `mergeProps()` or `splitProps()` view: the props, or an
120
+ * object of literal defaults, with the keys a `splitProps()` hides from it
121
+ * or keeps only.
122
+ */
123
+ interface ViewSource {
124
+ /** The default of each key, as literal text, or `undefined` for the props. */
125
+ readonly defaults: ReadonlyMap<string, string> | undefined;
126
+ readonly hidden: ReadonlySet<string>;
127
+ /** The only keys it holds, for a group `splitProps()` picked. */
128
+ readonly only: ReadonlySet<string> | undefined;
129
+ }
130
+
131
+ /** A props object made with `mergeProps()` and `splitProps()`, in source order. */
132
+ interface View {
133
+ readonly sources: readonly ViewSource[];
134
+ }
135
+
136
+ interface ViewRead extends PropRead {
137
+ readonly view: View;
138
+ }
139
+
140
+ /**
141
+ * What a key of a view reads as at a call site: the prop, the prop with a
142
+ * default for when it is `undefined`, or a text.
143
+ */
144
+ type Resolution =
145
+ | { readonly kind: 'props' }
146
+ | { readonly kind: 'fallback'; readonly text: string }
147
+ | { readonly kind: 'text'; readonly text: string };
148
+
149
+ interface ResolvedSpread {
150
+ readonly spread: ViewSpread;
151
+ readonly keys: ReadonlyMap<string, Resolution>;
152
+ }
153
+
154
+ interface ResolvedViews {
155
+ /** Reads of the props, including view reads the props answer. */
156
+ readonly propReads: readonly PropRead[];
157
+ /** View reads the props answer, unless the prop is `undefined`. */
158
+ readonly fallbacks: ReadonlyMap<PropRead, string>;
159
+ /** View reads a default or nothing answers, and their text. */
160
+ readonly texts: ReadonlyMap<Node, string>;
161
+ readonly spreads: readonly ResolvedSpread[];
162
+ }
163
+
164
+ /**
165
+ * A prop read that falls back to a default when the prop is `undefined`,
166
+ * the way `mergeProps()` reads it.
167
+ */
168
+ function withFallback(text: string, fallback: string): string {
169
+ return `((value) => (value !== undefined ? value : ${fallback}))(${text})`;
170
+ }
171
+
172
+ function allows(source: ViewSource, key: string): boolean {
173
+ return !source.hidden.has(key) && (source.only === undefined || source.only.has(key));
174
+ }
175
+
176
+ /**
177
+ * Whether an expression passed as a prop is never `undefined`.
178
+ */
179
+ function isDefinedExpression(node: Expression): boolean {
180
+ const inner = unwrap(node);
181
+ switch (inner.type) {
182
+ case 'ObjectExpression':
183
+ case 'ArrayExpression':
184
+ case 'ArrowFunctionExpression':
185
+ case 'FunctionExpression':
186
+ case 'ClassExpression':
187
+ case 'NewExpression':
188
+ case 'TemplateLiteral':
189
+ case 'JSXElement':
190
+ case 'JSXFragment':
191
+ return true;
192
+ default:
193
+ return evaluate(inner, () => undefined)?.value !== undefined;
194
+ }
195
+ }
196
+
197
+ interface ViewSpread extends ReadCount {
198
+ readonly attribute: JSXSpreadAttribute;
199
+ readonly element: JSXElement;
200
+ readonly view: View;
201
+ }
202
+
203
+ interface OuterReference {
204
+ readonly name: string;
205
+ readonly binding: Binding | undefined;
206
+ }
207
+
208
+ interface Component {
209
+ readonly binding: Binding;
210
+ readonly fn: ComponentFunction;
211
+ /** The statement that declares the component, when it can be removed. */
212
+ readonly declaration: Node | undefined;
213
+ readonly statements: readonly Statement[];
214
+ readonly root: JSXElement | JSXFragment;
215
+ readonly props: readonly PropRead[];
216
+ /** The props parameter, when there is one. */
217
+ readonly param: Binding | undefined;
218
+ /** Reads of a `mergeProps()` or `splitProps()` view, which a call site resolves. */
219
+ readonly viewReads: readonly ViewRead[];
220
+ /** Spreads of a view onto an element, which become the attributes it holds. */
221
+ readonly viewSpreads: readonly ViewSpread[];
222
+ /** The declarations of the views, which a copy drops. */
223
+ readonly viewDeclarations: readonly Statement[];
224
+ /** Bindings declared inside the component, which get fresh names in every copy. */
225
+ readonly locals: readonly Binding[];
226
+ /** References to bindings outside the component, which must mean the same at the call site. */
227
+ readonly outer: readonly OuterReference[];
228
+ }
229
+
230
+ interface CallSite {
231
+ readonly component: Component;
232
+ readonly element: JSXElement;
233
+ }
234
+
235
+ /** A copy of a component, ready to replace a call site. */
236
+ interface PreparedSite {
237
+ readonly element: JSXElement;
238
+ /** Where the statements go, when there are any. */
239
+ readonly host: { fn: Node; host: Host } | undefined;
240
+ readonly statements: string[];
241
+ readonly root: string;
242
+ }
243
+
244
+ function isWithin(node: Node, container: Node): boolean {
245
+ return node.start >= container.start && node.end <= container.end;
246
+ }
247
+
248
+ /**
249
+ * Orders call sites so every call inside a component's body comes before
250
+ * the calls to that component, and every call nested inside another call's
251
+ * element comes before that call. An outer call copies the current text of
252
+ * the calls inside it, so they must be done first.
253
+ */
254
+ function inBodyOrder(sites: readonly CallSite[]): CallSite[] {
255
+ const pending = [...sites];
256
+ const ordered: CallSite[] = [];
257
+ while (pending.length > 0) {
258
+ const ready = pending.filter(
259
+ (site) =>
260
+ !pending.some(
261
+ (other) =>
262
+ other !== site &&
263
+ (isWithin(other.element, site.component.fn) || isWithin(other.element, site.element)),
264
+ ),
265
+ );
266
+ // A cycle cannot happen, since a component that renders itself is not
267
+ // inlined, but falling back to the original order keeps this finite.
268
+ const next = ready.length > 0 ? ready : pending;
269
+ for (const site of next) {
270
+ ordered.push(site);
271
+ pending.splice(pending.indexOf(site), 1);
272
+ }
273
+ }
274
+ return ordered;
275
+ }
276
+
277
+ /**
278
+ * Where a component's statements go.
279
+ */
280
+ type Host =
281
+ | { readonly kind: 'return'; readonly statement: ReturnStatement }
282
+ | { readonly kind: 'arrow'; readonly body: Expression };
283
+
284
+ /**
285
+ * How one prop is read in a copy of the component.
286
+ */
287
+ type PropValue =
288
+ /** Replaced with an expression at every read. */
289
+ | { readonly kind: 'expression'; readonly text: string; readonly primary: boolean }
290
+ /** JSX, spliced in place when read as a JSX child. */
291
+ | { readonly kind: 'jsx'; readonly text: string; readonly primary: boolean }
292
+ /** JSX children, spliced in place when read as a JSX child. */
293
+ | {
294
+ readonly kind: 'children';
295
+ readonly children: readonly JSXChild[];
296
+ readonly text: string;
297
+ readonly primary: boolean;
298
+ };
299
+
300
+ const UNDEFINED: PropValue = { kind: 'expression', text: 'void 0', primary: false };
301
+
302
+ function isCapitalized(name: string): boolean {
303
+ return /^[A-Z]/.test(name);
304
+ }
305
+
306
+ function isReservedPropName(name: string): boolean {
307
+ return name === '__proto__' || Object.hasOwn(Object.prototype, name);
308
+ }
309
+
310
+ /**
311
+ * Whether `node` uses what its enclosing function provides: `this`,
312
+ * `arguments`, `super`, `new.target`, `await`, or `yield`. Moving such code
313
+ * into another function would change what it refers to.
314
+ */
315
+ export function usesFunctionContext(context: PassContext, node: Node): boolean {
316
+ let found = false;
317
+ const visit = (current: Node): void => {
318
+ if (found) {
319
+ return;
320
+ }
321
+ switch (current.type) {
322
+ case 'ThisExpression':
323
+ case 'Super':
324
+ case 'AwaitExpression':
325
+ case 'YieldExpression':
326
+ found = true;
327
+ return;
328
+ case 'MetaProperty':
329
+ found = current.meta.name === 'new';
330
+ return;
331
+ case 'Identifier':
332
+ // `arguments` and a direct `eval` read the function they run in.
333
+ found =
334
+ (current.name === 'arguments' || current.name === 'eval') &&
335
+ context.scopes.references.has(current) &&
336
+ context.scopes.references.get(current) === undefined;
337
+ break;
338
+ // These have their own `this`, `arguments`, and `new.target`.
339
+ case 'FunctionDeclaration':
340
+ case 'FunctionExpression':
341
+ case 'ClassDeclaration':
342
+ case 'ClassExpression':
343
+ return;
344
+ default:
345
+ forEachChild(current, visit);
346
+ }
347
+ };
348
+ forEachChild(node, visit);
349
+ return found;
350
+ }
351
+
352
+ /**
353
+ * Whether `node` contains a `return` that belongs to the function being searched.
354
+ */
355
+ function containsReturn(node: Node): boolean {
356
+ let found = false;
357
+ const visit = (current: Node): void => {
358
+ if (found || isFunctionNode(current)) {
359
+ return;
360
+ }
361
+ if (current.type === 'ReturnStatement') {
362
+ found = true;
363
+ return;
364
+ }
365
+ forEachChild(current, visit);
366
+ };
367
+ visit(node);
368
+ return found;
369
+ }
370
+
371
+ /**
372
+ * Whether Solid would pass an attribute expression as a getter. The JSX
373
+ * transform wraps any expression that reads a member or calls a function.
374
+ */
375
+ function isDynamic(node: Node): boolean {
376
+ let found = false;
377
+ const visit = (current: Node): void => {
378
+ if (found) {
379
+ return;
380
+ }
381
+ switch (current.type) {
382
+ case 'CallExpression':
383
+ case 'NewExpression':
384
+ case 'MemberExpression':
385
+ case 'TaggedTemplateExpression':
386
+ case 'ChainExpression':
387
+ case 'JSXElement':
388
+ case 'JSXFragment':
389
+ found = true;
390
+ break;
391
+ case 'ArrowFunctionExpression':
392
+ case 'FunctionExpression':
393
+ break;
394
+ default:
395
+ forEachChild(current, visit);
396
+ }
397
+ };
398
+ visit(node);
399
+ return found;
400
+ }
401
+
402
+ /**
403
+ * Whether any expression short of a sequence can replace `node` without
404
+ * parentheses, because its slot is a whole expression of its own.
405
+ */
406
+ export function acceptsAnyExpression(context: PassContext, node: Node): boolean {
407
+ const parent = context.parents.get(node);
408
+ if (!parent) {
409
+ return false;
410
+ }
411
+ switch (parent.type) {
412
+ case 'JSXExpressionContainer':
413
+ case 'JSXSpreadAttribute':
414
+ case 'SpreadElement':
415
+ case 'ArrayExpression':
416
+ case 'TemplateLiteral':
417
+ case 'ReturnStatement':
418
+ return true;
419
+ case 'CallExpression':
420
+ case 'NewExpression':
421
+ return parent.callee !== node;
422
+ case 'VariableDeclarator':
423
+ return parent.init === node;
424
+ case 'AssignmentExpression':
425
+ return parent.right === node;
426
+ case 'Property':
427
+ return parent.value === node && !parent.shorthand;
428
+ default:
429
+ return false;
430
+ }
431
+ }
432
+
433
+ /**
434
+ * The function a top-level binding declares, if it declares one.
435
+ */
436
+ function functionOf(binding: Binding, options: ResolvedOptions): ComponentFunction | undefined {
437
+ const { declaration } = binding;
438
+ if (binding.kind === 'function' && declaration.type === 'FunctionDeclaration') {
439
+ return declaration;
440
+ }
441
+ if (
442
+ isConstantDeclaration(binding, options) &&
443
+ declaration.type === 'VariableDeclarator' &&
444
+ declaration.id === binding.identifier &&
445
+ declaration.init
446
+ ) {
447
+ const init = unwrap(declaration.init);
448
+ if (init.type === 'ArrowFunctionExpression' || init.type === 'FunctionExpression') {
449
+ return init;
450
+ }
451
+ }
452
+ return undefined;
453
+ }
454
+
455
+ /**
456
+ * The attributes of a call site by name, or `undefined` when one cannot be inlined.
457
+ */
458
+ function attributesOf(element: JSXElement): Map<string, JSXAttribute> | undefined {
459
+ const attributes = new Map<string, JSXAttribute>();
460
+ for (const attribute of element.openingElement.attributes) {
461
+ // A spread can supply any prop, and a namespaced attribute or `ref` is
462
+ // something the JSX transform handles on its own.
463
+ if (
464
+ attribute.type !== 'JSXAttribute' ||
465
+ attribute.name.type !== 'JSXIdentifier' ||
466
+ attribute.name.name === 'ref' ||
467
+ attributes.has(attribute.name.name)
468
+ ) {
469
+ return undefined;
470
+ }
471
+ attributes.set(attribute.name.name, attribute);
472
+ }
473
+ return attributes;
474
+ }
475
+
476
+ function isAssignmentTarget(context: PassContext, node: Node): boolean {
477
+ const parent = context.parents.get(node);
478
+ if (!parent) {
479
+ return false;
480
+ }
481
+ switch (parent.type) {
482
+ case 'AssignmentExpression':
483
+ return parent.left === node;
484
+ case 'UpdateExpression':
485
+ return true;
486
+ case 'UnaryExpression':
487
+ return parent.operator === 'delete';
488
+ case 'ForInStatement':
489
+ case 'ForOfStatement':
490
+ return parent.left === node;
491
+ case 'ArrayPattern':
492
+ case 'ObjectPattern':
493
+ case 'RestElement':
494
+ return true;
495
+ case 'AssignmentPattern':
496
+ return parent.left === node;
497
+ case 'Property':
498
+ return parent.value === node && context.parents.get(parent)?.type === 'ObjectPattern';
499
+ case 'ParenthesizedExpression':
500
+ return isAssignmentTarget(context, parent);
501
+ default:
502
+ return false;
503
+ }
504
+ }
505
+
506
+ class Inliner {
507
+ changed = false;
508
+
509
+ private readonly hosts = new Map<Node, { host: Host; texts: string[] }>();
510
+
511
+ /**
512
+ * Providers whose subtree is closed, so statements can move out through
513
+ * them. Each maps to the text its reads become, or `undefined` when a
514
+ * binding that never changes is read at each site.
515
+ */
516
+ private readonly transparent = new Map<JSXElement, { provider: Provider; text?: string }>();
517
+
518
+ constructor(private readonly context: PassContext) {}
519
+
520
+ // ---------------------------------------------------------------------------
521
+ // Components
522
+ // ---------------------------------------------------------------------------
523
+
524
+ private scopeOf(fn: ComponentFunction): Scope | undefined {
525
+ return this.context.scopes.scopes.get(fn);
526
+ }
527
+
528
+ /**
529
+ * The statement to remove once nothing uses the component, or `undefined`
530
+ * when the declaration has to stay, like an exported one.
531
+ */
532
+ private removableDeclaration(binding: Binding): Node | undefined {
533
+ const { declaration } = binding;
534
+ if (declaration.type === 'FunctionDeclaration') {
535
+ return this.context.parents.get(declaration)?.type === 'Program' ? declaration : undefined;
536
+ }
537
+ const statement = this.context.parents.get(declaration);
538
+ if (
539
+ statement?.type === 'VariableDeclaration' &&
540
+ statement.declarations.length === 1 &&
541
+ this.context.parents.get(statement)?.type === 'Program'
542
+ ) {
543
+ return statement;
544
+ }
545
+ return undefined;
546
+ }
547
+
548
+ private analyzeComponent(binding: Binding): Component | undefined {
549
+ if (!isCapitalized(binding.name) || binding.mutated) {
550
+ return undefined;
551
+ }
552
+ const fn = functionOf(binding, this.context.options);
553
+ if (!fn || fn.async || fn.generator || !fn.body || fn.params.length > 1) {
554
+ return undefined;
555
+ }
556
+ const scope = this.scopeOf(fn);
557
+ if (!scope) {
558
+ return undefined;
559
+ }
560
+
561
+ // The body: statements, then one `return` of JSX.
562
+ let statements: Statement[] = [];
563
+ let root: Expression;
564
+ if (fn.body.type === 'BlockStatement') {
565
+ const body = fn.body.body;
566
+ const last = body.at(-1);
567
+ if (last?.type !== 'ReturnStatement' || !last.argument) {
568
+ return undefined;
569
+ }
570
+ const rest: Statement[] = [];
571
+ for (const statement of body.slice(0, -1)) {
572
+ // A directive like `"use strict"` changes how the body runs.
573
+ // TypeScript's AST gives every expression statement a `directive`
574
+ // key, which is `null` unless the statement is a directive.
575
+ const directive = 'directive' in statement ? statement.directive : null;
576
+ if (typeof directive === 'string' || containsReturn(statement)) {
577
+ return undefined;
578
+ }
579
+ rest.push(statement);
580
+ }
581
+ statements = rest;
582
+ root = unwrap(last.argument);
583
+ } else {
584
+ root = unwrap(fn.body);
585
+ }
586
+ if (root.type !== 'JSXElement' && root.type !== 'JSXFragment') {
587
+ return undefined;
588
+ }
589
+ if (usesFunctionContext(this.context, fn.body)) {
590
+ return undefined;
591
+ }
592
+
593
+ // The parameter is only read as `props.name`.
594
+ const param = fn.params.at(0);
595
+ let paramBinding: Binding | undefined;
596
+ if (param) {
597
+ if (param.type !== 'Identifier') {
598
+ return undefined;
599
+ }
600
+ paramBinding = scope.bindings.get(param.name);
601
+ if (!paramBinding || paramBinding.mutated) {
602
+ return undefined;
603
+ }
604
+ }
605
+ const views = this.analyzeViews(fn, scope, statements, paramBinding);
606
+ if (!views) {
607
+ return undefined;
608
+ }
609
+ const props: PropRead[] = [];
610
+ for (const reference of paramBinding?.references ?? []) {
611
+ if (views.arguments.has(reference)) {
612
+ continue;
613
+ }
614
+ const read = this.propRead(fn, reference);
615
+ if (!read) {
616
+ return undefined;
617
+ }
618
+ props.push(read);
619
+ }
620
+ statements = statements.filter((statement) => !views.declarations.includes(statement));
621
+
622
+ const locals: Binding[] = [];
623
+ const seen = new Set<Scope>();
624
+ for (const inner of this.context.scopes.scopes.values()) {
625
+ if (seen.has(inner) || !isWithinScope(inner, scope)) {
626
+ continue;
627
+ }
628
+ seen.add(inner);
629
+ for (const local of inner.bindings.values()) {
630
+ // A view's declaration and every use of it are replaced in a copy.
631
+ if (local !== paramBinding && !views.bindings.has(local)) {
632
+ locals.push(local);
633
+ }
634
+ }
635
+ }
636
+
637
+ const outer: OuterReference[] = [];
638
+ for (const [reference, target] of this.context.scopes.references) {
639
+ if (reference.start < fn.start || reference.end > fn.end) {
640
+ continue;
641
+ }
642
+ // A component that renders itself cannot be inlined into itself.
643
+ if (target === binding) {
644
+ return undefined;
645
+ }
646
+ if (target && isWithinScope(target.scope, scope)) {
647
+ continue;
648
+ }
649
+ if (reference.type === 'Identifier' || reference.type === 'JSXIdentifier') {
650
+ outer.push({ name: reference.name, binding: target });
651
+ }
652
+ }
653
+
654
+ return {
655
+ binding,
656
+ fn,
657
+ declaration: this.removableDeclaration(binding),
658
+ statements,
659
+ root,
660
+ props,
661
+ param: paramBinding,
662
+ viewReads: views.reads,
663
+ viewSpreads: views.spreads,
664
+ viewDeclarations: views.declarations,
665
+ locals,
666
+ outer,
667
+ };
668
+ }
669
+
670
+ private propRead(fn: ComponentFunction, reference: Node): PropRead | undefined {
671
+ const member = this.context.parents.get(reference);
672
+ if (member?.type !== 'MemberExpression' || member.object !== reference) {
673
+ return undefined;
674
+ }
675
+ let name: string;
676
+ if (!member.computed && member.property.type === 'Identifier') {
677
+ name = member.property.name;
678
+ } else if (
679
+ member.computed &&
680
+ member.property.type === 'Literal' &&
681
+ typeof member.property.value === 'string'
682
+ ) {
683
+ name = member.property.value;
684
+ } else {
685
+ return undefined;
686
+ }
687
+ if (isReservedPropName(name) || isAssignmentTarget(this.context, member)) {
688
+ return undefined;
689
+ }
690
+ return { member, name, repeated: this.isRepeated(fn, member) };
691
+ }
692
+
693
+ /**
694
+ * Whether `node` can run more than once each time `fn` runs.
695
+ */
696
+ private isRepeated(fn: ComponentFunction, node: Node): boolean {
697
+ let current = this.context.parents.get(node);
698
+ while (current && current !== fn) {
699
+ if (
700
+ isFunctionNode(current) ||
701
+ current.type === 'ForStatement' ||
702
+ current.type === 'ForInStatement' ||
703
+ current.type === 'ForOfStatement' ||
704
+ current.type === 'WhileStatement' ||
705
+ current.type === 'DoWhileStatement'
706
+ ) {
707
+ return true;
708
+ }
709
+ current = this.context.parents.get(current);
710
+ }
711
+ return false;
712
+ }
713
+
714
+ /**
715
+ * Finds the `mergeProps()` and `splitProps()` views of the props declared
716
+ * in a component's statements, and how each is used. A view can only be
717
+ * read as `view.name`, spread onto an element, or passed to another view.
718
+ * `undefined` when a view is used any other way.
719
+ */
720
+ private analyzeViews(
721
+ fn: ComponentFunction,
722
+ scope: Scope,
723
+ statements: readonly Statement[],
724
+ param: Binding | undefined,
725
+ ):
726
+ | {
727
+ bindings: Set<Binding>;
728
+ arguments: Set<Node>;
729
+ declarations: Statement[];
730
+ reads: ViewRead[];
731
+ spreads: ViewSpread[];
732
+ }
733
+ | undefined {
734
+ const views = new Map<Binding, View>();
735
+ const args = new Set<Node>();
736
+ const declarations: Statement[] = [];
737
+ for (const statement of statements) {
738
+ const declarator =
739
+ statement.type === 'VariableDeclaration' ? statement.declarations.at(0) : undefined;
740
+ if (
741
+ statement.type !== 'VariableDeclaration' ||
742
+ statement.kind !== 'const' ||
743
+ statement.declarations.length !== 1 ||
744
+ !declarator?.init
745
+ ) {
746
+ continue;
747
+ }
748
+ const init = unwrap(declarator.init);
749
+ if (init.type !== 'CallExpression') {
750
+ continue;
751
+ }
752
+ const callee = solidCallee(this.context, init);
753
+ let declared: [Node | null, View][] | null | undefined;
754
+ if (callee === 'mergeProps' && declarator.id.type === 'Identifier') {
755
+ const view = this.viewOf(init, param, views, args);
756
+ declared = view ? [[declarator.id, view]] : view;
757
+ } else if (callee === 'splitProps' && declarator.id.type === 'ArrayPattern') {
758
+ declared = this.splitViews(init, declarator.id.elements, param, views, args);
759
+ } else {
760
+ continue;
761
+ }
762
+ if (declared === null) {
763
+ continue;
764
+ }
765
+ if (!declared) {
766
+ return undefined;
767
+ }
768
+ for (const [identifier, view] of declared) {
769
+ if (identifier?.type !== 'Identifier') {
770
+ continue;
771
+ }
772
+ const binding = scope.bindings.get(identifier.name);
773
+ if (!binding || binding.mutated) {
774
+ return undefined;
775
+ }
776
+ views.set(binding, view);
777
+ }
778
+ declarations.push(statement);
779
+ }
780
+
781
+ const reads: ViewRead[] = [];
782
+ const spreads: ViewSpread[] = [];
783
+ for (const [binding, view] of views) {
784
+ for (const reference of binding.references) {
785
+ if (args.has(reference)) {
786
+ continue;
787
+ }
788
+ const parent = this.context.parents.get(reference);
789
+ const opening = parent ? this.context.parents.get(parent) : undefined;
790
+ const element = opening ? this.context.parents.get(opening) : undefined;
791
+ if (
792
+ parent?.type === 'JSXSpreadAttribute' &&
793
+ opening?.type === 'JSXOpeningElement' &&
794
+ element?.type === 'JSXElement'
795
+ ) {
796
+ spreads.push({
797
+ attribute: parent,
798
+ element,
799
+ view,
800
+ repeated: this.isRepeated(fn, parent),
801
+ });
802
+ continue;
803
+ }
804
+ const read = this.propRead(fn, reference);
805
+ if (!read) {
806
+ return undefined;
807
+ }
808
+ reads.push({ ...read, view });
809
+ }
810
+ }
811
+ return { bindings: new Set(views.keys()), arguments: args, declarations, reads, spreads };
812
+ }
813
+
814
+ /**
815
+ * The sources a view argument stands for: the props, a view, or a nested
816
+ * `mergeProps()` call.
817
+ */
818
+ private viewSources(
819
+ argument: Node,
820
+ param: Binding | undefined,
821
+ views: ReadonlyMap<Binding, View>,
822
+ args: Set<Node>,
823
+ ): readonly ViewSource[] | undefined {
824
+ if (argument.type === 'CallExpression') {
825
+ if (solidCallee(this.context, argument) !== 'mergeProps') {
826
+ return undefined;
827
+ }
828
+ return this.viewOf(argument, param, views, args)?.sources;
829
+ }
830
+ if (argument.type !== 'Identifier') {
831
+ return undefined;
832
+ }
833
+ const binding = this.context.scopes.references.get(argument);
834
+ if (binding && binding === param) {
835
+ return [{ defaults: undefined, hidden: new Set(), only: undefined }];
836
+ }
837
+ return binding ? views.get(binding)?.sources : undefined;
838
+ }
839
+
840
+ /**
841
+ * The view a `mergeProps()` call makes. `null` when it does not take the
842
+ * props or another view, and `undefined` when it does but its other
843
+ * arguments are not literal objects.
844
+ */
845
+ private viewOf(
846
+ call: CallExpression,
847
+ param: Binding | undefined,
848
+ views: ReadonlyMap<Binding, View>,
849
+ args: Set<Node>,
850
+ ): View | null | undefined {
851
+ const involved = call.arguments.some(
852
+ (argument) =>
853
+ argument.type !== 'SpreadElement' &&
854
+ this.viewSources(unwrap(argument), param, views, new Set()) !== undefined,
855
+ );
856
+ if (!involved) {
857
+ return null;
858
+ }
859
+ const sources: ViewSource[] = [];
860
+ for (const argument of call.arguments) {
861
+ if (argument.type === 'SpreadElement') {
862
+ return undefined;
863
+ }
864
+ const inner = unwrap(argument);
865
+ const existing = this.viewSources(inner, param, views, args);
866
+ if (existing) {
867
+ args.add(inner);
868
+ sources.push(...existing);
869
+ continue;
870
+ }
871
+ if (inner.type !== 'ObjectExpression') {
872
+ return undefined;
873
+ }
874
+ const defaults = new Map<string, string>();
875
+ for (const property of inner.properties) {
876
+ if (property.type !== 'Property' || property.kind !== 'init' || property.computed) {
877
+ return undefined;
878
+ }
879
+ let key: string;
880
+ if (property.key.type === 'Identifier') {
881
+ key = property.key.name;
882
+ } else if (property.key.type === 'Literal' && typeof property.key.value === 'string') {
883
+ key = property.key.value;
884
+ } else {
885
+ return undefined;
886
+ }
887
+ const value = evaluate(property.value, () => undefined);
888
+ const text = value ? literalText(value.value) : undefined;
889
+ if (text === undefined || isReservedPropName(key)) {
890
+ return undefined;
891
+ }
892
+ defaults.set(key, text);
893
+ }
894
+ sources.push({ defaults, hidden: new Set(), only: undefined });
895
+ }
896
+ return { sources };
897
+ }
898
+
899
+ /**
900
+ * The views `const [a, b, rest] = splitProps(view, ['x'], ['y'])` makes,
901
+ * each with its identifier. A key belongs to the first group that names
902
+ * it, and the last view holds the keys no group names. `null` when the
903
+ * call does not take the props or a view.
904
+ */
905
+ private splitViews(
906
+ call: CallExpression,
907
+ elements: readonly (Node | null)[],
908
+ param: Binding | undefined,
909
+ views: ReadonlyMap<Binding, View>,
910
+ args: Set<Node>,
911
+ ): [Node | null, View][] | null | undefined {
912
+ const first = call.arguments.at(0);
913
+ if (first === undefined || first.type === 'SpreadElement') {
914
+ return null;
915
+ }
916
+ const target = unwrap(first);
917
+ const base = this.viewSources(target, param, views, args);
918
+ if (!base) {
919
+ return null;
920
+ }
921
+ args.add(target);
922
+ const groups: string[][] = [];
923
+ for (const group of call.arguments.slice(1)) {
924
+ if (group.type !== 'ArrayExpression') {
925
+ return undefined;
926
+ }
927
+ const keys: string[] = [];
928
+ for (const key of group.elements) {
929
+ if (key?.type !== 'Literal' || typeof key.value !== 'string') {
930
+ return undefined;
931
+ }
932
+ keys.push(key.value);
933
+ }
934
+ groups.push(keys);
935
+ }
936
+ if (
937
+ elements.length > groups.length + 1 ||
938
+ elements.some((element) => element?.type === 'RestElement')
939
+ ) {
940
+ return undefined;
941
+ }
942
+ const claimed = new Set<string>();
943
+ const filters = groups.map((keys) => {
944
+ const owned = keys.filter((key) => !claimed.has(key));
945
+ for (const key of owned) {
946
+ claimed.add(key);
947
+ }
948
+ return new Set(owned);
949
+ });
950
+ return elements.map((element, index): [Node | null, View] => {
951
+ const only = filters.at(index);
952
+ const sources = base.map((source) => ({
953
+ defaults: source.defaults,
954
+ hidden: only ? source.hidden : new Set([...source.hidden, ...claimed]),
955
+ only: only
956
+ ? new Set([...only].filter((key) => source.only === undefined || source.only.has(key)))
957
+ : source.only,
958
+ }));
959
+ return [element, { sources }];
960
+ });
961
+ }
962
+
963
+ /**
964
+ * Whether a function is a component, which Solid runs untracked. Only a
965
+ * capitalized function bound at its declaration counts.
966
+ */
967
+ private isComponentFunction(fn: Node): boolean {
968
+ if (fn.type === 'FunctionDeclaration') {
969
+ return !fn.async && !fn.generator && fn.id !== null && isCapitalized(fn.id.name);
970
+ }
971
+ if (fn.type !== 'FunctionExpression' && fn.type !== 'ArrowFunctionExpression') {
972
+ return false;
973
+ }
974
+ if (fn.async || fn.generator) {
975
+ return false;
976
+ }
977
+ let parent = this.context.parents.get(fn);
978
+ while (parent?.type === 'ParenthesizedExpression') {
979
+ parent = this.context.parents.get(parent);
980
+ }
981
+ return (
982
+ parent?.type === 'VariableDeclarator' &&
983
+ parent.id.type === 'Identifier' &&
984
+ isCapitalized(parent.id.name)
985
+ );
986
+ }
987
+
988
+ /**
989
+ * Where the statements of a component created at `element` can go: the
990
+ * returned JSX of a component, with only intrinsic elements, fragments,
991
+ * and closed providers between it and the call.
992
+ */
993
+ private hostOf(element: JSXElement): { fn: Node; host: Host } | undefined {
994
+ let node: Node = element;
995
+ for (;;) {
996
+ const parent = this.context.parents.get(node);
997
+ if (!parent) {
998
+ return undefined;
999
+ }
1000
+ if (parent.type === 'JSXElement') {
1001
+ const { name } = parent.openingElement;
1002
+ const passable =
1003
+ this.transparent.has(parent) ||
1004
+ this.assumedHosts?.has(parent) === true ||
1005
+ (name.type === 'JSXIdentifier' && isIntrinsicTag(name.name));
1006
+ if (!passable) {
1007
+ return undefined;
1008
+ }
1009
+ const child = node;
1010
+ if (!parent.children.some((item) => item === child)) {
1011
+ return undefined;
1012
+ }
1013
+ } else if (parent.type === 'ReturnStatement') {
1014
+ const list = this.context.parents.get(parent);
1015
+ if (list?.type !== 'BlockStatement' && list?.type !== 'SwitchCase') {
1016
+ return undefined;
1017
+ }
1018
+ let fn = this.context.parents.get(list);
1019
+ while (fn && !isFunctionNode(fn)) {
1020
+ fn = this.context.parents.get(fn);
1021
+ }
1022
+ if (!fn || !this.isComponentFunction(fn)) {
1023
+ return undefined;
1024
+ }
1025
+ return { fn, host: { kind: 'return', statement: parent } };
1026
+ } else if (parent.type === 'ArrowFunctionExpression') {
1027
+ if (parent.body !== node || !this.isComponentFunction(parent)) {
1028
+ return undefined;
1029
+ }
1030
+ return { fn: parent, host: { kind: 'arrow', body: parent.body } };
1031
+ } else if (parent.type !== 'JSXFragment' && parent.type !== 'ParenthesizedExpression') {
1032
+ return undefined;
1033
+ }
1034
+ node = parent;
1035
+ }
1036
+ }
1037
+
1038
+ private childrenValue(
1039
+ element: JSXElement,
1040
+ reads: readonly ReadCount[],
1041
+ fresh: (base: string) => string,
1042
+ snapshots: string[],
1043
+ ): PropValue | undefined {
1044
+ const { children } = element;
1045
+ if (children.some((child) => child.type === 'JSXSpreadChild')) {
1046
+ return undefined;
1047
+ }
1048
+ const significant = children.filter((child) => !isInsignificant(child));
1049
+ const only = significant.at(0);
1050
+ if (only === undefined) {
1051
+ return { kind: 'children', children: [], text: 'void 0', primary: false };
1052
+ }
1053
+ let text: string;
1054
+ let primary = true;
1055
+ if (significant.length > 1 || only.type === 'JSXText') {
1056
+ text = `<>${this.context.s.slice(element.openingElement.end, element.closingElement?.start ?? element.end)}</>`;
1057
+ } else if (only.type === 'JSXExpressionContainer') {
1058
+ if (only.expression.type === 'JSXEmptyExpression') {
1059
+ return undefined;
1060
+ }
1061
+ // A single expression is passed like an attribute value, such as a
1062
+ // render function that has to stay one function.
1063
+ const value = this.expressionValue(only.expression, 'children', reads, fresh, snapshots);
1064
+ if (value.kind !== 'expression' || value.text !== textOf(this.context, only.expression)) {
1065
+ return value;
1066
+ }
1067
+ text = value.text;
1068
+ primary = value.primary;
1069
+ } else {
1070
+ text = textOf(this.context, only);
1071
+ }
1072
+ return { kind: 'children', children, text, primary };
1073
+ }
1074
+
1075
+ /**
1076
+ * How a prop reads in a copy of the component, and the `const` that stores
1077
+ * it first when the value has to be evaluated once.
1078
+ */
1079
+ private propValue(
1080
+ attribute: JSXAttribute | undefined,
1081
+ reads: readonly ReadCount[],
1082
+ fresh: (base: string) => string,
1083
+ snapshots: string[],
1084
+ ): PropValue | undefined {
1085
+ if (!attribute) {
1086
+ return UNDEFINED;
1087
+ }
1088
+ const { value } = attribute;
1089
+ if (value === null) {
1090
+ return { kind: 'expression', text: 'true', primary: true };
1091
+ }
1092
+ switch (value.type) {
1093
+ case 'Literal':
1094
+ // An attribute string can hold HTML entities, which are not decoded here.
1095
+ if (value.value.includes('&')) {
1096
+ return undefined;
1097
+ }
1098
+ return { kind: 'expression', text: JSON.stringify(value.value), primary: true };
1099
+ case 'JSXElement':
1100
+ case 'JSXFragment':
1101
+ return { kind: 'jsx', text: textOf(this.context, value), primary: true };
1102
+ default:
1103
+ break;
1104
+ }
1105
+ const { expression } = value;
1106
+ if (expression.type === 'JSXEmptyExpression') {
1107
+ return undefined;
1108
+ }
1109
+ const name = attribute.name.type === 'JSXIdentifier' ? attribute.name.name : 'prop';
1110
+ return this.expressionValue(expression, name, reads, fresh, snapshots);
1111
+ }
1112
+
1113
+ /**
1114
+ * How an expression passed as a prop reads in a copy of the component.
1115
+ */
1116
+ private expressionValue(
1117
+ expression: Expression,
1118
+ name: string,
1119
+ reads: readonly ReadCount[],
1120
+ fresh: (base: string) => string,
1121
+ snapshots: string[],
1122
+ ): PropValue {
1123
+ const text = textOf(this.context, expression);
1124
+ const inner = unwrap(expression);
1125
+ if (inner.type === 'JSXElement' || inner.type === 'JSXFragment') {
1126
+ return { kind: 'jsx', text, primary: true };
1127
+ }
1128
+ const primary = isPrimary(expression);
1129
+ if (isDynamic(expression) || this.isStable(inner)) {
1130
+ return { kind: 'expression', text, primary };
1131
+ }
1132
+ // A static value is evaluated once. One read that runs once keeps that.
1133
+ const read = reads.at(0);
1134
+ if (reads.length === 1 && read && !read.repeated) {
1135
+ return { kind: 'expression', text, primary };
1136
+ }
1137
+ const local = fresh(name);
1138
+ snapshots.push(`const ${local} = ${text};`);
1139
+ return { kind: 'expression', text: local, primary: true };
1140
+ }
1141
+
1142
+ /**
1143
+ * Whether evaluating `node` again gives the same value.
1144
+ */
1145
+ private isStable(node: Node): boolean {
1146
+ switch (node.type) {
1147
+ case 'Literal':
1148
+ // A regular expression literal creates a new object each time.
1149
+ return !('regex' in node);
1150
+ case 'TemplateLiteral':
1151
+ return node.expressions.length === 0;
1152
+ case 'UnaryExpression':
1153
+ return node.operator === '-' && node.argument.type === 'Literal';
1154
+ case 'Identifier': {
1155
+ const { references } = this.context.scopes;
1156
+ if (!references.has(node)) {
1157
+ return false;
1158
+ }
1159
+ const binding = references.get(node);
1160
+ if (!binding) {
1161
+ return node.name === 'undefined' || node.name === 'NaN' || node.name === 'Infinity';
1162
+ }
1163
+ return !binding.mutated;
1164
+ }
1165
+ default:
1166
+ return false;
1167
+ }
1168
+ }
1169
+
1170
+ /** The names `freshName` takes from while copies are only measured. */
1171
+ private scratchNames: Set<string> | undefined;
1172
+
1173
+ /**
1174
+ * Component calls measured as if they were inlined already, so the calls
1175
+ * in their children can hoist statements through them.
1176
+ */
1177
+ private assumedHosts: ReadonlySet<JSXElement> | undefined;
1178
+
1179
+ private freshName(base: string): string {
1180
+ const names = this.scratchNames ?? this.context.scopes.names;
1181
+ let index = 1;
1182
+ let name = `${base}$${String(index)}`;
1183
+ while (names.has(name)) {
1184
+ index += 1;
1185
+ name = `${base}$${String(index)}`;
1186
+ }
1187
+ names.add(name);
1188
+ return name;
1189
+ }
1190
+
1191
+ /**
1192
+ * The copy of `component` that would replace `element`, or `undefined`
1193
+ * when it cannot be inlined there. Nothing is written until `commit`.
1194
+ */
1195
+ private prepare(component: Component, element: JSXElement): PreparedSite | undefined {
1196
+ const attributes = attributesOf(element);
1197
+ if (!attributes) {
1198
+ return undefined;
1199
+ }
1200
+ const hasChildren = element.children.some((child) => !isInsignificant(child));
1201
+ if (hasChildren && attributes.has('children')) {
1202
+ return undefined;
1203
+ }
1204
+ for (const attribute of attributes.values()) {
1205
+ if (attribute.value && usesFunctionContext(this.context, attribute.value)) {
1206
+ return undefined;
1207
+ }
1208
+ }
1209
+ for (const child of element.children) {
1210
+ if (usesFunctionContext(this.context, child)) {
1211
+ return undefined;
1212
+ }
1213
+ }
1214
+
1215
+ // What each view read and spread resolves to at this call site.
1216
+ const views = this.resolveViews(component, element, attributes, hasChildren);
1217
+ if (!views) {
1218
+ return undefined;
1219
+ }
1220
+
1221
+ // What each prop reads as.
1222
+ const snapshots: string[] = [];
1223
+ const fresh = (base: string): string => this.freshName(base);
1224
+ const readsByName = new Map<string, ReadCount[]>();
1225
+ const count = (name: string, read: ReadCount): void => {
1226
+ const reads = readsByName.get(name) ?? [];
1227
+ reads.push(read);
1228
+ readsByName.set(name, reads);
1229
+ };
1230
+ for (const read of views.propReads) {
1231
+ count(read.name, read);
1232
+ }
1233
+ for (const read of views.fallbacks.keys()) {
1234
+ count(read.name, read);
1235
+ }
1236
+ for (const spread of views.spreads) {
1237
+ for (const [key, resolution] of spread.keys) {
1238
+ if (resolution.kind !== 'text') {
1239
+ count(key, spread.spread);
1240
+ }
1241
+ }
1242
+ }
1243
+ const values = new Map<string, PropValue>();
1244
+ for (const [name, reads] of readsByName) {
1245
+ let value: PropValue | undefined;
1246
+ if (name === 'children' && !attributes.has('children')) {
1247
+ value = this.childrenValue(element, reads, fresh, snapshots);
1248
+ } else {
1249
+ value = this.propValue(attributes.get(name), reads, fresh, snapshots);
1250
+ }
1251
+ if (!value) {
1252
+ return undefined;
1253
+ }
1254
+ values.set(name, value);
1255
+ }
1256
+
1257
+ // The component's outer references must mean the same at the call site.
1258
+ const scope = scopeAt(this.context.scopes, this.context.parents, element);
1259
+ for (const reference of component.outer) {
1260
+ if (lookup(scope, reference.name) !== reference.binding) {
1261
+ return undefined;
1262
+ }
1263
+ }
1264
+
1265
+ const hoisted = component.statements.length > 0 || snapshots.length > 0;
1266
+ const host = hoisted ? this.hostOf(element) : undefined;
1267
+ if (hoisted && !host) {
1268
+ return undefined;
1269
+ }
1270
+
1271
+ const contextTexts = this.contextTexts(component, element);
1272
+ if (!contextTexts) {
1273
+ return undefined;
1274
+ }
1275
+
1276
+ // Build the copy on the original code, so this pass's other edits stay out of it.
1277
+ const copy = new MagicString(this.context.code);
1278
+ this.renameLocals(copy, component, fresh);
1279
+ this.substituteProps(copy, views.propReads, values);
1280
+ this.substituteViews(copy, component, element, views, values);
1281
+ for (const [read, text] of contextTexts) {
1282
+ copy.overwrite(read.start, read.end, text);
1283
+ }
1284
+
1285
+ const statements = [...snapshots];
1286
+ const first = component.statements.at(0);
1287
+ const last = component.statements.at(-1);
1288
+ if (first && last) {
1289
+ statements.push(copy.slice(first.start, last.end));
1290
+ }
1291
+ return {
1292
+ element,
1293
+ host,
1294
+ statements,
1295
+ root: copy.slice(component.root.start, component.root.end),
1296
+ };
1297
+ }
1298
+
1299
+ /**
1300
+ * Writes a prepared copy over its call site.
1301
+ */
1302
+ private commit(site: PreparedSite): void {
1303
+ this.context.s.overwrite(site.element.start, site.element.end, site.root);
1304
+ if (site.host) {
1305
+ const entry = this.hosts.get(site.host.fn) ?? { host: site.host.host, texts: [] };
1306
+ entry.texts.push(...site.statements);
1307
+ this.hosts.set(site.host.fn, entry);
1308
+ }
1309
+ }
1310
+
1311
+ /**
1312
+ * The context reads in a component's copy at `element` that a closed
1313
+ * provider above it answers, with the text each becomes. `undefined` when
1314
+ * a read cannot take the value there.
1315
+ */
1316
+ private contextTexts(component: Component, element: JSXElement): Map<Node, string> | undefined {
1317
+ const texts = new Map<Node, string>();
1318
+ for (const { provider, text } of this.answeringProviders(element)) {
1319
+ for (const read of contextReads(this.context, component.fn, provider.context)) {
1320
+ const value = text ?? stableValueText(this.context, provider, element);
1321
+ if (value === undefined) {
1322
+ return undefined;
1323
+ }
1324
+ texts.set(read, value);
1325
+ }
1326
+ }
1327
+ return texts;
1328
+ }
1329
+
1330
+ /**
1331
+ * The closed providers that answer context reads at `element`. The nearest
1332
+ * provider of each context answers its reads, closed or not.
1333
+ */
1334
+ private answeringProviders(element: JSXElement): { provider: Provider; text?: string }[] {
1335
+ const answering: { provider: Provider; text?: string }[] = [];
1336
+ const seen = new Set<Binding>();
1337
+ for (
1338
+ let node = this.context.parents.get(element);
1339
+ node;
1340
+ node = this.context.parents.get(node)
1341
+ ) {
1342
+ const target =
1343
+ node.type === 'JSXElement'
1344
+ ? providerContext(this.context, node.openingElement.name)
1345
+ : undefined;
1346
+ if (node.type !== 'JSXElement' || !target || seen.has(target)) {
1347
+ continue;
1348
+ }
1349
+ seen.add(target);
1350
+ const entry = this.transparent.get(node);
1351
+ if (entry) {
1352
+ answering.push(entry);
1353
+ }
1354
+ }
1355
+ return answering;
1356
+ }
1357
+
1358
+ /**
1359
+ * Finds the providers statements can move out through: a subtree with
1360
+ * only visible code, where every component is one this pass can inline.
1361
+ * A value that is not a literal or a binding that never changes is
1362
+ * stored in a `const` of the host first, so every read gets the same one.
1363
+ */
1364
+ private findTransparentProviders(
1365
+ components: readonly Component[],
1366
+ sites: readonly CallSite[],
1367
+ ): Component[] {
1368
+ const byBinding = new Map(components.map((component) => [component.binding, component]));
1369
+ // Whether a subtree under `provider` only runs visible code, where each
1370
+ // component is one this pass inlines and is visible too.
1371
+ const closedUnder = (provider: Provider): ((node: Node) => boolean) => {
1372
+ const closedComponents = new Map<Component, boolean>();
1373
+ const options: ClosedOptions = {
1374
+ component: (element) => {
1375
+ const binding = this.context.scopes.references.get(element.openingElement.name);
1376
+ const component = binding ? byBinding.get(binding) : undefined;
1377
+ if (!component) {
1378
+ return false;
1379
+ }
1380
+ const known = closedComponents.get(component);
1381
+ if (known !== undefined) {
1382
+ return known;
1383
+ }
1384
+ // A component that renders itself is never closed.
1385
+ closedComponents.set(component, false);
1386
+ const closed = isClosed(this.context, component.fn, {
1387
+ ...options,
1388
+ props: component.param,
1389
+ });
1390
+ closedComponents.set(component, closed);
1391
+ return closed;
1392
+ },
1393
+ contextValue: (target) => (target === provider.context ? provider.value : undefined),
1394
+ };
1395
+ return (node) => isClosed(this.context, node, options);
1396
+ };
1397
+
1398
+ const changed: Component[] = [];
1399
+ for (const provider of findProviders(this.context)) {
1400
+ const { element } = provider;
1401
+ const inside = sites.some(
1402
+ (site) => isWithin(site.element, element) && site.element !== element,
1403
+ );
1404
+ if (!inside) {
1405
+ continue;
1406
+ }
1407
+ const isClosedNode = closedUnder(provider);
1408
+ const closed = element.children.every((child) => isClosedNode(child));
1409
+ if (!closed) {
1410
+ continue;
1411
+ }
1412
+ if (stableValueText(this.context, provider, element) !== undefined) {
1413
+ this.transparent.set(element, { provider });
1414
+ continue;
1415
+ }
1416
+ const host = this.hostOf(element);
1417
+ if (!host) {
1418
+ continue;
1419
+ }
1420
+ const name = this.freshName(
1421
+ `${provider.context.name.charAt(0).toLowerCase()}${provider.context.name.slice(1)}Value`,
1422
+ );
1423
+ const entry = this.hosts.get(host.fn) ?? { host: host.host, texts: [] };
1424
+ entry.texts.push(`const ${name} = ${textOf(this.context, provider.value)};`);
1425
+ this.hosts.set(host.fn, entry);
1426
+ this.context.s.overwrite(provider.value.start, provider.value.end, name);
1427
+ this.transparent.set(element, { provider, text: name });
1428
+ this.changed = true;
1429
+ for (const component of components) {
1430
+ if (isWithin(element, component.fn)) {
1431
+ changed.push(component);
1432
+ }
1433
+ }
1434
+ }
1435
+ return changed;
1436
+ }
1437
+
1438
+ /**
1439
+ * Resolves each view read and spread of a component at a call site.
1440
+ * `mergeProps()` reads the last source whose value is not `undefined`, so
1441
+ * a prop that can be `undefined` falls back to the default behind it. A
1442
+ * spread becomes the keys it holds, and its `children` become the
1443
+ * element's children. `undefined` when a spread repeats an attribute, or
1444
+ * holds `children` for an element that has some.
1445
+ */
1446
+ private resolveViews(
1447
+ component: Component,
1448
+ element: JSXElement,
1449
+ attributes: ReadonlyMap<string, JSXAttribute>,
1450
+ hasChildren: boolean,
1451
+ ): ResolvedViews | undefined {
1452
+ const has = (key: string): boolean =>
1453
+ attributes.has(key) || (key === 'children' && hasChildren);
1454
+ // Whether the prop the call site passes for `key` is never `undefined`.
1455
+ const defined = (key: string): boolean => {
1456
+ const attribute = attributes.get(key);
1457
+ if (attribute) {
1458
+ const { value } = attribute;
1459
+ if (value?.type !== 'JSXExpressionContainer') {
1460
+ return true;
1461
+ }
1462
+ return (
1463
+ value.expression.type !== 'JSXEmptyExpression' && isDefinedExpression(value.expression)
1464
+ );
1465
+ }
1466
+ const significant = element.children.filter((child) => !isInsignificant(child));
1467
+ const only = significant.at(0);
1468
+ if (significant.length !== 1 || only?.type !== 'JSXExpressionContainer') {
1469
+ return true;
1470
+ }
1471
+ return only.expression.type !== 'JSXEmptyExpression' && isDefinedExpression(only.expression);
1472
+ };
1473
+ const resolve = (view: View, key: string): Resolution => {
1474
+ const sources = view.sources.filter((source) => allows(source, key));
1475
+ for (let index = sources.length - 1; index >= 0; index -= 1) {
1476
+ const source = sources.at(index);
1477
+ const text = source?.defaults?.get(key);
1478
+ if (text !== undefined) {
1479
+ return { kind: 'text', text };
1480
+ }
1481
+ if (source && !source.defaults && has(key)) {
1482
+ if (defined(key)) {
1483
+ return { kind: 'props' };
1484
+ }
1485
+ const fallback = sources
1486
+ .slice(0, index)
1487
+ .findLast((earlier) => earlier.defaults?.has(key))
1488
+ ?.defaults?.get(key);
1489
+ return fallback === undefined ? { kind: 'props' } : { kind: 'fallback', text: fallback };
1490
+ }
1491
+ }
1492
+ return { kind: 'text', text: 'void 0' };
1493
+ };
1494
+
1495
+ const propReads: PropRead[] = [...component.props];
1496
+ const fallbacks = new Map<PropRead, string>();
1497
+ const texts = new Map<Node, string>();
1498
+ for (const read of component.viewReads) {
1499
+ const resolution = resolve(read.view, read.name);
1500
+ if (resolution.kind === 'props') {
1501
+ propReads.push(read);
1502
+ } else if (resolution.kind === 'fallback') {
1503
+ fallbacks.set(read, resolution.text);
1504
+ } else {
1505
+ texts.set(read.member, resolution.text);
1506
+ }
1507
+ }
1508
+
1509
+ const callKeys = [...attributes.keys()];
1510
+ if (hasChildren && !attributes.has('children')) {
1511
+ callKeys.push('children');
1512
+ }
1513
+ const spreads: ResolvedSpread[] = [];
1514
+ const taken = new Map<JSXElement, Set<string>>();
1515
+ for (const spread of component.viewSpreads) {
1516
+ // Keys come in the order the sources first hold them.
1517
+ const order = new Set<string>();
1518
+ for (const source of spread.view.sources) {
1519
+ const keys = source.defaults ? [...source.defaults.keys()] : callKeys;
1520
+ for (const key of keys.filter((name) => allows(source, name))) {
1521
+ order.add(key);
1522
+ }
1523
+ }
1524
+ let names = taken.get(spread.element);
1525
+ if (!names) {
1526
+ names = new Set();
1527
+ for (const attribute of spread.element.openingElement.attributes) {
1528
+ if (attribute.type === 'JSXAttribute') {
1529
+ names.add(
1530
+ attribute.name.type === 'JSXIdentifier'
1531
+ ? attribute.name.name
1532
+ : textOf(this.context, attribute.name),
1533
+ );
1534
+ }
1535
+ }
1536
+ taken.set(spread.element, names);
1537
+ }
1538
+ const keys = new Map<string, Resolution>();
1539
+ for (const key of order) {
1540
+ const resolution = resolve(spread.view, key);
1541
+ // Children become the element's children, so it must have none of its own.
1542
+ const fits =
1543
+ key === 'children'
1544
+ ? spread.element.openingElement.selfClosing && resolution.kind !== 'fallback'
1545
+ : /^[A-Za-z_$][\w$-]*$/.test(key);
1546
+ if (!fits || names.has(key)) {
1547
+ return undefined;
1548
+ }
1549
+ names.add(key);
1550
+ keys.set(key, resolution);
1551
+ }
1552
+ spreads.push({ spread, keys });
1553
+ }
1554
+ return { propReads, fallbacks, texts, spreads };
1555
+ }
1556
+
1557
+ /**
1558
+ * Writes the resolved view reads and spreads into a copy, and drops the
1559
+ * view declarations.
1560
+ */
1561
+ private substituteViews(
1562
+ copy: MagicString,
1563
+ component: Component,
1564
+ element: JSXElement,
1565
+ views: ResolvedViews,
1566
+ values: ReadonlyMap<string, PropValue>,
1567
+ ): void {
1568
+ for (const [member, text] of views.texts) {
1569
+ const bare = text !== 'void 0' || acceptsAnyExpression(this.context, member);
1570
+ copy.overwrite(member.start, member.end, bare ? text : `(${text})`);
1571
+ }
1572
+ for (const [read, fallback] of views.fallbacks) {
1573
+ const text = values.get(read.name)?.text ?? 'void 0';
1574
+ copy.overwrite(read.member.start, read.member.end, withFallback(text, fallback));
1575
+ }
1576
+ for (const { spread, keys } of views.spreads) {
1577
+ const parts: string[] = [];
1578
+ let children: string | undefined;
1579
+ for (const [key, resolution] of keys) {
1580
+ const value = values.get(key);
1581
+ if (key === 'children') {
1582
+ children = this.spreadChildren(element, resolution, value);
1583
+ continue;
1584
+ }
1585
+ let text = value?.text ?? 'void 0';
1586
+ if (resolution.kind === 'text') {
1587
+ text = resolution.text;
1588
+ } else if (resolution.kind === 'fallback') {
1589
+ text = withFallback(text, resolution.text);
1590
+ }
1591
+ parts.push(`${key}={${text}}`);
1592
+ }
1593
+ const { attribute } = spread;
1594
+ if (parts.length === 0) {
1595
+ copy.remove(attribute.start, attribute.end);
1596
+ } else {
1597
+ copy.overwrite(attribute.start, attribute.end, parts.join(' '));
1598
+ }
1599
+ if (children !== undefined) {
1600
+ const opening = spread.element.openingElement;
1601
+ const tag = textOf(this.context, opening.name);
1602
+ const close = this.context.code.lastIndexOf('/>', opening.end);
1603
+ copy.overwrite(close, opening.end, `>${children}</${tag}>`);
1604
+ }
1605
+ }
1606
+ for (const declaration of component.viewDeclarations) {
1607
+ copy.remove(declaration.start, declaration.end);
1608
+ }
1609
+ }
1610
+
1611
+ /**
1612
+ * The JSX children a spread's `children` becomes: the call site's own
1613
+ * children, or the value of a single expression or default.
1614
+ */
1615
+ private spreadChildren(
1616
+ element: JSXElement,
1617
+ resolution: Resolution,
1618
+ value: PropValue | undefined,
1619
+ ): string | undefined {
1620
+ if (resolution.kind === 'text') {
1621
+ return resolution.text === 'void 0' ? undefined : `{${resolution.text}}`;
1622
+ }
1623
+ if (!value) {
1624
+ return undefined;
1625
+ }
1626
+ if (value.kind === 'children' && element.closingElement) {
1627
+ return this.context.s.slice(element.openingElement.end, element.closingElement.start);
1628
+ }
1629
+ return `{${value.text}}`;
1630
+ }
1631
+
1632
+ private renameLocals(
1633
+ copy: MagicString,
1634
+ component: Component,
1635
+ fresh: (base: string) => string,
1636
+ ): void {
1637
+ for (const local of component.locals) {
1638
+ const name = fresh(local.name);
1639
+ for (const node of [local.identifier, ...local.references]) {
1640
+ const parent = this.context.parents.get(node);
1641
+ // `{ a }` and `{ a = 1 }` are shorthand for `{ a: a }` and `{ a: a = 1 }`.
1642
+ const shorthand =
1643
+ (parent?.type === 'Property' && parent.shorthand) ||
1644
+ (parent?.type === 'AssignmentPattern' &&
1645
+ this.context.parents.get(parent)?.type === 'Property' &&
1646
+ parent.left === node &&
1647
+ this.isShorthandValue(parent));
1648
+ copy.overwrite(node.start, node.end, shorthand ? `${local.name}: ${name}` : name);
1649
+ }
1650
+ }
1651
+ }
1652
+
1653
+ private isShorthandValue(node: Node): boolean {
1654
+ const parent = this.context.parents.get(node);
1655
+ return parent?.type === 'Property' && parent.shorthand && parent.value === node;
1656
+ }
1657
+
1658
+ private substituteProps(
1659
+ copy: MagicString,
1660
+ reads: readonly PropRead[],
1661
+ values: ReadonlyMap<string, PropValue>,
1662
+ ): void {
1663
+ // Reads that are a JSX child on their own, like `{props.children}`,
1664
+ // splice their JSX in place. They are grouped by parent so neighboring
1665
+ // text stays apart.
1666
+ const spliced = new Map<JSXElement | JSXFragment, Map<JSXChild, Piece>>();
1667
+ for (const read of reads) {
1668
+ const value = values.get(read.name);
1669
+ if (!value) {
1670
+ continue;
1671
+ }
1672
+ const container = this.context.parents.get(read.member);
1673
+ const parent = container ? this.context.parents.get(container) : undefined;
1674
+ if (
1675
+ value.kind !== 'expression' &&
1676
+ container?.type === 'JSXExpressionContainer' &&
1677
+ (parent?.type === 'JSXElement' || parent?.type === 'JSXFragment') &&
1678
+ isJSXChild(container, this.context.parents)
1679
+ ) {
1680
+ const pieces = spliced.get(parent) ?? new Map<JSXChild, Piece>();
1681
+ pieces.set(container, this.splicedPiece(container, value));
1682
+ spliced.set(parent, pieces);
1683
+ continue;
1684
+ }
1685
+ const bare = value.primary || acceptsAnyExpression(this.context, read.member);
1686
+ copy.overwrite(read.member.start, read.member.end, bare ? value.text : `(${value.text})`);
1687
+ }
1688
+ for (const [parent, pieces] of spliced) {
1689
+ writePieces(
1690
+ copy,
1691
+ parent.children.map((child) => pieces.get(child) ?? keptPiece(child)),
1692
+ );
1693
+ }
1694
+ }
1695
+
1696
+ private splicedPiece(container: JSXExpressionContainer, value: PropValue): Piece {
1697
+ if (value.kind === 'children') {
1698
+ const first = value.children.at(0);
1699
+ const last = value.children.at(-1);
1700
+ if (!first || !last) {
1701
+ return replacedPiece(container, '');
1702
+ }
1703
+ return {
1704
+ node: container,
1705
+ text: this.context.s.slice(first.start, last.end),
1706
+ startText: first.type === 'JSXText' ? first : undefined,
1707
+ endText: last.type === 'JSXText' ? last : undefined,
1708
+ };
1709
+ }
1710
+ return replacedPiece(container, value.text);
1711
+ }
1712
+
1713
+ // ---------------------------------------------------------------------------
1714
+ // Pass
1715
+ // ---------------------------------------------------------------------------
1716
+
1717
+ /**
1718
+ * The components worth inlining in this pass: those whose copies are no
1719
+ * larger than what they replace, which is their calls, and their
1720
+ * declaration when nothing else uses it.
1721
+ */
1722
+ private worthwhileComponents(
1723
+ sites: readonly CallSite[],
1724
+ postponed: ReadonlySet<Component>,
1725
+ otherUses: ReadonlyMap<Component, number>,
1726
+ ): Set<Component> {
1727
+ const byComponent = new Map<Component, JSXElement[]>();
1728
+ for (const site of sites) {
1729
+ if (!postponed.has(site.component)) {
1730
+ const elements = byComponent.get(site.component) ?? [];
1731
+ elements.push(site.element);
1732
+ byComponent.set(site.component, elements);
1733
+ }
1734
+ }
1735
+ const result = new Set<Component>();
1736
+ if (this.context.options.alwaysInline) {
1737
+ for (const component of byComponent.keys()) {
1738
+ result.add(component);
1739
+ }
1740
+ return result;
1741
+ }
1742
+ // The copies made here are only measured, so their fresh names are not kept.
1743
+ this.scratchNames = new Set(this.context.scopes.names);
1744
+ try {
1745
+ const copiesOf = new Map<Component, Map<JSXElement, PreparedSite | undefined>>();
1746
+ for (const [component, elements] of byComponent) {
1747
+ copiesOf.set(
1748
+ component,
1749
+ new Map(elements.map((element) => [element, this.prepare(component, element)])),
1750
+ );
1751
+ }
1752
+ for (const [component, byElement] of copiesOf) {
1753
+ const copies = [...byElement.values()].filter((copy) => copy !== undefined);
1754
+ if (copies.length === 0) {
1755
+ continue;
1756
+ }
1757
+ const gain =
1758
+ this.inliningGain(component, copies, this.removedShare(component, byElement, otherUses)) +
1759
+ this.enabledGain(component, copies, copiesOf, otherUses);
1760
+ if (gain >= 0) {
1761
+ result.add(component);
1762
+ }
1763
+ }
1764
+ } finally {
1765
+ this.scratchNames = undefined;
1766
+ }
1767
+ return result;
1768
+ }
1769
+
1770
+ /**
1771
+ * How much of a component's declaration inlining every call removes: all
1772
+ * of it when nothing else uses it, the module's share when other modules
1773
+ * use it too, and none when a call cannot be inlined or anything else
1774
+ * keeps it.
1775
+ */
1776
+ private removedShare(
1777
+ component: Component,
1778
+ copies: ReadonlyMap<JSXElement, PreparedSite | undefined>,
1779
+ otherUses: ReadonlyMap<Component, number>,
1780
+ ): number {
1781
+ if (
1782
+ component.declaration === undefined ||
1783
+ otherUses.get(component) !== 0 ||
1784
+ [...copies.values()].some((copy) => copy === undefined)
1785
+ ) {
1786
+ return 0;
1787
+ }
1788
+ const users = this.context.options.sharedComponents.get(component.binding.name) ?? 1;
1789
+ return users > 0 ? 1 / users : 0;
1790
+ }
1791
+
1792
+ /**
1793
+ * What inlining `component` saves through the calls in its children that
1794
+ * can only be inlined once it is: a component with statements needs an
1795
+ * element around its call to hoist them to.
1796
+ */
1797
+ private enabledGain(
1798
+ component: Component,
1799
+ copies: readonly PreparedSite[],
1800
+ copiesOf: ReadonlyMap<Component, ReadonlyMap<JSXElement, PreparedSite | undefined>>,
1801
+ otherUses: ReadonlyMap<Component, number>,
1802
+ ): number {
1803
+ const elements = copies.map((copy) => copy.element);
1804
+ this.assumedHosts = new Set(elements);
1805
+ let gain = 0;
1806
+ try {
1807
+ for (const [other, byElement] of copiesOf) {
1808
+ if (other === component) {
1809
+ continue;
1810
+ }
1811
+ const enabled = new Map(byElement);
1812
+ let changed = false;
1813
+ for (const [element, copy] of byElement) {
1814
+ if (!copy && elements.some((outer) => isWithin(element, outer))) {
1815
+ const next = this.prepare(other, element);
1816
+ enabled.set(element, next);
1817
+ changed ||= next !== undefined;
1818
+ }
1819
+ }
1820
+ if (!changed) {
1821
+ continue;
1822
+ }
1823
+ const now = [...byElement.values()].filter((copy) => copy !== undefined);
1824
+ const then = [...enabled.values()].filter((copy) => copy !== undefined);
1825
+ const before = now.length > 0 ? Math.max(0, this.inliningGain(other, now, 0)) : 0;
1826
+ const after = this.inliningGain(other, then, this.removedShare(other, enabled, otherUses));
1827
+ gain += Math.max(0, after - before);
1828
+ }
1829
+ } finally {
1830
+ this.assumedHosts = undefined;
1831
+ }
1832
+ return gain;
1833
+ }
1834
+
1835
+ /**
1836
+ * How much smaller the copies are than the calls they replace, once
1837
+ * lowered, counting the `share` of the declaration they remove.
1838
+ * Negative when they are larger.
1839
+ */
1840
+ private inliningGain(
1841
+ component: Component,
1842
+ copies: readonly PreparedSite[],
1843
+ share: number,
1844
+ ): number {
1845
+ const estimator = this.estimator();
1846
+ let calls =
1847
+ share > 0 && component.declaration ? share * estimator.node(component.declaration) : 0;
1848
+ let inlined = 0;
1849
+ for (const copy of copies) {
1850
+ const inTemplate = this.sitsInTemplate(copy.element);
1851
+ calls += estimator.jsx(copy.element, inTemplate);
1852
+ inlined += copySize(
1853
+ this.context.filename,
1854
+ this.sizeHeader(),
1855
+ copy,
1856
+ inTemplate,
1857
+ this.context.options,
1858
+ );
1859
+ }
1860
+ return calls - inlined;
1861
+ }
1862
+
1863
+ /**
1864
+ * Whether an element sits directly in an intrinsic element, whose
1865
+ * template its copy joins. A provider this pass makes transparent is
1866
+ * removed once its consumers are inlined, so the element above it counts.
1867
+ */
1868
+ private sitsInTemplate(element: JSXElement): boolean {
1869
+ let parent = this.context.parents.get(element);
1870
+ while (parent?.type === 'JSXElement' && this.transparent.has(parent)) {
1871
+ parent = this.context.parents.get(parent);
1872
+ }
1873
+ if (parent?.type === 'JSXElement' && this.assumedHosts?.has(parent) === true) {
1874
+ return true;
1875
+ }
1876
+ return (
1877
+ parent?.type === 'JSXElement' &&
1878
+ parent.openingElement.name.type === 'JSXIdentifier' &&
1879
+ isIntrinsicTag(parent.openingElement.name.name)
1880
+ );
1881
+ }
1882
+
1883
+ private sizeEstimator: SizeEstimator | undefined;
1884
+
1885
+ private estimator(): SizeEstimator {
1886
+ this.sizeEstimator ??= new SizeEstimator(this.context.code);
1887
+ return this.sizeEstimator;
1888
+ }
1889
+
1890
+ private header: string | undefined;
1891
+
1892
+ /**
1893
+ * What a copy measured on its own needs to know: the module's imports,
1894
+ * and the names that alias Solid's exports.
1895
+ */
1896
+ private sizeHeader(): string {
1897
+ if (this.header === undefined) {
1898
+ const imports = this.context.program.body
1899
+ .filter((statement) => statement.type === 'ImportDeclaration')
1900
+ .map((statement) => this.context.code.slice(statement.start, statement.end));
1901
+ const aliases = [...this.context.options.builtInAliases.keys()];
1902
+ if (aliases.length > 0) {
1903
+ imports.push(`var ${aliases.join(', ')};`);
1904
+ }
1905
+ this.header = imports.join('\n');
1906
+ }
1907
+ return this.header;
1908
+ }
1909
+
1910
+ run(): void {
1911
+ const components: Component[] = [];
1912
+ for (const binding of this.context.scopes.root.bindings.values()) {
1913
+ const component = this.analyzeComponent(binding);
1914
+ if (component) {
1915
+ components.push(component);
1916
+ }
1917
+ }
1918
+ if (components.length === 0) {
1919
+ return;
1920
+ }
1921
+
1922
+ const sites: CallSite[] = [];
1923
+ const otherUses = new Map<Component, number>();
1924
+ for (const component of components) {
1925
+ let uses = 0;
1926
+ for (const reference of component.binding.references) {
1927
+ const parent = this.context.parents.get(reference);
1928
+ if (parent?.type === 'JSXClosingElement') {
1929
+ continue;
1930
+ }
1931
+ const element = parent ? this.context.parents.get(parent) : undefined;
1932
+ if (parent?.type === 'JSXOpeningElement' && element?.type === 'JSXElement') {
1933
+ sites.push({ component, element });
1934
+ } else {
1935
+ uses += 1;
1936
+ }
1937
+ }
1938
+ otherUses.set(component, uses);
1939
+ }
1940
+
1941
+ // Inner call sites first, so an outer one copies their inlined text.
1942
+ sites.sort((a, b) => a.element.end - b.element.end);
1943
+ const inlined = new Map<Component, JSXElement[]>();
1944
+ // A component whose body changed in this pass is copied in the next one,
1945
+ // from its new body. A copy made now would miss what was inlined into it.
1946
+ const changedBodies = new Set<Component>(this.findTransparentProviders(components, sites));
1947
+ const worthwhile = this.worthwhileComponents(sites, changedBodies, otherUses);
1948
+ for (const site of inBodyOrder(sites)) {
1949
+ const postponed = changedBodies.has(site.component);
1950
+ // Each copy is made now, so it takes in the call sites inside it that
1951
+ // were inlined before it.
1952
+ const copy =
1953
+ postponed || !worthwhile.has(site.component)
1954
+ ? undefined
1955
+ : this.prepare(site.component, site.element);
1956
+ const done = copy !== undefined;
1957
+ if (copy) {
1958
+ this.commit(copy);
1959
+ this.changed = true;
1960
+ const elements = inlined.get(site.component) ?? [];
1961
+ elements.push(site.element);
1962
+ inlined.set(site.component, elements);
1963
+ } else {
1964
+ otherUses.set(site.component, (otherUses.get(site.component) ?? 0) + 1);
1965
+ }
1966
+ // A component holding a call that was inlined now, or postponed to the
1967
+ // next pass, waits too. A copy made now would copy the call as it is.
1968
+ if (done || postponed) {
1969
+ for (const component of components) {
1970
+ if (isWithin(site.element, component.fn)) {
1971
+ changedBodies.add(component);
1972
+ }
1973
+ }
1974
+ }
1975
+ }
1976
+
1977
+ this.writeHosts();
1978
+
1979
+ // A component nothing uses anymore is removed. A copy made in this pass
1980
+ // comes from the original code, so a component used inside a copied
1981
+ // component stays until the next pass inlines it there too.
1982
+ const copied = [...inlined.keys()];
1983
+ for (const [component, elements] of inlined) {
1984
+ const insideCopy = elements.some((element) =>
1985
+ copied.some(
1986
+ (other) =>
1987
+ other !== component && element.start >= other.fn.start && element.end <= other.fn.end,
1988
+ ),
1989
+ );
1990
+ if (component.declaration && otherUses.get(component) === 0 && !insideCopy) {
1991
+ this.context.s.remove(component.declaration.start, component.declaration.end);
1992
+ }
1993
+ }
1994
+ }
1995
+
1996
+ /**
1997
+ * The whitespace before `position` on its line.
1998
+ */
1999
+ private indentationAt(position: number): string {
2000
+ const { code } = this.context;
2001
+ const lineStart = code.lastIndexOf('\n', position - 1) + 1;
2002
+ return /^[ \t]*/.exec(code.slice(lineStart, position))?.[0] ?? '';
2003
+ }
2004
+
2005
+ private writeHosts(): void {
2006
+ for (const { host, texts } of this.hosts.values()) {
2007
+ if (host.kind === 'return') {
2008
+ const indent = this.indentationAt(host.statement.start);
2009
+ this.context.s.prependRight(
2010
+ host.statement.start,
2011
+ texts.map((text) => `${text}\n${indent}`).join(''),
2012
+ );
2013
+ } else {
2014
+ this.context.s.prependRight(host.body.start, `{ ${texts.join(' ')} return `);
2015
+ this.context.s.appendLeft(host.body.end, '; }');
2016
+ }
2017
+ }
2018
+ }
2019
+ }
2020
+
2021
+ /**
2022
+ * Runs the inline pass over a parsed program. Returns whether anything changed.
2023
+ */
2024
+ export function inline(context: PassContext): boolean {
2025
+ const inliner = new Inliner(context);
2026
+ inliner.run();
2027
+ return inliner.changed;
2028
+ }