solid-optimizer 0.4.0 → 1.0.0-next.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
@@ -7,9 +7,8 @@
7
7
  * branch, and the branch joins the surrounding template instead of paying for
8
8
  * a component call, a memo, and an insert.
9
9
  *
10
- * It follows the `optimize` option of Solid 2.0's `@solidjs/compiler`
11
- * (https://github.com/solidjs/solid/pull/3231), applied to Solid 1's
12
- * control-flow components.
10
+ * This is a port of the `optimize` option of `@solidjs/compiler`
11
+ * (https://github.com/solidjs/solid/pull/3231).
13
12
  *
14
13
  * # What folds
15
14
  *
@@ -19,13 +18,19 @@
19
18
  * - Statements a constant condition makes unreachable: `if`/`else` branches,
20
19
  * `while (false)` loops, and anything after a `return`, `throw`, `break`,
21
20
  * or `continue`.
22
- * - `<Show when>`, `<For each>`, `<Index each>`, `<Switch>`/`<Match when>`,
23
- * and `<Dynamic component>` with a static intrinsic tag name.
21
+ * - A call of an arrow function whose body is JSX, with constant arguments,
22
+ * as an element's child. The call becomes the JSX with the arguments in
23
+ * place of the parameters, so it joins the template around it.
24
+ * - `<For>` over a constant list, which becomes one copy of its row per
25
+ * item when the copies are no larger than the loop.
26
+ * - `<Show when>`, `<For each>`, `<Repeat count>`, `<Switch>`/`<Match when>`,
27
+ * and `<Dynamic component>` with a static intrinsic tag name or a
28
+ * component declared at the top level that nothing reassigns.
24
29
  *
25
30
  * # What does not fold
26
31
  *
27
- * `<Portal>`, `<Suspense>`, `<SuspenseList>`, and `<ErrorBoundary>` exist for
28
- * a runtime condition no static analysis can decide. A control-flow component with a
32
+ * `<Portal>`, `<Loading>`, `<Errored>`, and `<Reveal>` exist for a runtime
33
+ * condition no static analysis can decide. A control-flow component with a
29
34
  * spread attribute is left alone, since the spread can supply or override the
30
35
  * prop the fold reads. Function children also stop a fold, since the runtime
31
36
  * decides from their arity whether to call them.
@@ -35,15 +40,18 @@ import type {
35
40
  ConditionalExpression,
36
41
  Directive,
37
42
  Expression,
43
+ IdentifierReference,
38
44
  IfStatement,
39
45
  JSXChild,
40
46
  JSXElement,
47
+ JSXEmptyExpression,
41
48
  JSXFragment,
42
49
  LogicalExpression,
43
50
  Node,
44
51
  Statement,
45
52
  WhileStatement,
46
53
  } from 'oxc-parser';
54
+ import MagicString from 'magic-string';
47
55
  import type { Parents } from './ast';
48
56
  import {
49
57
  forEachChild,
@@ -52,11 +60,12 @@ import {
52
60
  isJSXChild,
53
61
  isPrimary,
54
62
  needsParensAt,
63
+ parse,
55
64
  startsLikeStatement,
56
65
  } from './ast';
57
66
  import type { PassContext } from './context';
58
67
  import { ConstantTable } from './constants';
59
- import { solidExport, textOf } from './context';
68
+ import { isConstantDeclaration, solidExport, textOf } from './context';
60
69
  import type { Piece } from './jsx';
61
70
  import {
62
71
  findAttribute,
@@ -68,6 +77,9 @@ import {
68
77
  splicePiece,
69
78
  writePieces,
70
79
  } from './jsx';
80
+ import type { Binding } from './scope';
81
+ import { lookup, scopeAt } from './scope';
82
+ import { SizeEstimator, compactLength } from './size';
71
83
  import type { ConstantLookup } from './value';
72
84
  import {
73
85
  arrayLiteralLength,
@@ -83,7 +95,7 @@ import {
83
95
  * The control-flow components this pass resolves.
84
96
  * `Match` is absent: it only has meaning inside a `<Switch>`, which folds it.
85
97
  */
86
- const FOLDABLE_FLOW = new Set(['Show', 'For', 'Index', 'Switch', 'Dynamic']);
98
+ const FOLDABLE_FLOW = new Set(['Show', 'For', 'Repeat', 'Switch', 'Dynamic']);
87
99
 
88
100
  /**
89
101
  * What a resolved control-flow element renders in its place.
@@ -198,6 +210,78 @@ function continuesPreviousStatement(text: string): boolean {
198
210
  return /^[([`+\-/]/.test(text);
199
211
  }
200
212
 
213
+ /** The name a property key or a computed member's string literal gives. */
214
+ function keyName(node: Node): string | undefined {
215
+ if (node.type === 'Identifier') {
216
+ return node.name;
217
+ }
218
+ return node.type === 'Literal' && typeof node.value === 'string' ? node.value : undefined;
219
+ }
220
+
221
+ type ConstantItem =
222
+ | { readonly kind: 'primitive'; readonly text: string }
223
+ | { readonly kind: 'object'; readonly keys: ReadonlyMap<string, string> };
224
+
225
+ /**
226
+ * The text of an expression that always gives the same primitive: a literal
227
+ * other than a regular expression, a template literal without expressions,
228
+ * or a negated number.
229
+ */
230
+ function primitiveText(context: PassContext, node: Expression): string | undefined {
231
+ let expression: Expression = node;
232
+ while (expression.type === 'ParenthesizedExpression') {
233
+ expression = expression.expression;
234
+ }
235
+ switch (expression.type) {
236
+ case 'Literal':
237
+ return 'regex' in expression ? undefined : textOf(context, expression);
238
+ case 'TemplateLiteral':
239
+ return expression.expressions.length === 0 ? textOf(context, expression) : undefined;
240
+ case 'UnaryExpression':
241
+ return expression.operator === '-' &&
242
+ expression.argument.type === 'Literal' &&
243
+ typeof expression.argument.value === 'number'
244
+ ? textOf(context, expression)
245
+ : undefined;
246
+ default:
247
+ return undefined;
248
+ }
249
+ }
250
+
251
+ /** Whether a child of `parent` is inserted into its template, not passed as a prop. */
252
+ function joinsTemplate(parent: JSXElement | JSXFragment): boolean {
253
+ if (parent.type === 'JSXFragment') {
254
+ return true;
255
+ }
256
+ const { name } = parent.openingElement;
257
+ return name.type === 'JSXIdentifier' && isIntrinsicTag(name.name);
258
+ }
259
+
260
+ /**
261
+ * Whether JSX holds a `ref` or a spread, which run while the JSX is made.
262
+ */
263
+ function hasRefOrSpread(root: Node): boolean {
264
+ let found = false;
265
+ const visit = (node: Node): void => {
266
+ if (found) {
267
+ return;
268
+ }
269
+ if (
270
+ node.type === 'JSXSpreadAttribute' ||
271
+ node.type === 'JSXSpreadChild' ||
272
+ (node.type === 'JSXAttribute' &&
273
+ node.name.type === 'JSXIdentifier' &&
274
+ node.name.name === 'ref')
275
+ ) {
276
+ found = true;
277
+ return;
278
+ }
279
+ forEachChild(node, visit);
280
+ };
281
+ visit(root);
282
+ return found;
283
+ }
284
+
201
285
  class Folder {
202
286
  changed = false;
203
287
 
@@ -446,6 +530,50 @@ class Folder {
446
530
  return identity;
447
531
  }
448
532
 
533
+ /**
534
+ * The name of the component an identifier refers to, when it is a
535
+ * capitalized top-level binding nothing reassigns, holding a function or a
536
+ * `lazy` component. A JSX tag with that name calls the same component. An
537
+ * import could hold anything, such as a tag name string, so it is left out.
538
+ */
539
+ private componentName(identifier: IdentifierReference): string | undefined {
540
+ const binding = this.context.scopes.references.get(identifier);
541
+ if (
542
+ !binding ||
543
+ binding.mutated ||
544
+ binding.scope.parent !== undefined ||
545
+ !/^[A-Z]/.test(binding.name)
546
+ ) {
547
+ return undefined;
548
+ }
549
+ const { declaration } = binding;
550
+ if (declaration.type === 'FunctionDeclaration') {
551
+ return declaration.async || declaration.generator ? undefined : binding.name;
552
+ }
553
+ if (
554
+ declaration.type !== 'VariableDeclarator' ||
555
+ declaration.id !== binding.identifier ||
556
+ !declaration.init ||
557
+ !isConstantDeclaration(binding, this.context.options)
558
+ ) {
559
+ return undefined;
560
+ }
561
+ let init: Expression = declaration.init;
562
+ while (init.type === 'ParenthesizedExpression') {
563
+ init = init.expression;
564
+ }
565
+ if (init.type === 'ArrowFunctionExpression' || init.type === 'FunctionExpression') {
566
+ return init.async || init.generator ? undefined : binding.name;
567
+ }
568
+ if (init.type === 'CallExpression' && init.callee.type === 'Identifier') {
569
+ const callee = this.context.scopes.references.get(init.callee);
570
+ return callee && solidExport(callee, this.context.options) === 'lazy'
571
+ ? binding.name
572
+ : undefined;
573
+ }
574
+ return undefined;
575
+ }
576
+
449
577
  private flowTag(element: JSXElement): string | undefined {
450
578
  const tag = this.builtInTag(element);
451
579
  return tag !== undefined && FOLDABLE_FLOW.has(tag) ? tag : undefined;
@@ -460,8 +588,9 @@ class Folder {
460
588
  case 'Show':
461
589
  return this.foldShow(element);
462
590
  case 'For':
463
- case 'Index':
464
591
  return this.foldFor(element);
592
+ case 'Repeat':
593
+ return this.foldRepeat(element);
465
594
  case 'Switch':
466
595
  return this.foldSwitch(element);
467
596
  case 'Dynamic':
@@ -562,11 +691,361 @@ class Folder {
562
691
  }
563
692
  const { expression } = each.value;
564
693
  // `each={[]}` renders the fallback, and so does a statically falsy `each`,
565
- // which `mapArray` and `indexArray` treat as an empty list. Either way the expression is
694
+ // which `mapArray` treats as an empty list. Either way the expression is
566
695
  // dropped, so it has to be skippable.
567
696
  const empty =
568
697
  arrayLiteralLength(expression) === 0 || truthiness(expression, this.lookup) === false;
569
- if (!empty || !isSideEffectFree(expression)) {
698
+ if (!empty) {
699
+ return this.unrollFor(element, expression);
700
+ }
701
+ if (!isSideEffectFree(expression)) {
702
+ return undefined;
703
+ }
704
+ return this.fallback(element);
705
+ }
706
+
707
+ /**
708
+ * Unrolls `<For>` over a constant list into one copy of its row per item.
709
+ *
710
+ * The list is an array literal, or a binding of one that only `<For>`
711
+ * reads, so nothing can change it. Each item is a primitive literal, or an
712
+ * object literal of them. The row is an arrow function whose body is JSX,
713
+ * and reads the item as `item.key`, or as itself when it is a primitive.
714
+ * Each row ran once, untracked, under its own owner. A copy is made with
715
+ * the JSX around it instead, which runs untracked too, and the JSX
716
+ * transform gives every dynamic part its own effect. A `ref` or a spread
717
+ * would run while the copy is made, so either one keeps the loop.
718
+ */
719
+ private unrollFor(element: JSXElement, expression: Expression): Fold | undefined {
720
+ if (
721
+ element.openingElement.attributes.some(
722
+ (attribute) =>
723
+ attribute.type === 'JSXAttribute' &&
724
+ attribute.name.type === 'JSXIdentifier' &&
725
+ attribute.name.name === 'keyed' &&
726
+ !(
727
+ attribute.value?.type === 'JSXExpressionContainer' &&
728
+ attribute.value.expression.type === 'Literal' &&
729
+ attribute.value.expression.value === false
730
+ ),
731
+ )
732
+ ) {
733
+ return undefined;
734
+ }
735
+ const byIndex = findAttribute(element, 'keyed') !== undefined;
736
+ const list = this.constantList(expression);
737
+ if (!list) {
738
+ return undefined;
739
+ }
740
+ const significant = element.children.filter((child) => !isInsignificant(child));
741
+ const only = significant.at(0);
742
+ if (significant.length !== 1 || only?.type !== 'JSXExpressionContainer') {
743
+ return undefined;
744
+ }
745
+ let row: Node = only.expression;
746
+ while (row.type === 'ParenthesizedExpression') {
747
+ row = row.expression;
748
+ }
749
+ if (
750
+ row.type !== 'ArrowFunctionExpression' ||
751
+ row.async ||
752
+ !row.expression ||
753
+ row.params.length > 2
754
+ ) {
755
+ return undefined;
756
+ }
757
+ let body: Node = row.body;
758
+ while (body.type === 'ParenthesizedExpression') {
759
+ body = body.expression;
760
+ }
761
+ if ((body.type !== 'JSXElement' && body.type !== 'JSXFragment') || hasRefOrSpread(body)) {
762
+ return undefined;
763
+ }
764
+ // A fold inside the row in this pass would be lost, so it waits for the next pass.
765
+ if (
766
+ this.context.s.slice(body.start, body.end) !== this.context.code.slice(body.start, body.end)
767
+ ) {
768
+ return undefined;
769
+ }
770
+ const scope = this.context.scopes.scopes.get(row);
771
+ if (!scope) {
772
+ return undefined;
773
+ }
774
+ const params: Binding[] = [];
775
+ for (const param of row.params) {
776
+ const binding = param.type === 'Identifier' ? scope.bindings.get(param.name) : undefined;
777
+ if (!binding || binding.mutated) {
778
+ return undefined;
779
+ }
780
+ params.push(binding);
781
+ }
782
+ const itemParam = params.at(0);
783
+ const indexParam = params.at(1);
784
+ const rows: string[] = [];
785
+ for (const [index, item] of list.items.entries()) {
786
+ const copy = new MagicString(this.context.code);
787
+ // With `keyed={false}` the item is an accessor and the index a number, and the other way around otherwise.
788
+ if (
789
+ (itemParam && !this.substituteItem(copy, itemParam, item, byIndex)) ||
790
+ (indexParam && !this.substituteIndex(copy, indexParam, index, !byIndex))
791
+ ) {
792
+ return undefined;
793
+ }
794
+ rows.push(copy.slice(body.start, body.end));
795
+ }
796
+ const text = `<>${rows.join('')}</>`;
797
+ if (!this.unrollingPays(element, text, list.declaration)) {
798
+ return undefined;
799
+ }
800
+ return { kind: 'jsx', text };
801
+ }
802
+
803
+ /**
804
+ * The items of a constant list, and the declaration that goes once no
805
+ * `<For>` reads it.
806
+ */
807
+ private constantList(
808
+ expression: Expression,
809
+ ): { items: ConstantItem[]; declaration: Node | undefined } | undefined {
810
+ let node: Expression = expression;
811
+ while (node.type === 'ParenthesizedExpression') {
812
+ node = node.expression;
813
+ }
814
+ let declaration: Node | undefined;
815
+ if (node.type === 'Identifier') {
816
+ const binding = this.context.scopes.references.get(node);
817
+ if (
818
+ binding?.declaration.type !== 'VariableDeclarator' ||
819
+ binding.declaration.id !== binding.identifier ||
820
+ !binding.declaration.init ||
821
+ !isConstantDeclaration(binding, this.context.options)
822
+ ) {
823
+ return undefined;
824
+ }
825
+ // Any other use could change the list, and an export can be changed by another module.
826
+ const statement = this.context.parents.get(binding.declaration);
827
+ const owner = statement ? this.context.parents.get(statement) : undefined;
828
+ if (
829
+ owner?.type === 'ExportNamedDeclaration' ||
830
+ !binding.references.every((reference) => this.isForEach(reference))
831
+ ) {
832
+ return undefined;
833
+ }
834
+ node = binding.declaration.init;
835
+ while (node.type === 'ParenthesizedExpression') {
836
+ node = node.expression;
837
+ }
838
+ declaration =
839
+ binding.references.length === 1 &&
840
+ statement?.type === 'VariableDeclaration' &&
841
+ statement.declarations.length === 1
842
+ ? statement
843
+ : undefined;
844
+ }
845
+ if (node.type !== 'ArrayExpression') {
846
+ return undefined;
847
+ }
848
+ const items: ConstantItem[] = [];
849
+ for (const element of node.elements) {
850
+ const item =
851
+ element && element.type !== 'SpreadElement' ? this.constantItem(element) : undefined;
852
+ if (!item) {
853
+ return undefined;
854
+ }
855
+ items.push(item);
856
+ }
857
+ return { items, declaration };
858
+ }
859
+
860
+ /** Whether a reference is the whole `each` of a Solid `<For>`. */
861
+ private isForEach(reference: Node): boolean {
862
+ const container = this.context.parents.get(reference);
863
+ const attribute = container ? this.context.parents.get(container) : undefined;
864
+ const opening = attribute ? this.context.parents.get(attribute) : undefined;
865
+ const element = opening ? this.context.parents.get(opening) : undefined;
866
+ return (
867
+ container?.type === 'JSXExpressionContainer' &&
868
+ attribute?.type === 'JSXAttribute' &&
869
+ attribute.name.type === 'JSXIdentifier' &&
870
+ attribute.name.name === 'each' &&
871
+ element?.type === 'JSXElement' &&
872
+ this.builtInTag(element) === 'For'
873
+ );
874
+ }
875
+
876
+ /** A list item whose value is known: a primitive literal, or an object literal of them. */
877
+ private constantItem(node: Expression): ConstantItem | undefined {
878
+ const primitive = primitiveText(this.context, node);
879
+ if (primitive !== undefined) {
880
+ return { kind: 'primitive', text: primitive };
881
+ }
882
+ if (node.type !== 'ObjectExpression') {
883
+ return undefined;
884
+ }
885
+ const keys = new Map<string, string>();
886
+ for (const property of node.properties) {
887
+ if (
888
+ property.type !== 'Property' ||
889
+ property.kind !== 'init' ||
890
+ property.method ||
891
+ property.computed
892
+ ) {
893
+ return undefined;
894
+ }
895
+ const key = keyName(property.key);
896
+ const value = primitiveText(this.context, property.value);
897
+ if (key === undefined || value === undefined || key === '__proto__') {
898
+ return undefined;
899
+ }
900
+ keys.set(key, value);
901
+ }
902
+ return { kind: 'object', keys };
903
+ }
904
+
905
+ /**
906
+ * Writes an item's value over each read of the row's item parameter.
907
+ * `false` when a read is not one the value can take the place of.
908
+ */
909
+ private substituteItem(
910
+ copy: MagicString,
911
+ param: Binding,
912
+ item: ConstantItem,
913
+ accessor: boolean,
914
+ ): boolean {
915
+ for (const reference of param.references) {
916
+ let read: Node = reference;
917
+ if (accessor) {
918
+ const call = this.context.parents.get(reference);
919
+ if (
920
+ call?.type !== 'CallExpression' ||
921
+ call.callee !== reference ||
922
+ call.arguments.length > 0
923
+ ) {
924
+ return false;
925
+ }
926
+ read = call;
927
+ }
928
+ if (item.kind === 'primitive') {
929
+ copy.overwrite(read.start, read.end, this.valueAt(read, item.text));
930
+ continue;
931
+ }
932
+ const member = this.context.parents.get(read);
933
+ if (
934
+ member?.type !== 'MemberExpression' ||
935
+ member.object !== read ||
936
+ isWriteTarget(member, this.context.parents)
937
+ ) {
938
+ return false;
939
+ }
940
+ // `item[name]` reads a variable key, so only a string literal counts when computed.
941
+ let key: string | undefined;
942
+ if (!member.computed) {
943
+ key = member.property.type === 'Identifier' ? member.property.name : undefined;
944
+ } else if (member.property.type === 'Literal') {
945
+ key = keyName(member.property);
946
+ }
947
+ // A call would run with the item as `this`, and a missing key could be on the prototype.
948
+ const parent = this.context.parents.get(member);
949
+ if (
950
+ key === undefined ||
951
+ (parent?.type === 'CallExpression' && parent.callee === member) ||
952
+ !item.keys.has(key)
953
+ ) {
954
+ return false;
955
+ }
956
+ copy.overwrite(
957
+ member.start,
958
+ member.end,
959
+ this.valueAt(member, item.keys.get(key) ?? 'void 0'),
960
+ );
961
+ }
962
+ return true;
963
+ }
964
+
965
+ /** A value's text in place of `node`, with parentheses unless it fills a JSX container. */
966
+ private valueAt(node: Node, text: string): string {
967
+ return this.context.parents.get(node)?.type === 'JSXExpressionContainer' ? text : `(${text})`;
968
+ }
969
+
970
+ /** Writes an item's index over each read of the row's index parameter. */
971
+ private substituteIndex(
972
+ copy: MagicString,
973
+ param: Binding,
974
+ index: number,
975
+ accessor: boolean,
976
+ ): boolean {
977
+ for (const reference of param.references) {
978
+ let read: Node = reference;
979
+ if (accessor) {
980
+ const call = this.context.parents.get(reference);
981
+ if (
982
+ call?.type !== 'CallExpression' ||
983
+ call.callee !== reference ||
984
+ call.arguments.length > 0
985
+ ) {
986
+ return false;
987
+ }
988
+ read = call;
989
+ }
990
+ copy.overwrite(read.start, read.end, String(index));
991
+ }
992
+ return true;
993
+ }
994
+
995
+ /**
996
+ * Whether the copies are estimated to be no larger, once lowered, than
997
+ * the loop and the list it no longer needs.
998
+ */
999
+ private unrollingPays(element: JSXElement, text: string, declaration: Node | undefined): boolean {
1000
+ const inTemplate = this.joinsParentTemplate(element);
1001
+ const loop =
1002
+ new SizeEstimator(this.context.code).jsx(element, inTemplate) +
1003
+ (declaration
1004
+ ? compactLength(this.context.code.slice(declaration.start, declaration.end))
1005
+ : 0);
1006
+ const code = `const __so_rows__ = ${text};`;
1007
+ const program = parse(this.context.filename, code);
1008
+ const statement = program.body.at(0);
1009
+ const init =
1010
+ statement?.type === 'VariableDeclaration' ? statement.declarations.at(0)?.init : undefined;
1011
+ if (init?.type !== 'JSXFragment') {
1012
+ return false;
1013
+ }
1014
+ // In an element, the rows splice into its template. Elsewhere they are a fragment of templates.
1015
+ const estimator = new SizeEstimator(code);
1016
+ const unrolled = inTemplate
1017
+ ? init.children.reduce(
1018
+ (size, child) =>
1019
+ size +
1020
+ (child.type === 'JSXElement' ? estimator.jsx(child, true) : estimator.node(child)),
1021
+ 0,
1022
+ )
1023
+ : estimator.jsx(init, false);
1024
+ return unrolled <= loop;
1025
+ }
1026
+
1027
+ /** Whether an element sits directly in an element or fragment whose template it joins. */
1028
+ private joinsParentTemplate(element: JSXElement): boolean {
1029
+ const parent = this.context.parents.get(element);
1030
+ return (
1031
+ (parent?.type === 'JSXElement' && joinsTemplate(parent)) || parent?.type === 'JSXFragment'
1032
+ );
1033
+ }
1034
+
1035
+ private foldRepeat(element: JSXElement): Fold | undefined {
1036
+ const count = findAttribute(element, 'count');
1037
+ if (
1038
+ count?.value?.type !== 'JSXExpressionContainer' ||
1039
+ count.value.expression.type === 'JSXEmptyExpression'
1040
+ ) {
1041
+ return undefined;
1042
+ }
1043
+ const value = evaluate(count.value.expression, this.lookup);
1044
+ if (typeof value?.value !== 'number') {
1045
+ return undefined;
1046
+ }
1047
+ // Written this way so `NaN` counts as empty, like `repeat` does.
1048
+ if (value.value >= 1) {
570
1049
  return undefined;
571
1050
  }
572
1051
  return this.fallback(element);
@@ -627,6 +1106,12 @@ class Folder {
627
1106
  * `<Dynamic component="div">` is just `<div>`, which the JSX transform can
628
1107
  * put in a template instead of creating the element at runtime.
629
1108
  */
1109
+ /**
1110
+ * `<Dynamic component="div">` becomes `<div>`. `<Dynamic component={Card}>`
1111
+ * becomes `<Card>` when `Card` is a component declared at the top level
1112
+ * that nothing reassigns. `<Dynamic>` then only renders `Card` with the
1113
+ * other props, through a memo that never changes.
1114
+ */
630
1115
  private foldDynamic(element: JSXElement): Fold | undefined {
631
1116
  const component = findAttribute(element, 'component');
632
1117
  if (!component?.value) {
@@ -635,17 +1120,26 @@ class Folder {
635
1120
  let tag: string | undefined;
636
1121
  const { value } = component;
637
1122
  if (value.type === 'Literal') {
638
- tag = value.value;
1123
+ tag = isIntrinsicTag(value.value) ? value.value : undefined;
639
1124
  } else if (
640
1125
  value.type === 'JSXExpressionContainer' &&
641
1126
  value.expression.type !== 'JSXEmptyExpression'
642
1127
  ) {
643
- const result = evaluate(value.expression, this.lookup);
644
- if (typeof result?.value === 'string') {
645
- tag = result.value;
1128
+ const expression =
1129
+ value.expression.type === 'ParenthesizedExpression'
1130
+ ? value.expression.expression
1131
+ : value.expression;
1132
+ if (expression.type === 'Identifier') {
1133
+ tag = this.componentName(expression);
1134
+ }
1135
+ if (tag === undefined) {
1136
+ const result = evaluate(value.expression, this.lookup);
1137
+ if (typeof result?.value === 'string' && isIntrinsicTag(result.value)) {
1138
+ tag = result.value;
1139
+ }
646
1140
  }
647
1141
  }
648
- if (tag === undefined || !isIntrinsicTag(tag)) {
1142
+ if (tag === undefined) {
649
1143
  return undefined;
650
1144
  }
651
1145
  const attributes = element.openingElement.attributes
@@ -713,6 +1207,15 @@ class Folder {
713
1207
  pieces.push(splicePiece(this.context.s, child, child.children));
714
1208
  continue;
715
1209
  }
1210
+ const reduced =
1211
+ child.type === 'JSXExpressionContainer' && joinsTemplate(parent)
1212
+ ? this.reducedCall(child.expression)
1213
+ : undefined;
1214
+ if (reduced !== undefined) {
1215
+ folded = true;
1216
+ pieces.push(replacedPiece(child, reduced));
1217
+ continue;
1218
+ }
716
1219
  const resolved = child.type === 'JSXElement' ? this.foldFlow(child) : undefined;
717
1220
  if (!resolved) {
718
1221
  pieces.push(keptPiece(child));
@@ -739,6 +1242,105 @@ class Folder {
739
1242
  }
740
1243
  }
741
1244
 
1245
+ /**
1246
+ * The JSX a call like `((n) => <li>{n}</li>)(1)` makes, with each
1247
+ * argument in place of its parameter, or `undefined` when that could
1248
+ * behave differently.
1249
+ *
1250
+ * The child is inserted by an effect that makes the JSX. The JSX
1251
+ * transform wraps every dynamic part of JSX in an effect of its own, so
1252
+ * making it reads nothing the outer effect tracks, and the outer effect
1253
+ * runs once. A `ref` runs while the JSX is made, and a spread reads its
1254
+ * object there, so either one keeps the call. Each argument has to be a
1255
+ * constant or a binding nothing reassigns, so reading it again where the
1256
+ * parameter was gives the same value.
1257
+ */
1258
+ private reducedCall(expression: Expression | JSXEmptyExpression): string | undefined {
1259
+ if (expression.type !== 'CallExpression' || expression.optional) {
1260
+ return undefined;
1261
+ }
1262
+ let callee: Expression = expression.callee;
1263
+ while (callee.type === 'ParenthesizedExpression') {
1264
+ callee = callee.expression;
1265
+ }
1266
+ if (callee.type !== 'ArrowFunctionExpression' || callee.async || !callee.expression) {
1267
+ return undefined;
1268
+ }
1269
+ let body: Node = callee.body;
1270
+ while (body.type === 'ParenthesizedExpression') {
1271
+ body = body.expression;
1272
+ }
1273
+ if (body.type !== 'JSXElement' && body.type !== 'JSXFragment') {
1274
+ return undefined;
1275
+ }
1276
+ const { params } = callee;
1277
+ const args = expression.arguments;
1278
+ if (params.length !== args.length || hasRefOrSpread(body)) {
1279
+ return undefined;
1280
+ }
1281
+ // A fold inside the body in this pass would be lost, so it waits for the next pass.
1282
+ if (
1283
+ this.context.s.slice(body.start, body.end) !== this.context.code.slice(body.start, body.end)
1284
+ ) {
1285
+ return undefined;
1286
+ }
1287
+ const scope = this.context.scopes.scopes.get(callee);
1288
+ if (!scope) {
1289
+ return undefined;
1290
+ }
1291
+ const copy = new MagicString(this.context.code);
1292
+ for (const [index, param] of params.entries()) {
1293
+ const arg = args.at(index);
1294
+ if (param.type !== 'Identifier' || !arg || arg.type === 'SpreadElement') {
1295
+ return undefined;
1296
+ }
1297
+ const binding = scope.bindings.get(param.name);
1298
+ const text = this.argumentText(arg);
1299
+ if (!binding || binding.mutated || text === undefined) {
1300
+ return undefined;
1301
+ }
1302
+ for (const reference of binding.references) {
1303
+ // A binding argument has to mean the same where the parameter was read.
1304
+ if (
1305
+ arg.type === 'Identifier' &&
1306
+ lookup(scopeAt(this.context.scopes, this.context.parents, reference), arg.name) !==
1307
+ this.context.scopes.references.get(arg)
1308
+ ) {
1309
+ return undefined;
1310
+ }
1311
+ const parent = this.context.parents.get(reference);
1312
+ const shorthand =
1313
+ parent?.type === 'Property' && parent.shorthand && parent.value === reference;
1314
+ copy.overwrite(reference.start, reference.end, shorthand ? `${param.name}: ${text}` : text);
1315
+ }
1316
+ }
1317
+ return copy.slice(body.start, body.end);
1318
+ }
1319
+
1320
+ /** The text of an argument that reads the same wherever it is copied. */
1321
+ private argumentText(arg: Expression): string | undefined {
1322
+ let node: Expression = arg;
1323
+ while (node.type === 'ParenthesizedExpression') {
1324
+ node = node.expression;
1325
+ }
1326
+ switch (node.type) {
1327
+ case 'Literal':
1328
+ return 'regex' in node ? undefined : textOf(this.context, node);
1329
+ case 'TemplateLiteral':
1330
+ return node.expressions.length === 0 ? textOf(this.context, node) : undefined;
1331
+ case 'UnaryExpression':
1332
+ return node.operator === '-' && node.argument.type === 'Literal'
1333
+ ? `(${textOf(this.context, node)})`
1334
+ : undefined;
1335
+ case 'Identifier': {
1336
+ const binding = this.context.scopes.references.get(node);
1337
+ return binding && !binding.mutated ? node.name : undefined;
1338
+ }
1339
+ default:
1340
+ return undefined;
1341
+ }
1342
+ }
1343
+
742
1344
  // ---------------------------------------------------------------------------
743
1345
  // Dead statements
744
1346
  // ---------------------------------------------------------------------------