solid-optimizer 0.3.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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "solid-optimizer",
3
- "version": "0.3.0",
4
- "description": "Experimental compile-time optimizer for SolidJS 1.x",
3
+ "version": "1.0.0-next.0",
4
+ "description": "Experimental compile-time optimizer for SolidJS",
5
5
  "keywords": [
6
6
  "compiler",
7
7
  "jsx",
@@ -39,29 +39,28 @@
39
39
  "oxc-parser": "^0.151.0"
40
40
  },
41
41
  "devDependencies": {
42
- "@babel/core": "^7.29.7",
43
42
  "@jridgewell/trace-mapping": "^0.3.31",
44
- "@types/babel__core": "^7.20.5",
43
+ "@solidjs/compiler": "2.0.0-rc.16",
44
+ "@solidjs/vite-plugin": "3.0.0-next.50",
45
+ "@solidjs/web": "2.0.0-rc.16",
45
46
  "@types/node": "^26.6.3",
46
- "babel-preset-solid": "^1.9.15",
47
47
  "happy-dom": "^20.14.5",
48
48
  "publint": "^0.3.24",
49
- "solid-js": "^1.9.15",
49
+ "solid-js": "2.0.0-rc.16",
50
50
  "tsdown": "^0.23.0",
51
51
  "typescript": "^7.0.2",
52
52
  "vite": "^8.3.1",
53
- "vite-plugin-solid": "^2.11.14",
54
53
  "vitest": "^5.0.2"
55
54
  },
56
55
  "peerDependencies": {
57
- "vite": "^8.0.0 || ^9.0.0",
58
- "vite-plugin-solid": "^2.11.0"
56
+ "@solidjs/vite-plugin": "^3.0.0-next.46",
57
+ "vite": "^8.0.0 || ^9.0.0"
59
58
  },
