solid-optimizer 1.0.0-next.8 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/fold.ts CHANGED
@@ -18,6 +18,10 @@
18
18
  * - Statements a constant condition makes unreachable: `if`/`else` branches,
19
19
  * `while (false)` loops, and anything after a `return`, `throw`, `break`,
20
20
  * or `continue`.
21
+ * - A `const`, or a `let` nothing writes to, declared inside a function,
22
+ * that nothing references and whose initializer has no side effects. A
23
+ * component left with such a declaration has a statement, which stops it
24
+ * from inlining where a statement has no place to go.
21
25
  * - A call of an arrow function whose body is JSX, with constant arguments,
22
26
  * as an element's child. The call becomes the JSX with the arguments in
23
27
  * place of the parameters, so it joins the template around it.
@@ -49,9 +53,9 @@ import type {
49
53
  LogicalExpression,
50
54
  Node,
51
55
  Statement,
56
+ VariableDeclaration,
52
57
  WhileStatement,
53
58
  } from 'oxc-parser';
54
- import MagicString from 'magic-string';
55
59
  import type { Parents } from './ast';
56
60
  import {
57
61
  forEachChild,
@@ -91,6 +95,8 @@ import {
91
95
  literalText,
92
96
  truthiness,
93
97
  } from './value';
98
+ import type { Content, Editor, Text } from './text';
99
+ import { getCode, join, joinText } from './text';
94
100
 
95
101
  /**
96
102
  * The control-flow components this pass resolves.
@@ -105,11 +111,11 @@ type Fold =
105
111
  /** JSX children, spliced in. */
106
112
  | { readonly kind: 'children'; readonly children: readonly JSXChild[] }
107
113
  /** An element or fragment, as source text. */
108
- | { readonly kind: 'jsx'; readonly text: string }
114
+ | { readonly kind: 'jsx'; readonly text: Content }
109
115
  /** An expression, such as a `fallback` prop's value. */
110
116
  | {
111
117
  readonly kind: 'expression';
112
- readonly text: string;
118
+ readonly text: Content;
113
119
  readonly primary: boolean;
114
120
  }
115
121
  | { readonly kind: 'empty' };
@@ -213,8 +219,8 @@ function containsHoistedDeclaration(statement: Node): boolean {
213
219
  }
214
220
 
215
221
  /** The source text of each node. */
216
- function getTexts(context: PassContext, nodes: readonly Node[]): string[] {
217
- const texts: string[] = [];
222
+ function getTexts(context: PassContext, nodes: readonly Node[]): Text[] {
223
+ const texts: Text[] = [];
218
224
  for (const node of nodes) {
219
225
  texts.push(getText(context, node));
220
226
  }
@@ -286,15 +292,15 @@ function isValueArgument(call: CallExpression): boolean {
286
292
  }
287
293
 
288
294
  type ConstantItem =
289
- | { readonly kind: 'primitive'; readonly text: string }
290
- | { readonly kind: 'object'; readonly keys: ReadonlyMap<string, string> };
295
+ | { readonly kind: 'primitive'; readonly text: Text }
296
+ | { readonly kind: 'object'; readonly keys: ReadonlyMap<string, Text> };
291
297
 
292
298
  /**
293
299
  * The text of an expression that always gives the same primitive: a literal
294
300
  * other than a regular expression, a template literal without expressions,
295
301
  * or a negated number.
296
302
  */
297
- function primitiveText(context: PassContext, node: Expression): string | undefined {
303
+ function primitiveText(context: PassContext, node: Expression): Text | undefined {
298
304
  let expression: Expression = node;
299
305
  while (expression.type === 'ParenthesizedExpression') {
300
306
  expression = expression.expression;
@@ -354,6 +360,9 @@ class Folder {
354
360
 
355
361
  private readonly lookup: ConstantLookup;
356
362
 
363
+ /** Declarations removed before the walk, which it does not enter. */
364
+ private readonly removed = new Set<Node>();
365
+
357
366
  constructor(private readonly context: PassContext) {
358
367
  this.lookup = new ConstantTable(context.scopes, context.options).lookup;
359
368
  }
@@ -363,6 +372,9 @@ class Folder {
363
372
  // ---------------------------------------------------------------------------
364
373
 
365
374
  walk(node: Node): void {
375
+ if (this.removed.has(node)) {
376
+ return;
377
+ }
366
378
  forEachChild(node, (child) => {
367
379
  this.walk(child);
368
380
  });
@@ -432,8 +444,8 @@ class Folder {
432
444
  );
433
445
  }
434
446
 
435
- private replace(node: Node, text: string): void {
436
- if (getText(this.context, node) === text) {
447
+ private replace(node: Node, text: Content): void {
448
+ if (getText(this.context, node).code === getCode(text)) {
437
449
  return;
438
450
  }
439
451
  this.context.s.overwrite(node.start, node.end, text);
@@ -547,15 +559,15 @@ class Folder {
547
559
  * Keeps `value`, evaluating `discarded` first when it has side effects.
548
560
  * `(discarded, value)` runs it in the same order and yields the same result.
549
561
  */
550
- private keepAfter(target: Node, discarded: Expression | undefined, value: Expression): string {
562
+ private keepAfter(target: Node, discarded: Expression | undefined, value: Expression): Text {
551
563
  const parts = discarded ? effectfulParts(discarded) : [];
552
564
  if (parts.length === 0) {
553
565
  const text = getText(this.context, value);
554
- return needsParensAt(target, value, this.context.parents) ? `(${text})` : text;
566
+ return needsParensAt(target, value, this.context.parents) ? joinText`(${text})` : text;
555
567
  }
556
568
  const texts = getTexts(this.context, parts);
557
569
  texts.push(getText(this.context, value));
558
- return `(${texts.join(', ')})`;
570
+ return joinText`(${join(texts, ', ')})`;
559
571
  }
560
572
 
561
573
  private foldLogical(node: LogicalExpression): void {
@@ -748,7 +760,7 @@ class Folder {
748
760
  }
749
761
  return {
750
762
  kind: 'expression',
751
- text: JSON.stringify(value.value),
763
+ text: this.context.s.written(JSON.stringify(value.value), value.start),
752
764
  primary: true,
753
765
  };
754
766
  case 'JSXElement':
@@ -777,7 +789,7 @@ class Folder {
777
789
  */
778
790
  private foldedJSX(node: JSXElement | JSXFragment): Fold {
779
791
  const text = getText(this.context, node);
780
- if (text.startsWith('<')) {
792
+ if (text.code.startsWith('<')) {
781
793
  return { kind: 'jsx', text };
782
794
  }
783
795
  return { kind: 'expression', text, primary: false };
@@ -867,7 +879,8 @@ class Folder {
867
879
  }
868
880
  // A fold inside the row in this pass would be lost, so it waits for the next pass.
869
881
  if (
870
- this.context.s.slice(body.start, body.end) !== this.context.code.slice(body.start, body.end)
882
+ this.context.s.slice(body.start, body.end).code !==
883
+ this.context.code.slice(body.start, body.end)
871
884
  ) {
872
885
  return undefined;
873
886
  }
@@ -885,9 +898,9 @@ class Folder {
885
898
  }
886
899
  const itemParam = params.at(0);
887
900
  const indexParam = params.at(1);
888
- const rows: string[] = [];
901
+ const rows: Text[] = [];
889
902
  for (const [index, item] of list.items.entries()) {
890
- const copy = new MagicString(this.context.code);
903
+ const copy = this.context.s.fresh();
891
904
  // With `keyed={false}` the item is an accessor and the index a number, and the other way around otherwise.
892
905
  if (
893
906
  (itemParam && !this.substituteItem(copy, itemParam, item, byIndex)) ||
@@ -897,7 +910,7 @@ class Folder {
897
910
  }
898
911
  rows.push(copy.slice(body.start, body.end));
899
912
  }
900
- const text = `<>${rows.join('')}</>`;
913
+ const text = joinText`<>${join(rows)}</>`;
901
914
  if (!this.unrollingPays(element, text, list.declaration)) {
902
915
  return undefined;
903
916
  }
@@ -985,7 +998,7 @@ class Folder {
985
998
  if (node.type !== 'ObjectExpression') {
986
999
  return undefined;
987
1000
  }
988
- const keys = new Map<string, string>();
1001
+ const keys = new Map<string, Text>();
989
1002
  for (const property of node.properties) {
990
1003
  if (
991
1004
  property.type !== 'Property' ||
@@ -1010,7 +1023,7 @@ class Folder {
1010
1023
  * `false` when a read is not one the value can take the place of.
1011
1024
  */
1012
1025
  private substituteItem(
1013
- copy: MagicString,
1026
+ copy: Editor,
1014
1027
  param: Binding,
1015
1028
  item: ConstantItem,
1016
1029
  accessor: boolean,
@@ -1066,17 +1079,14 @@ class Folder {
1066
1079
  }
1067
1080
 
1068
1081
  /** A value's text in place of `node`, with parentheses unless it fills a JSX container. */
1069
- private valueAt(node: Node, text: string): string {
1070
- return this.context.parents.get(node)?.type === 'JSXExpressionContainer' ? text : `(${text})`;
1082
+ private valueAt(node: Node, text: Content): Content {
1083
+ return this.context.parents.get(node)?.type === 'JSXExpressionContainer'
1084
+ ? text
1085
+ : joinText`(${text})`;
1071
1086
  }
1072
1087
 
1073
1088
  /** Writes an item's index over each read of the row's index parameter. */
1074
- private substituteIndex(
1075
- copy: MagicString,
1076
- param: Binding,
1077
- index: number,
1078
- accessor: boolean,
1079
- ): boolean {
1089
+ private substituteIndex(copy: Editor, param: Binding, index: number, accessor: boolean): boolean {
1080
1090
  for (const reference of param.references) {
1081
1091
  let read: Node = reference;
1082
1092
  if (accessor) {
@@ -1099,14 +1109,14 @@ class Folder {
1099
1109
  * Whether the copies are estimated to be no larger, once lowered, than
1100
1110
  * the loop and the list it no longer needs.
1101
1111
  */
1102
- private unrollingPays(element: JSXElement, text: string, declaration: Node | undefined): boolean {
1112
+ private unrollingPays(element: JSXElement, text: Text, declaration: Node | undefined): boolean {
1103
1113
  const inTemplate = this.joinsParentTemplate(element);
1104
1114
  const loop =
1105
1115
  new SizeEstimator(this.context.code).jsx(element, inTemplate) +
1106
1116
  (declaration
1107
1117
  ? compactLength(this.context.code.slice(declaration.start, declaration.end))
1108
1118
  : 0);
1109
- const code = `const __so_rows__ = ${text};`;
1119
+ const code = `const __so_rows__ = ${text.code};`;
1110
1120
  const program = parse(this.context.filename, code);
1111
1121
  const statement = program.body.at(0);
1112
1122
  const init =
@@ -1251,16 +1261,16 @@ class Folder {
1251
1261
  if (tag === undefined) {
1252
1262
  return undefined;
1253
1263
  }
1254
- const attributes: string[] = [];
1264
+ const attributes: Content[] = [tag];
1255
1265
  for (const attribute of element.openingElement.attributes) {
1256
1266
  if (attribute !== component) {
1257
1267
  attributes.push(getText(this.context, attribute));
1258
1268
  }
1259
1269
  }
1260
- const opening = [tag, ...attributes].join(' ');
1270
+ const opening = join(attributes, ' ');
1261
1271
  const text = element.closingElement
1262
- ? `<${opening}>${innerText(this.context.s, element)}</${tag}>`
1263
- : `<${opening} />`;
1272
+ ? joinText`<${opening}>${innerText(this.context.s, element)}</${tag}>`
1273
+ : joinText`<${opening} />`;
1264
1274
  return { kind: 'jsx', text };
1265
1275
  }
1266
1276
 
@@ -1275,14 +1285,14 @@ class Folder {
1275
1285
  this.replace(element, this.expressionText(resolved));
1276
1286
  }
1277
1287
 
1278
- private expressionText(resolved: Fold): string {
1288
+ private expressionText(resolved: Fold): Content {
1279
1289
  switch (resolved.kind) {
1280
1290
  case 'empty':
1281
1291
  return 'null';
1282
1292
  case 'jsx':
1283
1293
  return resolved.text;
1284
1294
  case 'expression':
1285
- return resolved.primary ? resolved.text : `(${resolved.text})`;
1295
+ return resolved.primary ? resolved.text : joinText`(${resolved.text})`;
1286
1296
  default: {
1287
1297
  const significant = getSignificant(resolved.children);
1288
1298
  const only = significant.at(0);
@@ -1300,7 +1310,7 @@ class Folder {
1300
1310
  if (!first || !last) {
1301
1311
  return 'null';
1302
1312
  }
1303
- return `<>${this.context.s.slice(first.start, last.end)}</>`;
1313
+ return joinText`<>${this.context.s.slice(first.start, last.end)}</>`;
1304
1314
  }
1305
1315
  }
1306
1316
  }
@@ -1342,7 +1352,7 @@ class Folder {
1342
1352
  pieces.push(replacedPiece(child, resolved.text));
1343
1353
  break;
1344
1354
  case 'expression':
1345
- pieces.push(replacedPiece(child, `{${resolved.text}}`));
1355
+ pieces.push(replacedPiece(child, joinText`{${resolved.text}}`));
1346
1356
  break;
1347
1357
  default:
1348
1358
  pieces.push(replacedPiece(child, ''));
@@ -1367,7 +1377,7 @@ class Folder {
1367
1377
  * constant or a binding nothing reassigns, so reading it again where the
1368
1378
  * parameter was gives the same value.
1369
1379
  */
1370
- private reducedCall(expression: Expression | JSXEmptyExpression): string | undefined {
1380
+ private reducedCall(expression: Expression | JSXEmptyExpression): Text | undefined {
1371
1381
  if (expression.type !== 'CallExpression' || expression.optional) {
1372
1382
  return undefined;
1373
1383
  }
@@ -1392,7 +1402,8 @@ class Folder {
1392
1402
  }
1393
1403
  // A fold inside the body in this pass would be lost, so it waits for the next pass.
1394
1404
  if (
1395
- this.context.s.slice(body.start, body.end) !== this.context.code.slice(body.start, body.end)
1405
+ this.context.s.slice(body.start, body.end).code !==
1406
+ this.context.code.slice(body.start, body.end)
1396
1407
  ) {
1397
1408
  return undefined;
1398
1409
  }
@@ -1400,7 +1411,7 @@ class Folder {
1400
1411
  if (!scope) {
1401
1412
  return undefined;
1402
1413
  }
1403
- const copy = new MagicString(this.context.code);
1414
+ const copy = this.context.s.fresh();
1404
1415
  for (const [index, param] of params.entries()) {
1405
1416
  const arg = args.at(index);
1406
1417
  if (param.type !== 'Identifier' || !arg || arg.type === 'SpreadElement') {
@@ -1423,14 +1434,18 @@ class Folder {
1423
1434
  const parent = this.context.parents.get(reference);
1424
1435
  const shorthand =
1425
1436
  parent?.type === 'Property' && parent.shorthand && parent.value === reference;
1426
- copy.overwrite(reference.start, reference.end, shorthand ? `${param.name}: ${text}` : text);
1437
+ copy.overwrite(
1438
+ reference.start,
1439
+ reference.end,
1440
+ shorthand ? joinText`${param.name}: ${text}` : text,
1441
+ );
1427
1442
  }
1428
1443
  }
1429
1444
  return copy.slice(body.start, body.end);
1430
1445
  }
1431
1446
 
1432
1447
  /** The text of an argument that reads the same wherever it is copied. */
1433
- private argumentText(arg: Expression): string | undefined {
1448
+ private argumentText(arg: Expression): Content | undefined {
1434
1449
  let node: Expression = arg;
1435
1450
  while (node.type === 'ParenthesizedExpression') {
1436
1451
  node = node.expression;
@@ -1442,7 +1457,7 @@ class Folder {
1442
1457
  return node.expressions.length === 0 ? getText(this.context, node) : undefined;
1443
1458
  case 'UnaryExpression':
1444
1459
  return node.operator === '-' && node.argument.type === 'Literal'
1445
- ? `(${getText(this.context, node)})`
1460
+ ? joinText`(${getText(this.context, node)})`
1446
1461
  : undefined;
1447
1462
  case 'Identifier': {
1448
1463
  const binding = this.context.scopes.references.get(node);
@@ -1495,27 +1510,119 @@ class Folder {
1495
1510
  }
1496
1511
  }
1497
1512
 
1498
- private replaceStatement(statement: Node, text: string): void {
1499
- if (text === '') {
1513
+ /**
1514
+ * Removes each declaration inside a function that nothing references. The
1515
+ * references are those of the code this pass parsed, so a binding whose last
1516
+ * read this pass folds is removed in the next round.
1517
+ */
1518
+ removeUnusedDeclarations(): void {
1519
+ for (const scope of this.context.scopes.scopes.values()) {
1520
+ if (scope === this.context.scopes.root) {
1521
+ continue;
1522
+ }
1523
+ for (const binding of scope.bindings.values()) {
1524
+ const declaration = this.unusedDeclaration(binding);
1525
+ if (declaration && !this.removed.has(declaration)) {
1526
+ this.removed.add(declaration);
1527
+ this.context.s.remove(declaration.start, declaration.end);
1528
+ this.changed = true;
1529
+ }
1530
+ }
1531
+ }
1532
+ }
1533
+
1534
+ /**
1535
+ * The declaration statement of `binding` when every binding it declares is
1536
+ * unused and every initializer can be skipped.
1537
+ */
1538
+ private unusedDeclaration(binding: Binding): VariableDeclaration | undefined {
1539
+ if (binding.declaration.type !== 'VariableDeclarator') {
1540
+ return undefined;
1541
+ }
1542
+ const statement = this.context.parents.get(binding.declaration);
1543
+ if (
1544
+ statement?.type !== 'VariableDeclaration' ||
1545
+ (statement.kind !== 'const' && statement.kind !== 'let') ||
1546
+ statement.declare
1547
+ ) {
1548
+ return undefined;
1549
+ }
1550
+
1551
+ // Only a statement in a list can go. A loop head or an export needs it.
1552
+ const container = this.context.parents.get(statement)?.type;
1553
+ if (
1554
+ container !== 'BlockStatement' &&
1555
+ container !== 'StaticBlock' &&
1556
+ container !== 'SwitchCase'
1557
+ ) {
1558
+ return undefined;
1559
+ }
1560
+
1561
+ // Every declarator has to go, or the statement stays whole.
1562
+ for (const declarator of statement.declarations) {
1563
+ if (declarator.id.type !== 'Identifier') {
1564
+ return undefined;
1565
+ }
1566
+ const declared = binding.scope.bindings.get(declarator.id.name);
1567
+ if (!declared || declared.mutated || declared.references.length > 0) {
1568
+ return undefined;
1569
+ }
1570
+ if (declarator.init && !this.isSkippableInit(declarator.init)) {
1571
+ return undefined;
1572
+ }
1573
+ }
1574
+ return statement;
1575
+ }
1576
+
1577
+ /**
1578
+ * Whether an unused initializer can be dropped: an expression with no side
1579
+ * effects, or a Solid call that only creates a value from such arguments.
1580
+ */
1581
+ private isSkippableInit(init: Expression): boolean {
1582
+ if (isSideEffectFree(init)) {
1583
+ return true;
1584
+ }
1585
+ const call = unwrap(init);
1586
+ if (call.type !== 'CallExpression' || call.callee.type !== 'Identifier') {
1587
+ return false;
1588
+ }
1589
+ const callee = this.context.scopes.references.get(call.callee);
1590
+ const identity = callee ? solidExport(callee, this.context.options) : undefined;
1591
+ if (
1592
+ identity === undefined ||
1593
+ (!PURE_CALLS.has(identity) && !(PURE_VALUE_CALLS.has(identity) && isValueArgument(call)))
1594
+ ) {
1595
+ return false;
1596
+ }
1597
+ for (const argument of call.arguments) {
1598
+ if (argument.type === 'SpreadElement' || !isSideEffectFree(argument)) {
1599
+ return false;
1600
+ }
1601
+ }
1602
+ return true;
1603
+ }
1604
+
1605
+ private replaceStatement(statement: Node, text: Content): void {
1606
+ if (getCode(text) === '') {
1500
1607
  this.context.s.remove(statement.start, statement.end);
1501
1608
  this.changed = true;
1502
1609
  return;
1503
1610
  }
1504
- this.replace(statement, continuesPreviousStatement(text) ? `;${text}` : text);
1611
+ this.replace(statement, continuesPreviousStatement(getCode(text)) ? joinText`;${text}` : text);
1505
1612
  }
1506
1613
 
1507
1614
  /**
1508
1615
  * A statement that keeps a discarded test's side effects, or `undefined`
1509
1616
  * when skipping the test changes nothing.
1510
1617
  */
1511
- private discardedTest(test: Expression): string | undefined {
1618
+ private discardedTest(test: Expression): Text | undefined {
1512
1619
  const parts = effectfulParts(test);
1513
1620
  const first = parts.at(0);
1514
1621
  if (first === undefined) {
1515
1622
  return undefined;
1516
1623
  }
1517
- const text = getTexts(this.context, parts).join(', ');
1518
- return startsLikeStatement(first) ? `(${text});` : `${text};`;
1624
+ const text = join(getTexts(this.context, parts), ', ');
1625
+ return startsLikeStatement(first) ? joinText`(${text});` : joinText`${text};`;
1519
1626
  }
1520
1627
 
1521
1628
  /**
@@ -1537,7 +1644,7 @@ class Folder {
1537
1644
  if (kept?.type === 'FunctionDeclaration') {
1538
1645
  return undefined;
1539
1646
  }
1540
- const parts: string[] = [];
1647
+ const parts: Text[] = [];
1541
1648
  const effect = this.discardedTest(statement.test);
1542
1649
  if (effect !== undefined) {
1543
1650
  parts.push(effect);
@@ -1545,7 +1652,7 @@ class Folder {
1545
1652
  if (kept) {
1546
1653
  parts.push(getText(this.context, kept));
1547
1654
  }
1548
- this.replaceStatement(statement, parts.join(' '));
1655
+ this.replaceStatement(statement, join(parts, ' '));
1549
1656
  return kept;
1550
1657
  }
1551
1658
 
@@ -1566,6 +1673,7 @@ class Folder {
1566
1673
  */
1567
1674
  export function fold(context: PassContext): boolean {
1568
1675
  const folder = new Folder(context);
1676
+ folder.removeUnusedDeclarations();
1569
1677
  folder.walk(context.program);
1570
1678
  return folder.changed;
1571
1679
  }