solid-optimizer 1.0.0-next.1 → 1.0.0-next.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/inline.ts CHANGED
@@ -8,7 +8,9 @@
8
8
  * A component inlines when its shape keeps the result equivalent:
9
9
  *
10
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.
11
+ * name, as a function declaration or a `const` bound to a function. A
12
+ * tag of an alias, like `const Separator = SeparatorRoot`, is renamed to
13
+ * the component first. See `renameAliasTags`.
12
14
  * - It takes no parameter, or one identifier that is only read as `props.name`,
13
15
  * or spread onto an element as `{...props}`.
14
16
  * - Its body is statements followed by one final `return` of JSX, or an arrow
@@ -264,6 +266,14 @@ type PropValue =
264
266
 
265
267
  const UNDEFINED: PropValue = { kind: 'expression', text: 'void 0', primary: false };
266
268
 
269
+ /** The function a copy is wrapped in when it is measured. See `copy-size.ts`. */
270
+ const COPY_WRAPPER = 'function SoSize$$(';
271
+
272
+ /** Whether code has a JSX tag named `name`. */
273
+ function hasTag(code: string, name: string): boolean {
274
+ return new RegExp(`<${name.replaceAll('$', String.raw`\$`)}[\\s/>]`).test(code);
275
+ }
276
+
267
277
  function isCapitalized(name: string): boolean {
268
278
  return /^[A-Z]/.test(name);
269
279
  }
@@ -333,6 +343,50 @@ function containsReturn(node: Node): boolean {
333
343
  return found;
334
344
  }
335
345
 
346
+ /**
347
+ * Collects the nodes an assignment target writes through: an identifier, or
348
+ * the root of a member chain, like `cache` in `cache.items[0] = x`. A root
349
+ * that is not a name, like a call, is collected as it is.
350
+ */
351
+ function collectWriteRoots(target: Node, roots: Node[]): void {
352
+ switch (target.type) {
353
+ case 'MemberExpression':
354
+ collectWriteRoots(target.object, roots);
355
+ break;
356
+ case 'ParenthesizedExpression':
357
+ case 'TSAsExpression':
358
+ case 'TSSatisfiesExpression':
359
+ case 'TSNonNullExpression':
360
+ case 'TSTypeAssertion':
361
+ collectWriteRoots(target.expression, roots);
362
+ break;
363
+ case 'ObjectPattern':
364
+ for (const property of target.properties) {
365
+ collectWriteRoots(
366
+ property.type === 'RestElement' ? property.argument : property.value,
367
+ roots,
368
+ );
369
+ }
370
+ break;
371
+ case 'ArrayPattern':
372
+ for (const element of target.elements) {
373
+ if (element) {
374
+ collectWriteRoots(element, roots);
375
+ }
376
+ }
377
+ break;
378
+ case 'AssignmentPattern':
379
+ collectWriteRoots(target.left, roots);
380
+ break;
381
+ case 'RestElement':
382
+ collectWriteRoots(target.argument, roots);
383
+ break;
384
+ default:
385
+ roots.push(target);
386
+ break;
387
+ }
388
+ }
389
+
336
390
  /**
337
391
  * Whether Solid would pass an attribute expression as a getter. The JSX
338
392
  * transform wraps any expression that reads a member or calls a function.
@@ -420,7 +474,10 @@ function functionOf(binding: Binding, options: ResolvedOptions): ComponentFuncti
420
474
  /**
421
475
  * The attributes of a call site by name, or `undefined` when one cannot be inlined.
422
476
  */
