solid-optimizer 1.0.0-next.4 → 1.0.0-next.5

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "solid-optimizer",
3
- "version": "1.0.0-next.4",
3
+ "version": "1.0.0-next.5",
4
4
  "description": "Experimental compile-time optimizer for SolidJS",
5
5
  "keywords": [
6
6
  "compiler",
package/src/ast.ts CHANGED
@@ -90,7 +90,7 @@ const RAW_TRANSFER = rawTransferSupported();
90
90
 
91
91
  export function parse(filename: string, code: string): Program {
92
92
  const options: ParserOptions & { experimentalRawTransfer?: boolean } = {
93
- lang: languageOf(filename),
93
+ lang: getLanguage(filename),
94
94
  sourceType: 'module',
95
95
  preserveParens: true,
96
96
  experimentalRawTransfer: RAW_TRANSFER,
@@ -103,7 +103,7 @@ export function parse(filename: string, code: string): Program {
103
103
  return result.program;
104
104
  }
105
105
 
106
- function languageOf(filename: string): 'jsx' | 'ts' | 'tsx' {
106
+ function getLanguage(filename: string): 'jsx' | 'ts' | 'tsx' {
107
107
  if (/\.tsx$/i.test(filename)) {
108
108
  return 'tsx';
109
109
  }
@@ -124,7 +124,8 @@ export function unwrap(node: Expression): Expression {
124
124
  current.type === 'TSAsExpression' ||
125
125
  current.type === 'TSSatisfiesExpression' ||
126
126
  current.type === 'TSNonNullExpression' ||
127
- current.type === 'TSTypeAssertion'
127
+ current.type === 'TSTypeAssertion' ||
128
+ current.type === 'TSInstantiationExpression'
128
129
  ) {
129
130
  current = current.expression;
130
131
  }
package/src/compile.ts CHANGED
@@ -11,6 +11,7 @@ import { fold } from './fold';
11
11
  import { inline } from './inline';
12
12
  import { inlineMemos } from './memo';
13
13
  import { removeProviders } from './provider';
14
+ import { lowerConditionals } from './conditional';
14
15
  import type { ScopeAnalysis } from './scope';
15
16
  import { analyzeScopes } from './scope';
16
17
  import type { Primitive } from './value';
@@ -50,6 +51,14 @@ export interface CompileOptions {
50
51
  * @default true
51
52
  */
52
53
  memos?: boolean;
54
+ /**
55
+ * Replace a `<Show>` or `<Switch>` without callback children or `keyed`
56
+ * with a ternary, which Solid's JSX transform compiles to memos without a
57
+ * component.
58
+ *
59
+ * @default true
60
+ */
61
+ conditionals?: boolean;
53
62
  /**
54
63
  * The names of Solid's built-in components. A tag only folds when it is
55
64
  * one of these, and an empty list turns control-flow folding off.
@@ -167,6 +176,12 @@ const DEFAULT_BUILT_INS = [
167
176
  const DEFAULT_MODULE_SOURCES = ['solid-js', '@solidjs/web'];
168
177
 
169
178
  function resolveOptions(options: CompileOptions): ResolvedOptions {
179
+ // Each module's context names become a set.
180
+ const importedContexts = new Map<string, Set<string>>();
181
+ for (const [source, names] of Object.entries(options.importedContexts ?? {})) {
182
+ importedContexts.set(source, new Set(names));
183
+ }
184
+
170
185
  return {
171
186
  builtIns: new Set(options.builtIns ?? DEFAULT_BUILT_INS),
172
187
  moduleSources: options.moduleSources ?? DEFAULT_MODULE_SOURCES,
@@ -174,12 +189,7 @@ function resolveOptions(options: CompileOptions): ResolvedOptions {
174
189
  constantVars: options.constantVars ?? false,
175
190
  importedConstants: resolveImportedConstants(options.importedConstants),
176
191
  globalConstants: new Map(Object.entries(options.globalConstants ?? {})),
177
- importedContexts: new Map(
178
- Object.entries(options.importedContexts ?? {}).map(([source, names]) => [
179
- source,
180
- new Set(names),
181
- ]),
182
- ),
192
+ importedContexts,
183
193
  sharedComponents: new Map(Object.entries(options.sharedComponents ?? {})),
184
194
  alwaysInline: options.alwaysInline ?? false,
185
195
  alwaysInlineComponents: new Set(options.alwaysInlineComponents ?? []),
@@ -298,6 +308,29 @@ export function compile(code: string, options: CompileOptions = {}): CompileResu
298
308
  }
299
309
  }
300
310
 
311
+ // `<Show>` and `<Switch>` are lowered last. The other passes read `when` of
312
+ // `<Show>` and `<Match>` as a tracked place, and a ternary's condition is
313
+ // not one. A lowered one can hold another, which the next round lowers.
314
+ if (options.conditionals ?? true) {
315
+ for (let round = 0; round < maxPasses; round += 1) {
316
+ const result = runPass(
317
+ parsedCurrent(),
318
+ filename,
319
+ resolved,
320
+ sourceMap,
321
+ lowerConditionals,
322
+ undefined,
323
+ );
324
+ if (!result) {
325
+ break;
326
+ }
327
+ current = result.code;
328
+ if (result.map !== undefined) {
329
+ maps.push(result.map);
330
+ }
331
+ }
332
+ }
333
+
301
334
  const report = skipped ? { skipped } : {};
302
335
  if (maps.length === 0) {
303
336
  return { code: current, map: null, ...report };
@@ -0,0 +1,540 @@
1
+ /**
2
+ * `<Show>` and `<Switch>` lowering.
3
+ *
4
+ * Solid's JSX transform compiles `{when ? children : fallback}` to a memo of
5
+ * `!!when` and a function that renders the branch it selects, which is what
6
+ * `<Show>` does without a callback child or `keyed`. The ternary skips the
7
+ * component call, the props object with its getters, and two of `<Show>`'s
8
+ * three memos.
9
+ *
10
+ * A `<Switch>` becomes a chain, `a ? A : b ? B : fallback`. The transform
11
+ * gives each later condition its own memo, read only when the ones before it
12
+ * are falsy, as `<Switch>` reads its `<Match>` conditions.
13
+ *
14
+ * A callback child like `{(user) => <b>{user().name}</b>}` becomes its body,
15
+ * with each `user()` read as `when` again. Only a `when` that reads names,
16
+ * members, and signals or memos is copied, so reading it again gives the same
17
+ * value. `<Show>`'s
18
+ * accessor throws when it is read after the condition turns falsy, and the
19
+ * copy reads the falsy value instead.
20
+ */
21
+ import type { ArrowFunctionExpression, JSXAttribute, JSXChild, JSXElement, Node } from 'oxc-parser';
22
+ import { forEachChild, isFunctionNode, isInsignificant, isIntrinsicTag, unwrap } from './ast';
23
+ import type { PassContext } from './context';
24
+ import { solidExport } from './context';
25
+ import { findAttribute } from './jsx';
26
+ import { lookup, scopeAt } from './scope';
27
+
28
+ /**
29
+ * How a lowered `<Show>` or `<Switch>` is written where it stands.
30
+ *
31
+ * - `container`: `{when ? children : fallback}`. A child of an element is
32
+ * inserted, and a child of a fragment becomes a memo, so both track the
33
+ * ternary.
34
+ * - `fragment`: `<>{when ? children : fallback}</>`, which compiles to a memo.
35
+ * A ternary alone as a component's child would be read again on every read
36
+ * of `props.children`, without a memo around it.
37
+ */
38
+ type Form = 'container' | 'fragment';
39
+
40
+ /**
41
+ * Rewrites each `<Show>` and `<Switch>` that can be lowered. One inside
42
+ * another that is lowered stays for the next run, since both would edit the
43
+ * same text.
44
+ */
45
+ export function lowerConditionals(context: PassContext): boolean {
46
+ let changed = false;
47
+ visit(context.program);
48
+ return changed;
49
+
50
+ function visit(node: Node): void {
51
+ if (node.type === 'JSXElement') {
52
+ const ternary = ternaryOf(context, node);
53
+ const form = ternary === undefined ? undefined : formAt(context, node);
54
+ if (ternary !== undefined && form !== undefined) {
55
+ context.s.overwrite(
56
+ node.start,
57
+ node.end,
58
+ form === 'container' ? `{${ternary}}` : `<>{${ternary}}</>`,
59
+ );
60
+ changed = true;
61
+ return;
62
+ }
63
+ }
64
+ forEachChild(node, visit);
65
+ }
66
+ }
67
+
68
+ /**
69
+ * The Solid built-in an element's tag resolves to, by the name Solid exports it under.
70
+ */
71
+ function builtInOf(context: PassContext, element: JSXElement): string | undefined {
72
+ const { name } = element.openingElement;
73
+ if (name.type !== 'JSXIdentifier') {
74
+ return undefined;
75
+ }
76
+ const { references } = context.scopes;
77
+ if (!references.has(name)) {
78
+ return undefined;
79
+ }
80
+ const binding = references.get(name);
81
+ const identity = binding ? solidExport(binding, context.options) : name.name;
82
+ return identity !== undefined && context.options.builtIns.has(identity) ? identity : undefined;
83
+ }
84
+
85
+ /**
86
+ * The ternary a `<Show>` or `<Switch>` lowers to, or `undefined` when its
87
+ * props or children need the component.
88
+ */
89
+ function ternaryOf(context: PassContext, element: JSXElement): string | undefined {
90
+ switch (builtInOf(context, element)) {
91
+ case 'Show': {
92
+ const branch = branchOf(context, element, ['when', 'fallback']);
93
+ if (branch === undefined) {
94
+ return undefined;
95
+ }
96
+ return `${branch.when} ? ${branch.children} : ${branch.fallback ?? 'undefined'}`;
97
+ }
98
+ case 'Switch':
99
+ return switchTernary(context, element);
100
+ default:
101
+ return undefined;
102
+ }
103
+ }
104
+
105
+ /**
106
+ * A `<Switch>` whose children are all `<Match>`es that lower, as a chain of ternaries.
107
+ */
108
+ function switchTernary(context: PassContext, element: JSXElement): string | undefined {
109
+ const props = propsOf(context, element, ['fallback']);
110
+ if (props === undefined) {
111
+ return undefined;
112
+ }
113
+ let chain = '';
114
+ let count = 0;
115
+ for (const child of significantChildren(element.children)) {
116
+ if (child.type !== 'JSXElement' || builtInOf(context, child) !== 'Match') {
117
+ return undefined;
118
+ }
119
+ const branch = branchOf(context, child, ['when']);
120
+ if (branch === undefined) {
121
+ return undefined;
122
+ }
123
+ chain += `${branch.when} ? ${branch.children} : `;
124
+ count += 1;
125
+ }
126
+ // A `<Switch>` without a `<Match>` renders its fallback, which the fold pass resolves.
127
+ if (count === 0) {
128
+ return undefined;
129
+ }
130
+ return `${chain}${props.get('fallback') ?? 'undefined'}`;
131
+ }
132
+
133
+ /**
134
+ * How a `<Show>` or `<Switch>` at this position is written once lowered, or `undefined`
135
+ * when the position is not supported.
136
+ */
137
+ function formAt(context: PassContext, element: JSXElement): Form | undefined {
138
+ const parent = context.parents.get(element);
139
+ if (parent === undefined) {
140
+ return 'fragment';
141
+ }
142
+ switch (parent.type) {
143
+ case 'JSXFragment':
144
+ return 'container';
145
+ case 'JSXElement': {
146
+ const { name } = parent.openingElement;
147
+ // A namespaced tag like `svg:g` is an element too.
148
+ if (
149
+ name.type === 'JSXNamespacedName' ||
150
+ (name.type === 'JSXIdentifier' && isIntrinsicTag(name.name))
151
+ ) {
152
+ return 'container';
153
+ }
154
+ // A component's children are one prop. Only a sole child keeps that prop a memo.
155
+ return isSoleChild(parent.children, element) ? 'fragment' : undefined;
156
+ }
157
+ case 'JSXExpressionContainer':
158
+ case 'JSXAttribute':
159
+ return undefined;
160
+ default:
161
+ // An expression outside JSX, such as a return value or a callback's body.
162
+ return isInJSXExpression(context, parent) ? undefined : 'fragment';
163
+ }
164
+ }
165
+
166
+ /**
167
+ * Whether a node is part of an expression in a JSX container, such as
168
+ * `{ok && <Show />}`, where a function boundary does not separate them.
169
+ */
170
+ function isInJSXExpression(context: PassContext, node: Node): boolean {
171
+ let current: Node | undefined = node;
172
+ while (current !== undefined && !isFunctionNode(current)) {
173
+ if (current.type === 'JSXExpressionContainer') {
174
+ return true;
175
+ }
176
+ current = context.parents.get(current);
177
+ }
178
+ return false;
179
+ }
180
+
181
+ function isSoleChild(children: readonly JSXChild[], element: JSXElement): boolean {
182
+ for (const child of children) {
183
+ if (child !== element && !isInsignificant(child)) {
184
+ return false;
185
+ }
186
+ }
187
+ return true;
188
+ }
189
+
190
+ /**
191
+ * The text of each prop of an element, or `undefined` when it has a prop
192
+ * other than `names`, a spread, or a prop more than once. A repeated prop
193
+ * takes its last value, and a spread could hold any prop, such as `keyed`.
194
+ */
195
+ function propsOf(
196
+ context: PassContext,
197
+ element: JSXElement,
198
+ names: readonly string[],
199
+ ): Map<string, string> | undefined {
200
+ const props = new Map<string, string>();
201
+ for (const attribute of element.openingElement.attributes) {
202
+ if (
203
+ attribute.type !== 'JSXAttribute' ||
204
+ attribute.name.type !== 'JSXIdentifier' ||
205
+ !names.includes(attribute.name.name) ||
206
+ props.has(attribute.name.name)
207
+ ) {
208
+ return undefined;
209
+ }
210
+ const text = expressionText(context, attribute);
211
+ if (text === undefined) {
212
+ return undefined;
213
+ }
214
+ props.set(attribute.name.name, text);
215
+ }
216
+ return props;
217
+ }
218
+
219
+ interface Branch {
220
+ readonly when: string;
221
+ readonly children: string;
222
+ readonly fallback: string | undefined;
223
+ }
224
+
225
+ /**
226
+ * The condition and children of a `<Show>` or `<Match>`, or `undefined` when
227
+ * the children could need the narrowed value.
228
+ */
229
+ function branchOf(
230
+ context: PassContext,
231
+ element: JSXElement,
232
+ names: readonly string[],
233
+ ): Branch | undefined {
234
+ const props = propsOf(context, element, names);
235
+ const when = props?.get('when');
236
+ if (props === undefined || when === undefined) {
237
+ return undefined;
238
+ }
239
+ const significant = significantChildren(element.children);
240
+ const sole = significant.length === 1 ? significant[0] : undefined;
241
+
242
+ // A callback child becomes its body, with the narrowed value read as `when`.
243
+ const callback =
244
+ sole?.type === 'JSXExpressionContainer' && sole.expression.type !== 'JSXEmptyExpression'
245
+ ? unwrap(sole.expression)
246
+ : undefined;
247
+ if (callback?.type === 'ArrowFunctionExpression') {
248
+ const body = callbackBody(context, element, callback);
249
+ return body === undefined
250
+ ? undefined
251
+ : { when, children: body, fallback: props.get('fallback') };
252
+ }
253
+
254
+ // Any other function child also receives the narrowed value. A sole child
255
+ // that could hold a function, like `{render}`, counts too. Several
256
+ // children are an array, which is rendered as it is.
257
+ if (
258
+ sole?.type === 'JSXExpressionContainer' &&
259
+ sole.expression.type !== 'JSXEmptyExpression' &&
260
+ !isNeverFunction(sole.expression)
261
+ ) {
262
+ return undefined;
263
+ }
264
+ for (const child of significant) {
265
+ if (
266
+ child.type === 'JSXExpressionContainer' &&
267
+ child.expression.type !== 'JSXEmptyExpression' &&
268
+ isFunctionNode(unwrap(child.expression))
269
+ ) {
270
+ return undefined;
271
+ }
272
+ }
273
+
274
+ // The children become one fragment, which keeps JSX's own whitespace rules for them.
275
+ const { closingElement } = element;
276
+ const inner = closingElement
277
+ ? context.s.slice(element.openingElement.end, closingElement.start)
278
+ : '';
279
+ return {
280
+ when,
281
+ children: significant.length > 0 ? `<>${inner}</>` : 'undefined',
282
+ fallback: props.get('fallback'),
283
+ };
284
+ }
285
+
286
+ /**
287
+ * The body of a callback child with each read of its parameter written as
288
+ * `when`, or `undefined` when that could change what the body renders.
289
+ */
290
+ function callbackBody(
291
+ context: PassContext,
292
+ element: JSXElement,
293
+ callback: ArrowFunctionExpression,
294
+ ): string | undefined {
295
+ // `<Show>` only passes the value to a callback that takes a parameter, and
296
+ // calls it untracked. A body that is only JSX reads nothing as it is made.
297
+ const param = callback.params.at(0);
298
+ if (
299
+ callback.async ||
300
+ callback.body.type === 'BlockStatement' ||
301
+ callback.params.length !== 1 ||
302
+ param?.type !== 'Identifier'
303
+ ) {
304
+ return undefined;
305
+ }
306
+ const body = unwrap(callback.body);
307
+ if (body.type !== 'JSXElement' && body.type !== 'JSXFragment') {
308
+ return undefined;
309
+ }
310
+ const attribute = findAttribute(element, 'when');
311
+ const value = attribute?.value;
312
+ if (
313
+ value?.type !== 'JSXExpressionContainer' ||
314
+ value.expression.type === 'JSXEmptyExpression' ||
315
+ !isPlainRead(context, value.expression)
316
+ ) {
317
+ return undefined;
318
+ }
319
+ const when = value.expression;
320
+ const whenText = `(${context.s.slice(when.start, when.end)})`;
321
+
322
+ // Each name `when` reads has to mean the same thing where the body reads the parameter.
323
+ const names: Node[] = [];
324
+ collectReferences(context, when, names);
325
+ const binding = lookup(scopeAt(context.scopes, context.parents, param), param.name);
326
+ // A write to the parameter, or a type that names it, has no copy to point at.
327
+ if (binding?.identifier !== param || binding.mutated || namesInTypes(body, param.name)) {
328
+ return undefined;
329
+ }
330
+ const edits: { start: number; end: number; text: string }[] = [];
331
+ for (const reference of binding.references) {
332
+ // A tag like `<C />` names a component, which an expression cannot replace.
333
+ if (reference.type !== 'Identifier') {
334
+ return undefined;
335
+ }
336
+ const scope = scopeAt(context.scopes, context.parents, reference);
337
+ for (const name of names) {
338
+ if (
339
+ name.type !== 'Identifier' ||
340
+ lookup(scope, name.name) !== context.scopes.references.get(name)
341
+ ) {
342
+ return undefined;
343
+ }
344
+ }
345
+ const parent = context.parents.get(reference);
346
+ if (
347
+ parent?.type === 'CallExpression' &&
348
+ parent.callee === reference &&
349
+ parent.arguments.length === 0 &&
350
+ !parent.optional
351
+ ) {
352
+ edits.push({ start: parent.start, end: parent.end, text: whenText });
353
+ } else if (parent?.type === 'Property' && parent.shorthand) {
354
+ return undefined;
355
+ } else {
356
+ edits.push({ start: reference.start, end: reference.end, text: `(() => ${whenText})` });
357
+ }
358
+ }
359
+
360
+ // Write the body with the edits, in order.
361
+ edits.sort((a, b) => a.start - b.start);
362
+ let text = '';
363
+ let at = body.start;
364
+ for (const edit of edits) {
365
+ text += context.s.slice(at, edit.start) + edit.text;
366
+ at = edit.end;
367
+ }
368
+ return text + context.s.slice(at, body.end);
369
+ }
370
+
371
+ /**
372
+ * Whether reading an expression again gives the same value, with nothing run
373
+ * between the reads: names, members, literals, and operators, and calls of
374
+ * a signal or a memo. Another call could change something or return
375
+ * something new, and `this` changes inside a `function` in the body.
376
+ */
377
+ function isPlainRead(context: PassContext, node: Node): boolean {
378
+ switch (node.type) {
379
+ case 'Identifier':
380
+ case 'Literal':
381
+ return true;
382
+ case 'ParenthesizedExpression':
383
+ case 'TSAsExpression':
384
+ case 'TSSatisfiesExpression':
385
+ case 'TSNonNullExpression':
386
+ case 'ChainExpression':
387
+ return isPlainRead(context, node.expression);
388
+ case 'MemberExpression':
389
+ return (
390
+ isPlainRead(context, node.object) && (!node.computed || isPlainRead(context, node.property))
391
+ );
392
+ case 'CallExpression':
393
+ return node.arguments.length === 0 && isAccessor(context, node.callee);
394
+ case 'UnaryExpression':
395
+ return node.operator !== 'delete' && isPlainRead(context, node.argument);
396
+ case 'BinaryExpression':
397
+ case 'LogicalExpression':
398
+ return isPlainRead(context, node.left) && isPlainRead(context, node.right);
399
+ case 'ConditionalExpression':
400
+ return (
401
+ isPlainRead(context, node.test) &&
402
+ isPlainRead(context, node.consequent) &&
403
+ isPlainRead(context, node.alternate)
404
+ );
405
+ default:
406
+ return false;
407
+ }
408
+ }
409
+
410
+ /**
411
+ * Whether a callee is the getter of a `createSignal` or a `createMemo` from
412
+ * Solid, declared with `const` and never written, which returns its current
413
+ * value without running anything else.
414
+ */
415
+ function isAccessor(context: PassContext, callee: Node): boolean {
416
+ if (callee.type !== 'Identifier') {
417
+ return false;
418
+ }
419
+ const binding = context.scopes.references.get(callee);
420
+ if (!binding || binding.mutated || binding.kind !== 'const') {
421
+ return false;
422
+ }
423
+ const { declaration } = binding;
424
+ if (declaration.type !== 'VariableDeclarator' || !declaration.init) {
425
+ return false;
426
+ }
427
+ const init = unwrap(declaration.init);
428
+ if (init.type !== 'CallExpression' || init.callee.type !== 'Identifier') {
429
+ return false;
430
+ }
431
+ const factory = context.scopes.references.get(init.callee);
432
+ const name = factory ? solidExport(factory, context.options) : undefined;
433
+ if (name === 'createMemo') {
434
+ return declaration.id === binding.identifier;
435
+ }
436
+ // The getter is the first name of `const [value, setValue] = createSignal()`.
437
+ return (
438
+ name === 'createSignal' &&
439
+ declaration.id.type === 'ArrayPattern' &&
440
+ declaration.id.elements.at(0) === binding.identifier
441
+ );
442
+ }
443
+
444
+ /** Whether a TypeScript type in `node`, like `typeof v`, names `name`. */
445
+ function namesInTypes(node: unknown, name: string): boolean {
446
+ if (typeof node !== 'object' || node === null) {
447
+ return false;
448
+ }
449
+ if (Array.isArray(node)) {
450
+ for (const item of node) {
451
+ if (namesInTypes(item, name)) {
452
+ return true;
453
+ }
454
+ }
455
+ return false;
456
+ }
457
+ const type: unknown = Reflect.get(node, 'type');
458
+ if (type === 'TSTypeQuery') {
459
+ const exprName: unknown = Reflect.get(node, 'exprName');
460
+ return (
461
+ typeof exprName === 'object' && exprName !== null && Reflect.get(exprName, 'name') === name
462
+ );
463
+ }
464
+ for (const key of Object.keys(node)) {
465
+ if (key !== 'parent' && namesInTypes(Reflect.get(node, key), name)) {
466
+ return true;
467
+ }
468
+ }
469
+ return false;
470
+ }
471
+
472
+ /** The identifiers in an expression that refer to a binding or a global. */
473
+ function collectReferences(context: PassContext, node: Node, out: Node[]): void {
474
+ if (node.type === 'Identifier' && context.scopes.references.has(node)) {
475
+ out.push(node);
476
+ }
477
+ forEachChild(node, (child) => {
478
+ collectReferences(context, child, out);
479
+ });
480
+ }
481
+
482
+ /**
483
+ * Whether an expression's value can never be a function: a literal, JSX, or
484
+ * an operator that returns a string, number, or boolean.
485
+ */
486
+ function isNeverFunction(node: Node): boolean {
487
+ switch (node.type) {
488
+ case 'Literal':
489
+ case 'TemplateLiteral':
490
+ case 'JSXElement':
491
+ case 'JSXFragment':
492
+ case 'BinaryExpression':
493
+ case 'UnaryExpression':
494
+ case 'UpdateExpression':
495
+ return true;
496
+ case 'ParenthesizedExpression':
497
+ return isNeverFunction(node.expression);
498
+ case 'ConditionalExpression':
499
+ return isNeverFunction(node.consequent) && isNeverFunction(node.alternate);
500
+ case 'LogicalExpression':
501
+ return isNeverFunction(node.left) && isNeverFunction(node.right);
502
+ default:
503
+ return false;
504
+ }
505
+ }
506
+
507
+ function significantChildren(children: readonly JSXChild[]): JSXChild[] {
508
+ const result: JSXChild[] = [];
509
+ for (const child of children) {
510
+ if (!isInsignificant(child)) {
511
+ result.push(child);
512
+ }
513
+ }
514
+ return result;
515
+ }
516
+
517
+ /**
518
+ * The text of an attribute's value as an expression, or `undefined` when the
519
+ * value is not supported.
520
+ */
521
+ function expressionText(context: PassContext, attribute: JSXAttribute): string | undefined {
522
+ const { value } = attribute;
523
+ if (value === null) {
524
+ // A bare attribute is `true`. The fold pass resolves those.
525
+ return undefined;
526
+ }
527
+ switch (value.type) {
528
+ case 'JSXExpressionContainer':
529
+ if (value.expression.type === 'JSXEmptyExpression') {
530
+ return undefined;
531
+ }
532
+ return `(${context.s.slice(value.expression.start, value.expression.end)})`;
533
+ case 'JSXElement':
534
+ case 'JSXFragment':
535
+ return context.s.slice(value.start, value.end);
536
+ default:
537
+ // A string literal can hold HTML entities, which a JS string does not decode.
538
+ return undefined;
539
+ }
540
+ }
package/src/constants.ts CHANGED
@@ -26,7 +26,11 @@ export function resolveImportedConstants(
26
26
  ): ResolvedImportedConstants {
27
27
  const result = new Map<string, Map<string, Const>>();
28
28
  for (const [source, exports] of Object.entries(constants ?? {})) {
29
- result.set(source, new Map(Object.entries(exports).map(([name, value]) => [name, { value }])));
29
+ const entries = new Map<string, Const>();
30
+ for (const [name, value] of Object.entries(exports)) {
31
+ entries.set(name, { value });
32
+ }
33
+ result.set(source, entries);
30
34
  }
31
35
  return result;
32
36
  }
@@ -67,7 +71,7 @@ export class ConstantTable {
67
71
  }
68
72
  const binding = scopes.references.get(reference);
69
73
  if (binding) {
70
- return this.constantOf(binding);
74
+ return this.getConstant(binding);
71
75
  }
72
76
  return this.globalConstant(reference.name) ?? globalValue(reference.name);
73
77
  };
@@ -141,7 +145,7 @@ export class ConstantTable {
141
145
  * A reference that runs before its declaration throws at runtime, and
142
146
  * folding turns it into the value. Minifiers make the same trade.
143
147
  */
144
- constantOf(binding: Binding): Const | undefined {
148
+ getConstant(binding: Binding): Const | undefined {
145
149
  const cached = this.constants.get(binding);
146
150
  if (cached !== undefined) {
147
151
  return cached ?? undefined;
@@ -268,7 +272,7 @@ export function constantExports(
268
272
  for (const declarator of declaration.declarations) {
269
273
  if (declarator.id.type === 'Identifier') {
270
274
  const binding = topLevel.bindings.get(declarator.id.name);
271
- add(declarator.id.name, binding ? table.constantOf(binding) : undefined);
275
+ add(declarator.id.name, binding ? table.getConstant(binding) : undefined);
272
276
  }
273
277
  }
274
278
  continue;
@@ -286,7 +290,7 @@ export function constantExports(
286
290
  add(exported, options.importedConstants.get(statement.source.value)?.get(local));
287
291
  } else {
288
292
  const binding = topLevel.bindings.get(local);
289
- add(exported, binding ? table.constantOf(binding) : undefined);
293
+ add(exported, binding ? table.getConstant(binding) : undefined);
290
294
  }
291
295
  }
292
296
  }