60
59
  "peerDependenciesMeta": {
61
- "vite": {
60
+ "@solidjs/vite-plugin": {
62
61
  "optional": true
63
62
  },
64
- "vite-plugin-solid": {
63
+ "vite": {
65
64
  "optional": true
66
65
  }
67
66
  },
package/src/ast.ts CHANGED
@@ -1,5 +1,5 @@
1
- import type { Expression, JSXChild, Node, Program } from 'oxc-parser';
2
- import { parseSync, visitorKeys } from 'oxc-parser';
1
+ import type { Expression, JSXChild, Node, ParserOptions, Program } from 'oxc-parser';
2
+ import { parseSync, rawTransferSupported, visitorKeys } from 'oxc-parser';
3
3
 
4
4
  /**
5
5
  * Keys that only hold TypeScript types. Types never run, so no pass reads or rewrites them.
@@ -82,12 +82,20 @@ export function collectParents(program: Program): Parents {
82
82
  return parents;
83
83
  }
84
84
 
85
+ /**
86
+ * Raw transfer hands the AST over in shared memory instead of as JSON, which
87
+ * is several times faster to read. It is not in the options' type yet.
88
+ */
89
+ const RAW_TRANSFER = rawTransferSupported();
90
+
85
91
  export function parse(filename: string, code: string): Program {
86
- const result = parseSync(filename, code, {
92
+ const options: ParserOptions & { experimentalRawTransfer?: boolean } = {
87
93
  lang: languageOf(filename),
88
94
  sourceType: 'module',
89
95
  preserveParens: true,
90
- });
96
+ experimentalRawTransfer: RAW_TRANSFER,
97
+ };
98
+ const result = parseSync(filename, code, options);
91
99
  const error = result.errors.at(0);
92
100
  if (error) {
93
101
  throw new SyntaxError(`[solid-optimizer] ${filename}: ${error.codeframe ?? error.message}`);
package/src/compile.ts CHANGED
@@ -1,15 +1,17 @@
1
1
  import type { SourceMap } from '@jridgewell/remapping';
2
+ import type { Program } from 'oxc-parser';
2
3
  import remapping from '@jridgewell/remapping';
3
4
  import MagicString from 'magic-string';
5
+ import type { Parents } from './ast';
4
6
  import { collectParents, parse } from './ast';
5
7
  import type { ImportedConstants } from './constants';
6
8
  import { constantExports, namedImportSources, resolveImportedConstants } from './constants';
7
- import type { PassContext, ResolvedOptions } from './context';
9
+ import type { PassContext, ResolvedOptions, Skip } from './context';
8
10
  import { fold } from './fold';
9
11
  import { inline } from './inline';
10
12
  import { inlineMemos } from './memo';
11
- import { simplifyServer } from './server';
12
13
  import { removeProviders } from './provider';
14
+ import type { ScopeAnalysis } from './scope';
13
15
  import { analyzeScopes } from './scope';
14
16
  import type { Primitive } from './value';
15
17
 
@@ -34,19 +36,6 @@ export interface CompileOptions {
34
36
  * @default true
35
37
  */
36
38
  inline?: boolean;
37
- /**
38
- * Compile for the server: remove `createEffect` and `onMount`, and reduce
39
- * `untrack`, `batch`, `startTransition`, `createDeferred`, `getListener`,
40
- * `createMemo`, `createRenderEffect`, and `createComputed` to what they do
41
- * on the server.
42
- *
43
- * This runs once, after the other passes. The server and client build
44
- * make the same folding and inlining decisions from the same code, so the
45
- * server renders the tree the client hydrates.
46
- *
47
- * @default false
48
- */
49
- server?: boolean;
50
39
  /**
51
40
  * Remove context providers whose reads are all visible, and give each
52
41
  * read the provider's value.
@@ -65,14 +54,14 @@ export interface CompileOptions {
65
54
  * The names of Solid's built-in components. A tag only folds when it is
66
55
  * one of these, and an empty list turns control-flow folding off.
67
56
  *
68
- * @default ['For', 'Show', 'Switch', 'Match', 'Suspense', 'SuspenseList', 'Portal', 'Index', 'Dynamic', 'ErrorBoundary']
57
+ * @default ['For', 'Show', 'Switch', 'Match', 'Loading', 'Reveal', 'Portal', 'Repeat', 'Dynamic', 'Errored']
69
58
  */
70
59
  builtIns?: readonly string[];
71
60
  /**
72
61
  * The modules that export Solid's built-in components. A tag imported from
73
62
  * anywhere else is a different component.
74
63
  *
75
- * @default ['solid-js', 'solid-js/web']
64
+ * @default ['solid-js', '@solidjs/web']
76
65
  */
77
66
  moduleSources?: readonly string[];
78
67
  /**
@@ -94,6 +83,12 @@ export interface CompileOptions {
94
83
  * like a local `const`. `constantExports` reads them from a module.
95
84
  */
96
85
  importedConstants?: ImportedConstants;
86
+ /**
87
+ * Values of global names and paths that fold like constants, such as the
88
+ * `define` entries of a bundler: `{ __DEV__: false, 'import.meta.env.MODE': 'production' }`.
89
+ * A path starts at `import.meta` or at a name the module does not declare.
90
+ */
91
+ globalConstants?: Readonly<Record<string, Primitive>>;
97
92
  /**
98
93
  * The exports of imported modules that are contexts made by Solid's
99
94
  * `createContext`, keyed by the import specifier as the code writes it.
@@ -130,12 +125,24 @@ export interface CompileOptions {
130
125
  * @default true
131
126
  */
132
127
  sourceMap?: boolean;
128
+ /**
129
+ * Record what the inline, provider, and memo passes leave alone, and why.
130
+ * The result lists them in `skipped`.
131
+ *
132
+ * @default false
133
+ */
134
+ report?: boolean;
133
135
  }
134
136
 
135
137
  export interface CompileResult {
136
138
  code: string;
137
139
  /** The map from the output back to the input, or `null` when nothing changed or maps are off. */
138
140
  map: SourceMap | null;
141
+ /**
142
+ * What the last round left alone, and why, when `report` is set. The last
143
+ * round changes nothing, unless `maxPasses` stopped the rounds first.
144
+ */
145
+ skipped?: Skip[];
139
146
  }
140
147
 
141
148
  const DEFAULT_BUILT_INS = [
@@ -143,15 +150,15 @@ const DEFAULT_BUILT_INS = [
143
150
  'Show',
144
151
  'Switch',
145
152
  'Match',
146
- 'Suspense',
147
- 'SuspenseList',
153
+ 'Loading',
154
+ 'Reveal',
148
155
  'Portal',
149
- 'Index',
156
+ 'Repeat',
150
157
  'Dynamic',
151
- 'ErrorBoundary',
158
+ 'Errored',
152
159
  ];
153
160
 
154
- const DEFAULT_MODULE_SOURCES = ['solid-js', 'solid-js/web'];
161
+ const DEFAULT_MODULE_SOURCES = ['solid-js', '@solidjs/web'];
155
162
 
156
163
  function resolveOptions(options: CompileOptions): ResolvedOptions {
157
164
  return {
@@ -160,6 +167,7 @@ function resolveOptions(options: CompileOptions): ResolvedOptions {
160
167
  builtInAliases: new Map(Object.entries(options.builtInAliases ?? {})),
161
168
  constantVars: options.constantVars ?? false,
162
169
  importedConstants: resolveImportedConstants(options.importedConstants),
170
+ globalConstants: new Map(Object.entries(options.globalConstants ?? {})),
163
171
  importedContexts: new Map(
164
172
  Object.entries(options.importedContexts ?? {}).map(([source, names]) => [
165
173
  source,
@@ -178,22 +186,38 @@ interface PassResult {
178
186
  map: string | undefined;
179
187
  }
180
188
 
189
+ /** A parse of some code, which passes that change nothing can share. */
190
+ interface Parsed {
191
+ readonly code: string;
192
+ readonly program: Program;
193
+ readonly parents: Parents;
194
+ readonly scopes: ScopeAnalysis;
195
+ }
196
+
197
+ function parseCode(code: string, filename: string): Parsed {
198
+ const program = parse(filename, code);
199
+ return { code, program, parents: collectParents(program), scopes: analyzeScopes(program) };
200
+ }
201
+
181
202
  function runPass(
182
- code: string,
203
+ parsed: Parsed,
183
204
  filename: string,
184
205
  options: ResolvedOptions,
185
206
  sourceMap: boolean,
186
207
  pass: Pass,
208
+ skips: Skip[] | undefined,
187
209
  ): PassResult | undefined {
188
- const program = parse(filename, code);
210
+ const { code } = parsed;
189
211
  const context: PassContext = {
190
212
  code,
191
213
  filename,
192
214
  s: new MagicString(code),
193
- program,
194
- parents: collectParents(program),
195
- scopes: analyzeScopes(program),
215
+ program: parsed.program,
216
+ parents: parsed.parents,
217
+ // A pass adds the names it gives out, so each pass starts from the parse's own.
218
+ scopes: { ...parsed.scopes, names: new Set(parsed.scopes.names) },
196
219
  options,
220
+ skips,
197
221
  };
198
222
  if (!pass(context)) {
199
223
  return undefined;
@@ -237,11 +261,23 @@ export function compile(code: string, options: CompileOptions = {}): CompileResu
237
261
 
238
262
  const maps: string[] = [];
239
263
  let current = code;
264
+ // A pass that changes nothing leaves the code as it was, so the next pass
265
+ // reuses the parse instead of parsing the same code again.
266
+ let parsed: Parsed | undefined;
267
+ const parsedCurrent = (): Parsed => {
268
+ if (parsed?.code !== current) {
269
+ parsed = parseCode(current, filename);
270
+ }
271
+ return parsed;
272
+ };
240
273
  const maxPasses = options.maxPasses ?? 10;
274
+ let skipped: Skip[] | undefined;
241
275
  for (let round = 0; round < maxPasses; round += 1) {
242
276
  let changed = false;
277
+ // Only the last round's skips are kept. An earlier round can skip what a later one takes.
278
+ skipped = options.report === true ? [] : undefined;
243
279
  for (const pass of passes) {
244
- const result = runPass(current, filename, resolved, sourceMap, pass);
280
+ const result = runPass(parsedCurrent(), filename, resolved, sourceMap, pass, skipped);
245
281
  if (result) {
246
282
  changed = true;
247
283
  current = result.code;
@@ -255,21 +291,12 @@ export function compile(code: string, options: CompileOptions = {}): CompileResu
255
291
  }
256
292
  }
257
293
 
258
- if (options.server ?? false) {
259
- const result = runPass(current, filename, resolved, sourceMap, simplifyServer);
260
- if (result) {
261
- current = result.code;
262
- if (result.map !== undefined) {
263
- maps.push(result.map);
264
- }
265
- }
266
- }
267
-
294
+ const report = skipped ? { skipped } : {};
268
295
  if (maps.length === 0) {
269
- return { code: current, map: null };
296
+ return { code: current, map: null, ...report };
270
297
  }
271
298
  // Each map points at the output of the pass before it, so they chain from the last one.
272
- return { code: current, map: remapping(maps.reverse(), () => null) };
299
+ return { code: current, map: remapping(maps.reverse(), () => null), ...report };
273
300
  }
274
301
 
275
302
  export interface ModuleConstants {
@@ -290,11 +317,11 @@ export interface ModuleConstants {
290
317
  * Reads what a module imports and the constants it exports, so that
291
318
  * `compile` can fold them in the modules that import it.
292
319
  *
293
- * Only `filename` and `importedConstants` of the options are used.
320
+ * Only `filename`, `importedConstants`, and `globalConstants` of the options are used.
294
321
  */
295
322
  export function readModuleConstants(
296
323
  code: string,
297
- options: Pick<CompileOptions, 'filename' | 'importedConstants'> = {},
324
+ options: Pick<CompileOptions, 'filename' | 'importedConstants' | 'globalConstants'> = {},
298
325
  ): ModuleConstants {
299
326
  const program = parse(options.filename ?? 'input.jsx', code);
300
327
  return {
package/src/constants.ts CHANGED
@@ -60,16 +60,56 @@ export class ConstantTable {
60
60
  ) {
61
61
  this.lookup = (reference) => {
62
62
  if (reference.type === 'MemberExpression') {
63
- return this.namespaceMember(scopes, reference);
63
+ return this.namespaceMember(scopes, reference) ?? this.globalMember(scopes, reference);
64
64
  }
65
65
  if (!scopes.references.has(reference) || reference.type !== 'Identifier') {
66
66
  return undefined;
67
67
  }
68
68
  const binding = scopes.references.get(reference);
69
- return binding ? this.constantOf(binding) : globalValue(reference.name);
69
+ if (binding) {
70
+ return this.constantOf(binding);
71
+ }
72
+ return this.globalConstant(reference.name) ?? globalValue(reference.name);
70
73
  };
71
74
  }
72
75
 
76
+ private globalConstant(path: string): Const | undefined {
77
+ const { globalConstants } = this.options;
78
+ return globalConstants.has(path) ? { value: globalConstants.get(path) } : undefined;
79
+ }
80
+
81
+ /**
82
+ * The value of a path like `import.meta.env.MODE` or `process.env.X` that
83
+ * `globalConstants` holds. The path starts at `import.meta` or at a name
84
+ * nothing declares, and goes through plain property reads.
85
+ */
86
+ private globalMember(scopes: ScopeAnalysis, node: MemberExpression): Const | undefined {
87
+ if (this.options.globalConstants.size === 0) {
88
+ return undefined;
89
+ }
90
+ const names: string[] = [];
91
+ let current: Node = node;
92
+ while (current.type === 'MemberExpression') {
93
+ if (current.computed || current.optional || current.property.type !== 'Identifier') {
94
+ return undefined;
95
+ }
96
+ names.unshift(current.property.name);
97
+ current = current.object;
98
+ }
99
+ if (current.type === 'MetaProperty') {
100
+ names.unshift(`${current.meta.name}.${current.property.name}`);
101
+ } else if (
102
+ current.type === 'Identifier' &&
103
+ scopes.references.has(current) &&
104
+ scopes.references.get(current) === undefined
105
+ ) {
106
+ names.unshift(current.name);
107
+ } else {
108
+ return undefined;
109
+ }
110
+ return this.globalConstant(names.join('.'));
111
+ }
112
+
73
113
  /**
74
114
  * The value of `ns.NAME`, where `ns` is `import * as ns` from a module
75
115
  * whose constants are known.
package/src/context.ts CHANGED
@@ -3,6 +3,7 @@ import type { Node, Program } from 'oxc-parser';
3
3
  import type { Parents } from './ast';
4
4
  import type { ResolvedImportedConstants } from './constants';
5
5
  import type { Binding, ScopeAnalysis } from './scope';
6
+ import type { Primitive } from './value';
6
7
 
7
8
  export interface ResolvedOptions {
8
9
  /** The control-flow components a tag may resolve to. */
@@ -15,6 +16,8 @@ export interface ResolvedOptions {
15
16
  readonly constantVars: boolean;
16
17
  /** The constants imported modules export, by import specifier and export name. */
17
18
  readonly importedConstants: ResolvedImportedConstants;
19
+ /** Values of global names and paths, like `__DEV__` or `import.meta.env.MODE`. */
20
+ readonly globalConstants: ReadonlyMap<string, Primitive>;
18
21
  /** The exports of imported modules that are contexts, by import specifier. */
19
22
  readonly importedContexts: ReadonlyMap<string, ReadonlySet<string>>;
20
23
  /** Components other modules use too, by the number of modules that use them. */
@@ -62,6 +65,21 @@ export function solidExport(binding: Binding, options: ResolvedOptions): string
62
65
  return undefined;
63
66
  }
64
67
 
68
+ /** The passes that record what they leave alone. */
69
+ export type SkipPass = 'inline' | 'contexts' | 'memos';
70
+
71
+ /**
72
+ * Something a pass left alone, and why. The `compile` option `report`
73
+ * collects them.
74
+ */
75
+ export interface Skip {
76
+ readonly pass: SkipPass;
77
+ /** A short code for the reason, like `call-spread`. */
78
+ readonly reason: string;
79
+ /** The component, context, or memo it is about. */
80
+ readonly name: string;
81
+ }
82
+
65
83
  /**
66
84
  * Everything a pass needs: the parsed code and the string it edits.
67
85
  *
@@ -77,6 +95,20 @@ export interface PassContext {
77
95
  readonly parents: Parents;
78
96
  readonly scopes: ScopeAnalysis;
79
97
  readonly options: ResolvedOptions;
98
+ /** Where a pass records what it leaves alone, when the caller asked for a report. */
99
+ readonly skips: Skip[] | undefined;
100
+ }
101
+
102
+ /**
103
+ * Records that a pass left something alone, when the caller asked for a report.
104
+ */
105
+ export function recordSkip(
106
+ context: PassContext,
107
+ pass: SkipPass,
108
+ reason: string,
109
+ name: string,
110
+ ): void {
111
+ context.skips?.push({ pass, reason, name });
80
112
  }
81
113
 
82
114
  /**
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Measures a component's copy at a call site: folds it as the passes after
3
+ * inlining would, then estimates its size with `SizeEstimator`.
4
+ */
5
+ import MagicString from 'magic-string';
6
+ import { collectParents, parse } from './ast';
7
+ import type { ResolvedOptions } from './context';
8
+ import { fold } from './fold';
9
+ import { analyzeScopes } from './scope';
10
+ import { SizeEstimator } from './size';
11
+
12
+ /** The name of the function a copy is wrapped in to be folded and measured. */
13
+ const WRAPPER = '__so_size__';
14
+
15
+ export interface Copy {
16
+ /** The statements the copy hoists out of the JSX. */
17
+ readonly statements: readonly string[];
18
+ /** The JSX that replaces the call site. */
19
+ readonly root: string;
20
+ }
21
+
22
+ /**
23
+ * The size of a component's copy at one call site, once its props have
24
+ * folded. `header` declares the names the fold pass needs to know, like
25
+ * imports of Solid. `inTemplate` is whether the call site sits directly in
26
+ * an element.
27
+ */
28
+ export function copySize(
29
+ filename: string,
30
+ header: string,
31
+ copy: Copy,
32
+ inTemplate: boolean,
33
+ options: ResolvedOptions,
34
+ ): number {
35
+ let code = `${header}\nfunction ${WRAPPER}() {\n${copy.statements.join('\n')}\nreturn (${copy.root});\n}\n`;
36
+ // Constant props fold the copy's conditions, as later passes would.
37
+ for (let round = 0; round < 3; round += 1) {
38
+ const program = parse(filename, code);
39
+ const s = new MagicString(code);
40
+ const changed = fold({
41
+ code,
42
+ filename,
43
+ s,
44
+ program,
45
+ parents: collectParents(program),
46
+ scopes: analyzeScopes(program),
47
+ options,
48
+ // Only the copy is measured, so nothing it skips is reported.
49
+ skips: undefined,
50
+ });
51
+ if (!changed) {
52
+ break;
53
+ }
54
+ code = s.toString();
55
+ }
56
+ const program = parse(filename, code);
57
+ const wrapper = program.body.at(-1);
58
+ if (wrapper?.type !== 'FunctionDeclaration' || !wrapper.body) {
59
+ return Number.POSITIVE_INFINITY;
60
+ }
61
+ const estimator = new SizeEstimator(code);
62
+ let size = 0;
63
+ for (const statement of wrapper.body.body) {
64
+ if (statement.type !== 'ReturnStatement') {
65
+ size += estimator.node(statement);
66
+ continue;
67
+ }
68
+ if (statement.argument) {
69
+ size += estimator.root(statement.argument, inTemplate);
70
+ }
71
+ }
72
+ return size;
73
+ }