423
- function attributesOf(element: JSXElement): Map<string, JSXAttribute> | undefined {
477
+ function attributesOf(
478
+ context: PassContext,
479
+ element: JSXElement,
480
+ ): Map<string, JSXAttribute> | undefined {
424
481
  const attributes = new Map<string, JSXAttribute>();
425
482
  for (const attribute of element.openingElement.attributes) {
426
483
  // A spread can supply any prop, and a namespaced attribute is something
@@ -428,7 +485,7 @@ function attributesOf(element: JSXElement): Map<string, JSXAttribute> | undefine
428
485
  if (
429
486
  attribute.type !== 'JSXAttribute' ||
430
487
  attribute.name.type !== 'JSXIdentifier' ||
431
- (attribute.name.name === 'ref' && !isForwardableRef(attribute)) ||
488
+ (attribute.name.name === 'ref' && !isForwardableRef(context, attribute)) ||
432
489
  attributes.has(attribute.name.name)
433
490
  ) {
434
491
  return undefined;
@@ -500,17 +557,37 @@ function isMemberRead(read: ReadCount): read is PropRead {
500
557
  * assigned the element, so it has to stay the name itself. Anything else
501
558
  * would be evaluated when the element is made, outside the `untrack` the
502
559
  * component's `ref` runs it in.
560
+ *
561
+ * Inside an array, `void 0` and `untrack(() => target)` count too. Solid
562
+ * skips an empty entry of a ref array, and evaluates the whole `ref`
563
+ * untracked. They come from a component that forwards `props.ref` in an
564
+ * array, once a call site that passes no `ref` is inlined.
503
565
  */
504
- function isForwardableRef(attribute: JSXAttribute): boolean {
566
+ function isForwardableRef(context: PassContext, attribute: JSXAttribute): boolean {
505
567
  const { value } = attribute;
506
568
  if (value?.type !== 'JSXExpressionContainer' || value.expression.type === 'JSXEmptyExpression') {
507
569
  return false;
508
570
  }
509
- const isTarget = (node: Expression): boolean => {
571
+ const isTarget = (node: Expression, inArray: boolean): boolean => {
510
572
  const inner = unwrap(node);
511
573
  if (inner.type === 'ArrayExpression') {
512
574
  return inner.elements.every(
513
- (element) => element !== null && element.type !== 'SpreadElement' && isTarget(element),
575
+ (element) =>
576
+ element !== null && element.type !== 'SpreadElement' && isTarget(element, true),
577
+ );
578
+ }
579
+ if (inArray && isVoidZero(inner)) {
580
+ return true;
581
+ }
582
+ if (inArray && inner.type === 'CallExpression' && solidCallee(context, inner) === 'untrack') {
583
+ const callback = inner.arguments.at(0);
584
+ return (
585
+ inner.arguments.length === 1 &&
586
+ callback?.type === 'ArrowFunctionExpression' &&
587
+ callback.expression &&
588
+ callback.params.length === 0 &&
589
+ callback.body.type !== 'BlockStatement' &&
590
+ isTarget(callback.body, true)
514
591
  );
515
592
  }
516
593
  return (
@@ -519,7 +596,17 @@ function isForwardableRef(attribute: JSXAttribute): boolean {
519
596
  inner.type === 'FunctionExpression'
520
597
  );
521
598
  };
522
- return isTarget(value.expression);
599
+ return isTarget(value.expression, false);
600
+ }
601
+
602
+ /** Whether an expression is `void 0`. */
603
+ function isVoidZero(node: Expression): boolean {
604
+ return (
605
+ node.type === 'UnaryExpression' &&
606
+ node.operator === 'void' &&
607
+ node.argument.type === 'Literal' &&
608
+ node.argument.value === 0
609
+ );
523
610
  }
524
611
 
525
612
  /**
@@ -655,6 +742,38 @@ class Inliner {
655
742
  return undefined;
656
743
  }
657
744
 
745
+ /**
746
+ * Whether statements assign, update, or delete through a binding declared
747
+ * outside `scope`, or through a global. Writes inside nested functions
748
+ * count too, since a function can run right away, like a memo's.
749
+ */
750
+ private writesOutside(statements: readonly Statement[], scope: Scope): boolean {
751
+ const roots: Node[] = [];
752
+ const visit = (node: Node): void => {
753
+ if (node.type === 'AssignmentExpression') {
754
+ collectWriteRoots(node.left, roots);
755
+ } else if (node.type === 'UpdateExpression') {
756
+ collectWriteRoots(node.argument, roots);
757
+ } else if (node.type === 'UnaryExpression' && node.operator === 'delete') {
758
+ collectWriteRoots(node.argument, roots);
759
+ }
760
+ forEachChild(node, visit);
761
+ };
762
+ for (const statement of statements) {
763
+ visit(statement);
764
+ }
765
+ for (const root of roots) {
766
+ if (root.type !== 'Identifier') {
767
+ return true;
768
+ }
769
+ const target = this.context.scopes.references.get(root);
770
+ if (!target || !isWithinScope(target.scope, scope)) {
771
+ return true;
772
+ }
773
+ }
774
+ return false;
775
+ }
776
+
658
777
  private analyzeComponent(binding: Binding): Component | undefined {
659
778
  if (!isCapitalized(binding.name)) {
660
779
  return undefined;
@@ -721,6 +840,12 @@ class Inliner {
721
840
  this.reason = 'component-this';
722
841
  return undefined;
723
842
  }
843
+ // A copy's statements run before any JSX of the function they move into,
844
+ // so JSX there could read a value they write later than it should.
845
+ if (this.writesOutside(statements, scope)) {
846
+ this.reason = 'component-write';
847
+ return undefined;
848
+ }
724
849
 
725
850
  // The parameter is only read as `props.name`.
726
851
  const param = fn.params.at(0);
@@ -1396,7 +1521,7 @@ class Inliner {
1396
1521
  * when it cannot be inlined there. Nothing is written until `commit`.
1397
1522
  */
1398
1523
  private prepare(component: Component, element: JSXElement): PreparedSite | undefined {
1399
- const attributes = attributesOf(element);
1524
+ const attributes = attributesOf(this.context, element);
1400
1525
  if (!attributes) {
1401
1526
  this.reason = callSiteReason(element);
1402
1527
  return undefined;
@@ -1910,10 +2035,14 @@ class Inliner {
1910
2035
  }
1911
2036
  }
1912
2037
  const result = new Set<Component>();
1913
- if (this.context.options.alwaysInline) {
1914
- for (const component of byComponent.keys()) {
2038
+ const { alwaysInline, alwaysInlineComponents } = this.context.options;
2039
+ for (const component of byComponent.keys()) {
2040
+ if (alwaysInline || alwaysInlineComponents.has(component.binding.name)) {
1915
2041
  result.add(component);
2042
+ byComponent.delete(component);
1916
2043
  }
2044
+ }
2045
+ if (byComponent.size === 0) {
1917
2046
  return result;
1918
2047
  }
1919
2048
  // The copies made here are only measured, so their fresh names are not kept.
@@ -1926,6 +2055,21 @@ class Inliner {
1926
2055
  new Map(elements.map((element) => [element, this.prepare(component, element)])),
1927
2056
  );
1928
2057
  }
2058
+ this.sites = sites;
2059
+ this.otherUses = otherUses;
2060
+ this.blocked = new Map();
2061
+ for (const [inner, byElement] of copiesOf) {
2062
+ for (const [element, copy] of byElement) {
2063
+ const outer = copy
2064
+ ? undefined
2065
+ : this.components.find((item) => item !== inner && isWithin(element, item.fn));
2066
+ if (outer) {
2067
+ const list = this.blocked.get(outer) ?? [];
2068
+ list.push(inner);
2069
+ this.blocked.set(outer, list);
2070
+ }
2071
+ }
2072
+ }
1929
2073
  for (const [component, byElement] of copiesOf) {
1930
2074
  const copies = [...byElement.values()].filter((copy) => copy !== undefined);
1931
2075
  if (copies.length === 0) {
@@ -1940,6 +2084,8 @@ class Inliner {
1940
2084
  }
1941
2085
  } finally {
1942
2086
  this.scratchNames = undefined;
2087
+ this.otherUses = undefined;
2088
+ this.blocked = new Map();
1943
2089
  }
1944
2090
  return result;
1945
2091
  }
@@ -2023,20 +2169,80 @@ class Inliner {
2023
2169
  let calls =
2024
2170
  share > 0 && component.declaration ? share * estimator.node(component.declaration) : 0;
2025
2171
  let inlined = 0;
2172
+ const blocked = this.blockedWithin(component);
2173
+ // The blocked components that some copy still calls once measured.
2174
+ const kept = new Set<Component>();
2026
2175
  for (const copy of copies) {
2027
2176
  const inTemplate = this.sitsInTemplate(copy.element);
2028
2177
  calls += estimator.jsx(copy.element, inTemplate);
2178
+ const measured = { code: '' };
2029
2179
  inlined += copySize(
2030
2180
  this.context.filename,
2031
2181
  this.sizeHeader(),
2032
2182
  copy,
2033
2183
  inTemplate,
2034
2184
  this.context.options,
2185
+ blocked.length > 0 ? { declarations: this.declarationsOf(blocked), inline } : undefined,
2186
+ measured,
2035
2187
  );
2188
+ const body = measured.code.slice(measured.code.lastIndexOf(COPY_WRAPPER));
2189
+ for (const inner of blocked) {
2190
+ if (hasTag(body, inner.binding.name)) {
2191
+ kept.add(inner);
2192
+ }
2193
+ }
2194
+ }
2195
+ // A blocked component that inlines into every copy goes away with this
2196
+ // one, when nothing else uses it.
2197
+ if (share > 0) {
2198
+ for (const inner of blocked) {
2199
+ if (!kept.has(inner) && inner.declaration && this.onlyUsedWithin(inner, component)) {
2200
+ calls += share * estimator.node(inner.declaration);
2201
+ }
2202
+ }
2036
2203
  }
2037
2204
  return calls - inlined;
2038
2205
  }
2039
2206
 
2207
+ /**
2208
+ * The components whose calls in a component's body cannot be inlined
2209
+ * there, but may be in a copy, once the call site resolves the props
2210
+ * they are given. Those they call in turn count too.
2211
+ */
2212
+ private blockedWithin(component: Component): Component[] {
2213
+ const found: Component[] = [];
2214
+ const pending = [component];
2215
+ for (let outer = pending.pop(); outer; outer = pending.pop()) {
2216
+ for (const inner of this.blocked.get(outer) ?? []) {
2217
+ if (inner !== component && !found.includes(inner)) {
2218
+ found.push(inner);
2219
+ pending.push(inner);
2220
+ }
2221
+ }
2222
+ }
2223
+ return found;
2224
+ }
2225
+
2226
+ /** The declarations of components, for a copy measured on its own. */
2227
+ private declarationsOf(components: readonly Component[]): string {
2228
+ const texts: string[] = [];
2229
+ for (const component of components) {
2230
+ const statement = this.topLevelStatement(component.binding.declaration);
2231
+ if (statement) {
2232
+ texts.push(textOf(this.context, statement));
2233
+ }
2234
+ }
2235
+ return texts.join('\n');
2236
+ }
2237
+
2238
+ /** Whether every call of `inner` is in `outer`, and nothing else uses it. */
2239
+ private onlyUsedWithin(inner: Component, outer: Component): boolean {
2240
+ return (
2241
+ this.otherUses?.get(inner) === 0 &&
2242
+ this.sites.every((site) => site.component !== inner || isWithin(site.element, outer.fn))
2243
+ );
2244
+ }
2245
+
2040
2246
  /**
2041
2247
  * Whether an element sits directly in an intrinsic element, whose
2042
2248
  * template its copy joins. A provider this pass makes transparent is
@@ -2066,6 +2272,37 @@ class Inliner {
2066
2272
 
2067
2273
  private header: string | undefined;
2068
2274
 
2275
+ /** The components of the module this pass can inline. */
2276
+ private readonly components: Component[] = [];
2277
+
2278
+ /** The call sites of those components. */
2279
+ private sites: readonly CallSite[] = [];
2280
+
2281
+ /** How many times each component is used other than as a call, while estimating. */
2282
+ private otherUses: ReadonlyMap<Component, number> | undefined;
2283
+
2284
+ /**
2285
+ * The components called in each component's body where the call cannot
2286
+ * be inlined as it is, while estimating.
2287
+ */
2288
+ private blocked = new Map<Component, Component[]>();
2289
+
2290
+ /** The top-level statement a node is part of, without an `export`. */
2291
+ private topLevelStatement(node: Node): Node | undefined {
2292
+ let current = node;
2293
+ for (let parent = this.context.parents.get(current); parent;) {
2294
+ if (parent.type === 'Program') {
2295
+ return current.type === 'ExportNamedDeclaration' ||
2296
+ current.type === 'ExportDefaultDeclaration'
2297
+ ? (current.declaration ?? undefined)
2298
+ : current;
2299
+ }
2300
+ current = parent;
2301
+ parent = this.context.parents.get(current);
2302
+ }
2303
+ return undefined;
2304
+ }
2305
+
2069
2306
  /**
2070
2307
  * What a copy measured on its own needs to know: the module's imports,
2071
2308
  * and the names that alias Solid's exports.
@@ -2088,8 +2325,95 @@ class Inliner {
2088
2325
  return this.header;
2089
2326
  }
2090
2327
 
2328
+ /**
2329
+ * The component a top-level alias like `const Button = ButtonRoot` names,
2330
+ * or `undefined` when the binding is not one.
2331
+ */
2332
+ private aliasTarget(binding: Binding): Binding | undefined {
2333
+ const { declaration } = binding;
2334
+ if (
2335
+ !isCapitalized(binding.name) ||
2336
+ !isConstantDeclaration(binding, this.context.options) ||
2337
+ declaration.type !== 'VariableDeclarator' ||
2338
+ declaration.id !== binding.identifier ||
2339
+ !declaration.init
2340
+ ) {
2341
+ return undefined;
2342
+ }
2343
+ const init = unwrap(declaration.init);
2344
+ if (init.type !== 'Identifier') {
2345
+ return undefined;
2346
+ }
2347
+ const target = this.context.scopes.references.get(init);
2348
+ return target &&
2349
+ target !== binding &&
2350
+ target.scope.parent === undefined &&
2351
+ !target.mutated &&
2352
+ isCapitalized(target.name)
2353
+ ? target
2354
+ : undefined;
2355
+ }
2356
+
2357
+ /**
2358
+ * The statement of an alias nothing uses that `reference` is the value
2359
+ * of, like `const Separator = SeparatorRoot` once its tags are renamed.
2360
+ * It does not keep the component, and goes away with it.
2361
+ */
2362
+ private unusedAlias(reference: Node): Node | undefined {
2363
+ const declarator = this.context.parents.get(reference);
2364
+ if (declarator?.type !== 'VariableDeclarator' || declarator.id.type !== 'Identifier') {
2365
+ return undefined;
2366
+ }
2367
+ const alias = this.context.scopes.root.bindings.get(declarator.id.name);
2368
+ const statement = this.context.parents.get(declarator);
2369
+ return alias?.declaration === declarator &&
2370
+ this.aliasTarget(alias) !== undefined &&
2371
+ alias.references.length === 0 &&
2372
+ statement?.type === 'VariableDeclaration' &&
2373
+ statement.declarations.length === 1 &&
2374
+ this.context.parents.get(statement)?.type === 'Program'
2375
+ ? statement
2376
+ : undefined;
2377
+ }
2378
+
2379
+ /**
2380
+ * Renames each tag of an alias to the component it names, where that name
2381
+ * means the same. Libraries often export a component under a second name,
2382
+ * like `const Separator = SeparatorRoot`. The next pass inlines the calls.
2383
+ */
2384
+ private renameAliasTags(): boolean {
2385
+ let renamed = false;
2386
+ for (const binding of this.context.scopes.root.bindings.values()) {
2387
+ const target = this.aliasTarget(binding);
2388
+ if (!target) {
2389
+ continue;
2390
+ }
2391
+ for (const reference of binding.references) {
2392
+ const parent = this.context.parents.get(reference);
2393
+ if (
2394
+ (parent?.type !== 'JSXOpeningElement' && parent?.type !== 'JSXClosingElement') ||
2395
+ parent.name !== reference
2396
+ ) {
2397
+ continue;
2398
+ }
2399
+ const scope = scopeAt(this.context.scopes, this.context.parents, reference);
2400
+ if (lookup(scope, target.name) !== target) {
2401
+ continue;
2402
+ }
2403
+ this.context.s.overwrite(reference.start, reference.end, target.name);
2404
+ renamed = true;
2405
+ }
2406
+ }
2407
+ return renamed;
2408
+ }
2409
+
2091
2410
  run(): void {
2092
- const components: Component[] = [];
2411
+ // The calls through an alias inline in the next pass, from the renamed tags.
2412
+ if (this.renameAliasTags()) {
2413
+ this.changed = true;
2414
+ return;
2415
+ }
2416
+ const { components } = this;
2093
2417
  const rejected = new Map<Binding, string>();
2094
2418
  for (const binding of this.context.scopes.root.bindings.values()) {
2095
2419
  this.reason = 'not-a-function';
@@ -2109,6 +2433,8 @@ class Inliner {
2109
2433
 
2110
2434
  const sites: CallSite[] = [];
2111
2435
  const otherUses = new Map<Component, number>();
2436
+ // The aliases nothing uses, which are removed with their component.
2437
+ const aliases = new Map<Component, Node[]>();
2112
2438
  for (const component of components) {
2113
2439
  let uses = 0;
2114
2440
  for (const reference of component.binding.references) {
@@ -2117,8 +2443,11 @@ class Inliner {
2117
2443
  continue;
2118
2444
  }
2119
2445
  const element = parent ? this.context.parents.get(parent) : undefined;
2446
+ const alias = this.unusedAlias(reference);
2120
2447
  if (parent?.type === 'JSXOpeningElement' && element?.type === 'JSXElement') {
2121
2448
  sites.push({ component, element });
2449
+ } else if (alias) {
2450
+ aliases.set(component, [...(aliases.get(component) ?? []), alias]);
2122
2451
  } else {
2123
2452
  uses += 1;
2124
2453
  }
@@ -2181,6 +2510,9 @@ class Inliner {
2181
2510
  );
2182
2511
  if (component.declaration && otherUses.get(component) === 0 && !insideCopy) {
2183
2512
  this.context.s.remove(component.declaration.start, component.declaration.end);
2513
+ for (const alias of aliases.get(component) ?? []) {
2514
+ this.context.s.remove(alias.start, alias.end);
2515
+ }
2184
2516
  }
2185
2517
  }
2186
2518
  }