solid-optimizer 1.0.0-next.9 → 1.1.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
@@ -56,7 +56,6 @@ import type {
56
56
  VariableDeclaration,
57
57
  WhileStatement,
58
58
  } from 'oxc-parser';
59
- import MagicString from 'magic-string';
60
59
  import type { Parents } from './ast';
61
60
  import {
62
61
  forEachChild,
@@ -96,6 +95,8 @@ import {
96
95
  literalText,
97
96
  truthiness,
98
97
  } from './value';
98
+ import type { Content, Editor, Text } from './text';
99
+ import { getCode, join, joinText } from './text';
99
100
 
100
101
  /**
101
102
  * The control-flow components this pass resolves.
@@ -110,11 +111,11 @@ type Fold =
110
111
  /** JSX children, spliced in. */
111
112
  | { readonly kind: 'children'; readonly children: readonly JSXChild[] }
112
113
  /** An element or fragment, as source text. */
113
- | { readonly kind: 'jsx'; readonly text: string }
114
+ | { readonly kind: 'jsx'; readonly text: Content }
114
115
  /** An expression, such as a `fallback` prop's value. */
115
116
  | {
116
117
  readonly kind: 'expression';
117
- readonly text: string;
118
+ readonly text: Content;
118
119
  readonly primary: boolean;
119
120
  }
120
121
  | { readonly kind: 'empty' };
@@ -218,8 +219,8 @@ function containsHoistedDeclaration(statement: Node): boolean {
218
219
  }
219
220
 
220
221
  /** The source text of each node. */
221
- function getTexts(context: PassContext, nodes: readonly Node[]): string[] {
222
- const texts: string[] = [];
222
+ function getTexts(context: PassContext, nodes: readonly Node[]): Text[] {
223
+ const texts: Text[] = [];
223
224
  for (const node of nodes) {
224
225
  texts.push(getText(context, node));
225
226
  }
@@ -291,15 +292,15 @@ function isValueArgument(call: CallExpression): boolean {
291
292
  }
292
293
 
293
294
  type ConstantItem =
294
- | { readonly kind: 'primitive'; readonly text: string }
295
- | { readonly kind: 'object'; readonly keys: ReadonlyMap<string, string> };
295
+ | { readonly kind: 'primitive'; readonly text: Text }
296
+ | { readonly kind: 'object'; readonly keys: ReadonlyMap<string, Text> };
296
297
 
297
298
  /**
298
299
  * The text of an expression that always gives the same primitive: a literal
299
300
  * other than a regular expression, a template literal without expressions,
300
301
  * or a negated number.
301
302
  */
302
- function primitiveText(context: PassContext, node: Expression): string | undefined {
303
+ function primitiveText(context: PassContext, node: Expression): Text | undefined {
303
304
  let expression: Expression = node;
304
305
  while (expression.type === 'ParenthesizedExpression') {
305
306
  expression = expression.expression;
@@ -443,8 +444,8 @@ class Folder {
443
444
  );
444
445
  }
445
446
 
446
- private replace(node: Node, text: string): void {
447
- if (getText(this.context, node) === text) {
447
+ private replace(node: Node, text: Content): void {
448
+ if (getText(this.context, node).code === getCode(text)) {
448
449
  return;
449
450
  }
450
451
  this.context.s.overwrite(node.start, node.end, text);
@@ -558,15 +559,15 @@ class Folder {
558
559
  * Keeps `value`, evaluating `discarded` first when it has side effects.
559
560
  * `(discarded, value)` runs it in the same order and yields the same result.
560
561
  */
561
- private keepAfter(target: Node, discarded: Expression | undefined, value: Expression): string {
562
+ private keepAfter(target: Node, discarded: Expression | undefined, value: Expression): Text {
562
563
  const parts = discarded ? effectfulParts(discarded) : [];
563
564
  if (parts.length === 0) {
564
565
  const text = getText(this.context, value);
565
- return needsParensAt(target, value, this.context.parents) ? `(${text})` : text;
566
+ return needsParensAt(target, value, this.context.parents) ? joinText`(${text})` : text;
566
567
  }
567
568
  const texts = getTexts(this.context, parts);
568
569
  texts.push(getText(this.context, value));
569
- return `(${texts.join(', ')})`;
570
+ return joinText`(${join(texts, ', ')})`;
570
571
  }
571
572
 
572
573
  private foldLogical(node: LogicalExpression): void {
@@ -759,7 +760,7 @@ class Folder {
759
760
  }
760
761
  return {
761
762
  kind: 'expression',
762
- text: JSON.stringify(value.value),
763
+ text: this.context.s.written(JSON.stringify(value.value), value.start),
763
764
  primary: true,
764
765
  };
765
766
  case 'JSXElement':
@@ -788,7 +789,7 @@ class Folder {
788
789
  */
789
790
  private foldedJSX(node: JSXElement | JSXFragment): Fold {
790
791
  const text = getText(this.context, node);
791
- if (text.startsWith('<')) {
792
+ if (text.code.startsWith('<')) {
792
793
  return { kind: 'jsx', text };
793
794
  }
794
795
  return { kind: 'expression', text, primary: false };
@@ -878,7 +879,8 @@ class Folder {
878
879
  }
879
880
  // A fold inside the row in this pass would be lost, so it waits for the next pass.
880
881
  if (
881
- 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)
882
884
  ) {
883
885
  return undefined;
884
886
  }
@@ -896,9 +898,9 @@ class Folder {
896
898
  }
897
899
  const itemParam = params.at(0);
898
900
  const indexParam = params.at(1);
899
- const rows: string[] = [];
901
+ const rows: Text[] = [];
900
902
  for (const [index, item] of list.items.entries()) {
901
- const copy = new MagicString(this.context.code);
903
+ const copy = this.context.s.fresh();
902
904
  // With `keyed={false}` the item is an accessor and the index a number, and the other way around otherwise.
903
905
  if (
904
906
  (itemParam && !this.substituteItem(copy, itemParam, item, byIndex)) ||
@@ -908,7 +910,7 @@ class Folder {
908
910
  }
909
911
  rows.push(copy.slice(body.start, body.end));
910
912
  }
911
- const text = `<>${rows.join('')}</>`;
913
+ const text = joinText`<>${join(rows)}</>`;
912
914
  if (!this.unrollingPays(element, text, list.declaration)) {
913
915
  return undefined;
914
916
  }
@@ -996,7 +998,7 @@ class Folder {
996
998
  if (node.type !== 'ObjectExpression') {
997
999
  return undefined;
998
1000
  }
999
- const keys = new Map<string, string>();
1001
+ const keys = new Map<string, Text>();
1000
1002
  for (const property of node.properties) {
1001
1003
  if (
1002
1004
  property.type !== 'Property' ||
@@ -1021,7 +1023,7 @@ class Folder {
1021
1023
  * `false` when a read is not one the value can take the place of.
1022
1024
  */
1023
1025
  private substituteItem(
1024
- copy: MagicString,
1026
+ copy: Editor,
1025
1027
  param: Binding,
1026
1028
  item: ConstantItem,
1027
1029
  accessor: boolean,
@@ -1077,17 +1079,14 @@ class Folder {
1077
1079
  }
1078
1080
 
1079
1081
  /** A value's text in place of `node`, with parentheses unless it fills a JSX container. */
1080
- private valueAt(node: Node, text: string): string {
1081
- 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})`;
1082
1086
  }
1083
1087
 
1084
1088
  /** Writes an item's index over each read of the row's index parameter. */
1085
- private substituteIndex(
1086
- copy: MagicString,
1087
- param: Binding,
1088
- index: number,
1089
- accessor: boolean,
1090
- ): boolean {
1089
+ private substituteIndex(copy: Editor, param: Binding, index: number, accessor: boolean): boolean {
1091
1090
  for (const reference of param.references) {
1092
1091
  let read: Node = reference;
1093
1092
  if (accessor) {
@@ -1110,14 +1109,14 @@ class Folder {
1110
1109
  * Whether the copies are estimated to be no larger, once lowered, than
1111
1110
  * the loop and the list it no longer needs.
1112
1111
  */
1113
- private unrollingPays(element: JSXElement, text: string, declaration: Node | undefined): boolean {
1112
+ private unrollingPays(element: JSXElement, text: Text, declaration: Node | undefined): boolean {
1114
1113
  const inTemplate = this.joinsParentTemplate(element);
1115
1114
  const loop =
1116
1115
  new SizeEstimator(this.context.code).jsx(element, inTemplate) +
1117
1116
  (declaration
1118
1117
  ? compactLength(this.context.code.slice(declaration.start, declaration.end))
1119
1118
  : 0);
1120
- const code = `const __so_rows__ = ${text};`;
1119
+ const code = `const __so_rows__ = ${text.code};`;
1121
1120
  const program = parse(this.context.filename, code);
1122
1121
  const statement = program.body.at(0);
1123
1122
  const init =
@@ -1262,16 +1261,16 @@ class Folder {
1262
1261
  if (tag === undefined) {
1263
1262
  return undefined;
1264
1263
  }
1265
- const attributes: string[] = [];
1264
+ const attributes: Content[] = [tag];
1266
1265
  for (const attribute of element.openingElement.attributes) {
1267
1266
  if (attribute !== component) {
1268
1267
  attributes.push(getText(this.context, attribute));
1269
1268
  }
1270
1269
  }
1271
- const opening = [tag, ...attributes].join(' ');
1270
+ const opening = join(attributes, ' ');
1272
1271
  const text = element.closingElement
1273
- ? `<${opening}>${innerText(this.context.s, element)}</${tag}>`
1274
- : `<${opening} />`;
1272
+ ? joinText`<${opening}>${innerText(this.context.s, element)}</${tag}>`
1273
+ : joinText`<${opening} />`;
1275
1274
  return { kind: 'jsx', text };
1276
1275
  }
1277
1276
 
@@ -1286,14 +1285,14 @@ class Folder {
1286
1285
  this.replace(element, this.expressionText(resolved));
1287
1286
  }
1288
1287
 
1289
- private expressionText(resolved: Fold): string {
1288
+ private expressionText(resolved: Fold): Content {
1290
1289
  switch (resolved.kind) {
1291
1290
  case 'empty':
1292
1291
  return 'null';
1293
1292
  case 'jsx':
1294
1293
  return resolved.text;
1295
1294
  case 'expression':
1296
- return resolved.primary ? resolved.text : `(${resolved.text})`;
1295
+ return resolved.primary ? resolved.text : joinText`(${resolved.text})`;
1297
1296
  default: {
1298
1297
  const significant = getSignificant(resolved.children);
1299
1298
  const only = significant.at(0);
@@ -1311,7 +1310,7 @@ class Folder {
1311
1310
  if (!first || !last) {
1312
1311
  return 'null';
1313
1312
  }
1314
- return `<>${this.context.s.slice(first.start, last.end)}</>`;
1313
+ return joinText`<>${this.context.s.slice(first.start, last.end)}</>`;
1315
1314
  }
1316
1315
  }
1317
1316
  }
@@ -1353,7 +1352,7 @@ class Folder {
1353
1352
  pieces.push(replacedPiece(child, resolved.text));
1354
1353
  break;
1355
1354
  case 'expression':
1356
- pieces.push(replacedPiece(child, `{${resolved.text}}`));
1355
+ pieces.push(replacedPiece(child, joinText`{${resolved.text}}`));
1357
1356
  break;
1358
1357
  default:
1359
1358
  pieces.push(replacedPiece(child, ''));
@@ -1378,7 +1377,7 @@ class Folder {
1378
1377
  * constant or a binding nothing reassigns, so reading it again where the
1379
1378
  * parameter was gives the same value.
1380
1379
  */
1381
- private reducedCall(expression: Expression | JSXEmptyExpression): string | undefined {
1380
+ private reducedCall(expression: Expression | JSXEmptyExpression): Text | undefined {
1382
1381
  if (expression.type !== 'CallExpression' || expression.optional) {
1383
1382
  return undefined;
1384
1383
  }
@@ -1403,7 +1402,8 @@ class Folder {
1403
1402
  }
1404
1403
  // A fold inside the body in this pass would be lost, so it waits for the next pass.
1405
1404
  if (
1406
- 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)
1407
1407
  ) {
1408
1408
  return undefined;
1409
1409
  }
@@ -1411,7 +1411,7 @@ class Folder {
1411
1411
  if (!scope) {
1412
1412
  return undefined;
1413
1413
  }
1414
- const copy = new MagicString(this.context.code);
1414
+ const copy = this.context.s.fresh();
1415
1415
  for (const [index, param] of params.entries()) {
1416
1416
  const arg = args.at(index);
1417
1417
  if (param.type !== 'Identifier' || !arg || arg.type === 'SpreadElement') {
@@ -1434,14 +1434,18 @@ class Folder {
1434
1434
  const parent = this.context.parents.get(reference);
1435
1435
  const shorthand =
1436
1436
  parent?.type === 'Property' && parent.shorthand && parent.value === reference;
1437
- 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
+ );
1438
1442
  }
1439
1443
  }
1440
1444
  return copy.slice(body.start, body.end);
1441
1445
  }
1442
1446
 
1443
1447
  /** The text of an argument that reads the same wherever it is copied. */
1444
- private argumentText(arg: Expression): string | undefined {
1448
+ private argumentText(arg: Expression): Content | undefined {
1445
1449
  let node: Expression = arg;
1446
1450
  while (node.type === 'ParenthesizedExpression') {
1447
1451
  node = node.expression;
@@ -1453,7 +1457,7 @@ class Folder {
1453
1457
  return node.expressions.length === 0 ? getText(this.context, node) : undefined;
1454
1458
  case 'UnaryExpression':
1455
1459
  return node.operator === '-' && node.argument.type === 'Literal'
1456
- ? `(${getText(this.context, node)})`
1460
+ ? joinText`(${getText(this.context, node)})`
1457
1461
  : undefined;
1458
1462
  case 'Identifier': {
1459
1463
  const binding = this.context.scopes.references.get(node);
@@ -1598,27 +1602,27 @@ class Folder {
1598
1602
  return true;
1599
1603
  }
1600
1604
 
1601
- private replaceStatement(statement: Node, text: string): void {
1602
- if (text === '') {
1605
+ private replaceStatement(statement: Node, text: Content): void {
1606
+ if (getCode(text) === '') {
1603
1607
  this.context.s.remove(statement.start, statement.end);
1604
1608
  this.changed = true;
1605
1609
  return;
1606
1610
  }
1607
- this.replace(statement, continuesPreviousStatement(text) ? `;${text}` : text);
1611
+ this.replace(statement, continuesPreviousStatement(getCode(text)) ? joinText`;${text}` : text);
1608
1612
  }
1609
1613
 
1610
1614
  /**
1611
1615
  * A statement that keeps a discarded test's side effects, or `undefined`
1612
1616
  * when skipping the test changes nothing.
1613
1617
  */
1614
- private discardedTest(test: Expression): string | undefined {
1618
+ private discardedTest(test: Expression): Text | undefined {
1615
1619
  const parts = effectfulParts(test);
1616
1620
  const first = parts.at(0);
1617
1621
  if (first === undefined) {
1618
1622
  return undefined;
1619
1623
  }
1620
- const text = getTexts(this.context, parts).join(', ');
1621
- return startsLikeStatement(first) ? `(${text});` : `${text};`;
1624
+ const text = join(getTexts(this.context, parts), ', ');
1625
+ return startsLikeStatement(first) ? joinText`(${text});` : joinText`${text};`;
1622
1626
  }
1623
1627
 
1624
1628
  /**
@@ -1640,7 +1644,7 @@ class Folder {
1640
1644
  if (kept?.type === 'FunctionDeclaration') {
1641
1645
  return undefined;
1642
1646
  }
1643
- const parts: string[] = [];
1647
+ const parts: Text[] = [];
1644
1648
  const effect = this.discardedTest(statement.test);
1645
1649
  if (effect !== undefined) {
1646
1650
  parts.push(effect);
@@ -1648,7 +1652,7 @@ class Folder {
1648
1652
  if (kept) {
1649
1653
  parts.push(getText(this.context, kept));
1650
1654
  }
1651
- this.replaceStatement(statement, parts.join(' '));
1655
+ this.replaceStatement(statement, join(parts, ' '));
1652
1656
  return kept;
1653
1657
  }
1654
1658