solid-optimizer 1.0.0-next.0 → 1.0.0-next.10

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