solid-optimizer 1.0.0-next.7 → 1.0.0-next.9

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.7",
3
+ "version": "1.0.0-next.9",
4
4
  "description": "Experimental compile-time optimizer for SolidJS",
5
5
  "keywords": [
6
6
  "compiler",
package/src/compile.ts CHANGED
@@ -15,6 +15,7 @@ import { removeProviders } from './provider';
15
15
  import { lowerConditionals } from './conditional';
16
16
  import type { ScopeAnalysis } from './scope';
17
17
  import { analyzeScopes } from './scope';
18
+ import { terminateStatements } from './terminate';
18
19
  import type { Primitive } from './value';
19
20
 
20
21
  export interface CompileOptions {
@@ -288,6 +289,21 @@ export function compile(code: string, options: CompileOptions = {}): CompileResu
288
289
  }
289
290
  return parsed;
290
291
  };
292
+ const terminated = runPass(
293
+ parsedCurrent(),
294
+ filename,
295
+ resolved,
296
+ sourceMap,
297
+ terminateStatements,
298
+ undefined,
299
+ );
300
+ if (terminated) {
301
+ current = terminated.code;
302
+ if (terminated.map !== undefined) {
303
+ maps.push(terminated.map);
304
+ }
305
+ }
306
+ const start = current;
291
307
  const maxPasses = options.maxPasses ?? 10;
292
308
  let skipped: Skip[] | undefined;
293
309
  for (let round = 0; round < maxPasses; round += 1) {
@@ -335,7 +351,7 @@ export function compile(code: string, options: CompileOptions = {}): CompileResu
335
351
  // A pass can put an element straight inside a parent that cannot hold it,
336
352
  // which Solid's JSX transform rejects. Only a changed module can have one
337
353
  // that its source did not.
338
- if (current !== code) {
354
+ if (current !== start) {
339
355
  const result = runPass(
340
356
  parsedCurrent(),
341
357
  filename,
@@ -353,6 +369,10 @@ export function compile(code: string, options: CompileOptions = {}): CompileResu
353
369
  }
354
370
 
355
371
  const report = skipped ? { skipped } : {};
372
+ // Semicolons alone are no reason to change a module.
373
+ if (current === start) {
374
+ return { code, map: null, ...report };
375
+ }
356
376
  if (maps.length === 0) {
357
377
  return { code: current, map: null, ...report };
358
378
  }
package/src/constants.ts CHANGED
@@ -202,6 +202,28 @@ export function namedImportSources(
202
202
  return [...sources];
203
203
  }
204
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
+
205
227
  /**
206
228
  * Whether the module reads one of these import bindings as a value. Scope
207
229
  * analysis skips type positions, so a binding used only in types has no
package/src/fold.ts CHANGED
@@ -18,6 +18,10 @@
18
18
  * - Statements a constant condition makes unreachable: `if`/`else` branches,
19
19
  * `while (false)` loops, and anything after a `return`, `throw`, `break`,
20
20
  * or `continue`.
21
+ * - A `const`, or a `let` nothing writes to, declared inside a function,
22
+ * that nothing references and whose initializer has no side effects. A
23
+ * component left with such a declaration has a statement, which stops it
24
+ * from inlining where a statement has no place to go.
21
25
  * - A call of an arrow function whose body is JSX, with constant arguments,
22
26
  * as an element's child. The call becomes the JSX with the arguments in
23
27
  * place of the parameters, so it joins the template around it.
@@ -49,6 +53,7 @@ import type {
49
53
  LogicalExpression,
50
54
  Node,
51
55
  Statement,
56
+ VariableDeclaration,
52
57
  WhileStatement,
53
58
  } from 'oxc-parser';
54
59
  import MagicString from 'magic-string';
@@ -354,6 +359,9 @@ class Folder {
354
359
 
355
360
  private readonly lookup: ConstantLookup;
356
361
 
362
+ /** Declarations removed before the walk, which it does not enter. */
363
+ private readonly removed = new Set<Node>();
364
+
357
365
  constructor(private readonly context: PassContext) {
358
366
  this.lookup = new ConstantTable(context.scopes, context.options).lookup;
359
367
  }
@@ -363,6 +371,9 @@ class Folder {
363
371
  // ---------------------------------------------------------------------------
364
372
 
365
373
  walk(node: Node): void {
374
+ if (this.removed.has(node)) {
375
+ return;
376
+ }
366
377
  forEachChild(node, (child) => {
367
378
  this.walk(child);
368
379
  });
@@ -1495,6 +1506,98 @@ class Folder {
1495
1506
  }
1496
1507
  }
1497
1508
 
1509
+ /**
1510
+ * Removes each declaration inside a function that nothing references. The
1511
+ * references are those of the code this pass parsed, so a binding whose last
1512
+ * read this pass folds is removed in the next round.
1513
+ */
1514
+ removeUnusedDeclarations(): void {
1515
+ for (const scope of this.context.scopes.scopes.values()) {
1516
+ if (scope === this.context.scopes.root) {
1517
+ continue;
1518
+ }
1519
+ for (const binding of scope.bindings.values()) {
1520
+ const declaration = this.unusedDeclaration(binding);
1521
+ if (declaration && !this.removed.has(declaration)) {
1522
+ this.removed.add(declaration);
1523
+ this.context.s.remove(declaration.start, declaration.end);
1524
+ this.changed = true;
1525
+ }
1526
+ }
1527
+ }
1528
+ }
1529
+
1530
+ /**
1531
+ * The declaration statement of `binding` when every binding it declares is
1532
+ * unused and every initializer can be skipped.
1533
+ */
1534
+ private unusedDeclaration(binding: Binding): VariableDeclaration | undefined {
1535
+ if (binding.declaration.type !== 'VariableDeclarator') {
1536
+ return undefined;
1537
+ }
1538
+ const statement = this.context.parents.get(binding.declaration);
1539
+ if (
1540
+ statement?.type !== 'VariableDeclaration' ||
1541
+ (statement.kind !== 'const' && statement.kind !== 'let') ||
1542
+ statement.declare
1543
+ ) {
1544
+ return undefined;
1545
+ }
1546
+
1547
+ // Only a statement in a list can go. A loop head or an export needs it.
1548
+ const container = this.context.parents.get(statement)?.type;
1549
+ if (
1550
+ container !== 'BlockStatement' &&
1551
+ container !== 'StaticBlock' &&
1552
+ container !== 'SwitchCase'
1553
+ ) {
1554
+ return undefined;
1555
+ }
1556
+
1557
+ // Every declarator has to go, or the statement stays whole.
1558
+ for (const declarator of statement.declarations) {
1559
+ if (declarator.id.type !== 'Identifier') {
1560
+ return undefined;
1561
+ }
1562
+ const declared = binding.scope.bindings.get(declarator.id.name);
1563
+ if (!declared || declared.mutated || declared.references.length > 0) {
1564
+ return undefined;
1565
+ }
1566
+ if (declarator.init && !this.isSkippableInit(declarator.init)) {
1567
+ return undefined;
1568
+ }
1569
+ }
1570
+ return statement;
1571
+ }
1572
+
1573
+ /**
1574
+ * Whether an unused initializer can be dropped: an expression with no side
1575
+ * effects, or a Solid call that only creates a value from such arguments.
1576
+ */
1577
+ private isSkippableInit(init: Expression): boolean {
1578
+ if (isSideEffectFree(init)) {
1579
+ return true;
1580
+ }
1581
+ const call = unwrap(init);
1582
+ if (call.type !== 'CallExpression' || call.callee.type !== 'Identifier') {
1583
+ return false;
1584
+ }
1585
+ const callee = this.context.scopes.references.get(call.callee);
1586
+ const identity = callee ? solidExport(callee, this.context.options) : undefined;
1587
+ if (
1588
+ identity === undefined ||
1589
+ (!PURE_CALLS.has(identity) && !(PURE_VALUE_CALLS.has(identity) && isValueArgument(call)))
1590
+ ) {
1591
+ return false;
1592
+ }
1593
+ for (const argument of call.arguments) {
1594
+ if (argument.type === 'SpreadElement' || !isSideEffectFree(argument)) {
1595
+ return false;
1596
+ }
1597
+ }
1598
+ return true;
1599
+ }
1600
+
1498
1601
  private replaceStatement(statement: Node, text: string): void {
1499
1602
  if (text === '') {
1500
1603
  this.context.s.remove(statement.start, statement.end);
@@ -1566,6 +1669,7 @@ class Folder {
1566
1669
  */
1567
1670
  export function fold(context: PassContext): boolean {
1568
1671
  const folder = new Folder(context);
1672
+ folder.removeUnusedDeclarations();
1569
1673
  folder.walk(context.program);
1570
1674
  return folder.changed;
1571
1675
  }
package/src/inline.ts CHANGED
@@ -1015,7 +1015,9 @@ class Inliner {
1015
1015
  if (view === null) {
1016
1016
  continue;
1017
1017
  }
1018
- const binding = scope.bindings.get(declarator.id.name);
1018
+ // A body with its own scope (a parameter has a default) holds the declaration.
1019
+ const body = (fn.body && this.context.scopes.scopes.get(fn.body)) ?? scope;
1020
+ const binding = body.bindings.get(declarator.id.name);
1019
1021
  if (!view || !binding || binding.mutated) {
1020
1022
  return undefined;
1021
1023
  }
@@ -2374,22 +2376,155 @@ class Inliner {
2374
2376
  : undefined;
2375
2377
  }
2376
2378
 
2379
+ /**
2380
+ * The parts of a compound component like Kobalte's
2381
+ * `const Dialog = Object.assign(DialogRoot, { Trigger: DialogTrigger })`,
2382
+ * or `undefined` when the binding is not one. `<Dialog>` is `<DialogRoot>`,
2383
+ * since `Object.assign` returns its first argument, and `<Dialog.Trigger>`
2384
+ * is `<DialogTrigger>` while nothing writes to a member of either.
2385
+ */
2386
+ private compoundTarget(
2387
+ binding: Binding,
2388
+ ): { root: Binding; parts: ReadonlyMap<string, Binding> } | undefined {
2389
+ const { declaration } = binding;
2390
+ if (
2391
+ !isCapitalized(binding.name) ||
2392
+ !isConstantDeclaration(binding, this.context.options) ||
2393
+ declaration.type !== 'VariableDeclarator' ||
2394
+ declaration.id !== binding.identifier ||
2395
+ !declaration.init
2396
+ ) {
2397
+ return undefined;
2398
+ }
2399
+ const init = unwrap(declaration.init);
2400
+ if (
2401
+ init.type !== 'CallExpression' ||
2402
+ init.optional ||
2403
+ init.arguments.length !== 2 ||
2404
+ !this.isObjectAssign(init.callee)
2405
+ ) {
2406
+ return undefined;
2407
+ }
2408
+ const [first, second] = init.arguments;
2409
+ if (first.type !== 'Identifier' || second.type !== 'ObjectExpression') {
2410
+ return undefined;
2411
+ }
2412
+ const root = this.topLevelComponent(first);
2413
+ if (!root || root === binding || this.hasMemberWrite(binding) || this.hasMemberWrite(root)) {
2414
+ return undefined;
2415
+ }
2416
+ const parts = new Map<string, Binding>();
2417
+ for (const property of second.properties) {
2418
+ if (
2419
+ property.type !== 'Property' ||
2420
+ property.kind !== 'init' ||
2421
+ property.computed ||
2422
+ property.method ||
2423
+ property.value.type !== 'Identifier'
2424
+ ) {
2425
+ return undefined;
2426
+ }
2427
+ const key = propertyKeyName(property.key);
2428
+ if (key === undefined) {
2429
+ return undefined;
2430
+ }
2431
+ // Only parts with a capitalized name can be tags. The others stay reads.
2432
+ const part = this.topLevelComponent(property.value);
2433
+ if (part) {
2434
+ parts.set(key, part);
2435
+ }
2436
+ }
2437
+ return { root, parts };
2438
+ }
2439
+
2440
+ /** Whether `callee` is the global `Object.assign`. */
2441
+ private isObjectAssign(callee: Node): boolean {
2442
+ return (
2443
+ callee.type === 'MemberExpression' &&
2444
+ !callee.computed &&
2445
+ !callee.optional &&
2446
+ callee.object.type === 'Identifier' &&
2447
+ callee.object.name === 'Object' &&
2448
+ !this.context.scopes.references.get(callee.object) &&
2449
+ callee.property.type === 'Identifier' &&
2450
+ callee.property.name === 'assign'
2451
+ );
2452
+ }
2453
+
2454
+ /** The top-level binding with a capitalized name that `reference` reads, when nothing reassigns it. */
2455
+ private topLevelComponent(reference: Node): Binding | undefined {
2456
+ const target = this.context.scopes.references.get(reference);
2457
+ return target &&
2458
+ target.scope.parent === undefined &&
2459
+ !target.mutated &&
2460
+ isCapitalized(target.name)
2461
+ ? target
2462
+ : undefined;
2463
+ }
2464
+
2465
+ /** Whether anything assigns to, updates, or deletes a member of the binding. */
2466
+ private hasMemberWrite(binding: Binding): boolean {
2467
+ for (const reference of binding.references) {
2468
+ const member = this.context.parents.get(reference);
2469
+ if (member?.type !== 'MemberExpression' || member.object !== reference) {
2470
+ continue;
2471
+ }
2472
+ const use = this.context.parents.get(member);
2473
+ if (
2474
+ (use?.type === 'AssignmentExpression' && use.left === member) ||
2475
+ use?.type === 'UpdateExpression' ||
2476
+ (use?.type === 'UnaryExpression' && use.operator === 'delete')
2477
+ ) {
2478
+ return true;
2479
+ }
2480
+ }
2481
+ return false;
2482
+ }
2483
+
2484
+ /** Whether the code reads a member of the binding, like `DialogRoot.Trigger`. */
2485
+ private hasMemberRead(binding: Binding): boolean {
2486
+ for (const reference of binding.references) {
2487
+ const member = this.context.parents.get(reference);
2488
+ if (
2489
+ (member?.type === 'MemberExpression' || member?.type === 'JSXMemberExpression') &&
2490
+ member.object === reference
2491
+ ) {
2492
+ return true;
2493
+ }
2494
+ }
2495
+ return false;
2496
+ }
2497
+
2377
2498
  /**
2378
2499
  * The statement of an alias nothing uses that `reference` is the value
2379
2500
  * of, like `const Separator = SeparatorRoot` once its tags are renamed.
2380
- * It does not keep the component, and goes away with it.
2501
+ * It does not keep the component, and goes away with it. A compound
2502
+ * component counts too, when its tags are renamed and nothing reads the
2503
+ * members `Object.assign` gave its root.
2381
2504
  */
2382
2505
  private unusedAlias(reference: Node): Node | undefined {
2383
- const declarator = this.context.parents.get(reference);
2506
+ let declarator = this.context.parents.get(reference);
2507
+ if (declarator?.type === 'Property') {
2508
+ declarator = this.context.parents.get(declarator);
2509
+ }
2510
+ if (declarator?.type === 'ObjectExpression' || declarator?.type === 'CallExpression') {
2511
+ const call =
2512
+ declarator.type === 'CallExpression' ? declarator : this.context.parents.get(declarator);
2513
+ declarator = call ? this.context.parents.get(call) : undefined;
2514
+ }
2384
2515
  if (declarator?.type !== 'VariableDeclarator' || declarator.id.type !== 'Identifier') {
2385
2516
  return undefined;
2386
2517
  }
2387
2518
  const alias = this.context.scopes.root.bindings.get(declarator.id.name);
2519
+ if (alias?.declaration !== declarator || alias.references.length > 0) {
2520
+ return undefined;
2521
+ }
2522
+ const compound = this.compoundTarget(alias);
2523
+ if (this.aliasTarget(alias) === undefined && (!compound || this.hasMemberRead(compound.root))) {
2524
+ return undefined;
2525
+ }
2388
2526
  const statement = this.context.parents.get(declarator);
2389
- return alias?.declaration === declarator &&
2390
- this.aliasTarget(alias) !== undefined &&
2391
- alias.references.length === 0 &&
2392
- statement?.type === 'VariableDeclaration' &&
2527
+ return statement?.type === 'VariableDeclaration' &&
2393
2528
  statement.declarations.length === 1 &&
2394
2529
  this.context.parents.get(statement)?.type === 'Program'
2395
2530
  ? statement
@@ -2404,23 +2539,36 @@ class Inliner {
2404
2539
  private renameAliasTags(): boolean {
2405
2540
  let renamed = false;
2406
2541
  for (const binding of this.context.scopes.root.bindings.values()) {
2407
- const target = this.aliasTarget(binding);
2542
+ const compound = this.compoundTarget(binding);
2543
+ const target = this.aliasTarget(binding) ?? compound?.root;
2408
2544
  if (!target) {
2409
2545
  continue;
2410
2546
  }
2411
2547
  for (const reference of binding.references) {
2412
2548
  const parent = this.context.parents.get(reference);
2549
+ // `<Dialog.Trigger>` is the part `Object.assign` gave the root.
2550
+ let tag: Node = reference;
2551
+ let renamedTo = target;
2552
+ if (parent?.type === 'JSXMemberExpression' && parent.object === reference) {
2553
+ const part = compound?.parts.get(parent.property.name);
2554
+ if (!part) {
2555
+ continue;
2556
+ }
2557
+ tag = parent;
2558
+ renamedTo = part;
2559
+ }
2560
+ const element = this.context.parents.get(tag);
2413
2561
  if (
2414
- (parent?.type !== 'JSXOpeningElement' && parent?.type !== 'JSXClosingElement') ||
2415
- parent.name !== reference
2562
+ (element?.type !== 'JSXOpeningElement' && element?.type !== 'JSXClosingElement') ||
2563
+ element.name !== tag
2416
2564
  ) {
2417
2565
  continue;
2418
2566
  }
2419
2567
  const scope = scopeAt(this.context.scopes, this.context.parents, reference);
2420
- if (lookup(scope, target.name) !== target) {
2568
+ if (lookup(scope, renamedTo.name) !== renamedTo) {
2421
2569
  continue;
2422
2570
  }
2423
- this.context.s.overwrite(reference.start, reference.end, target.name);
2571
+ this.context.s.overwrite(tag.start, tag.end, renamedTo.name);
2424
2572
  renamed = true;
2425
2573
  }
2426
2574
  }
@@ -2786,3 +2934,11 @@ function hasChild(children: readonly Node[], child: Node): boolean {
2786
2934
  }
2787
2935
  return false;
2788
2936
  }
2937
+
2938
+ /** The name a non-computed object key spells, like `Trigger` or `'Trigger'`. */
2939
+ function propertyKeyName(key: Node): string | undefined {
2940
+ if (key.type === 'Identifier') {
2941
+ return key.name;
2942
+ }
2943
+ return key.type === 'Literal' && typeof key.value === 'string' ? key.value : undefined;
2944
+ }
package/src/scope.ts CHANGED
@@ -14,6 +14,7 @@ import type {
14
14
  BindingPattern,
15
15
  Class,
16
16
  Directive,
17
+ FunctionBody,
17
18
  Function as FunctionNode,
18
19
  JSXElementName,
19
20
  ModuleExportName,
@@ -69,7 +70,11 @@ export interface ScopeAnalysis {
69
70
  readonly root: Scope;
70
71
  /** What each identifier reference resolves to. `undefined` means a global. */
71
72
  readonly references: Map<Node, Binding | undefined>;
72
- /** The scope each scope-creating node opens. A function body shares its function's scope. */
73
+ /**
74
+ * The scope each scope-creating node opens. A function body shares its
75
+ * function's scope, unless a parameter has a default or a computed key: then
76
+ * the body opens its own scope inside the function's, as in the spec.
77
+ */
73
78
  readonly scopes: Map<Node, Scope>;
74
79
  /** Every identifier name in the program, for generating names that collide with none. */
75
80
  readonly names: Set<string>;
@@ -123,6 +128,50 @@ export function isWithinScope(scope: Scope, ancestor: Scope): boolean {
123
128
  return false;
124
129
  }
125
130
 
131
+ /**
132
+ * Whether a parameter list holds an expression: a default value or a computed
133
+ * key, at any depth.
134
+ */
135
+ function hasParameterExpressions(params: readonly (BindingPattern | ParamPattern)[]): boolean {
136
+ for (const param of params) {
137
+ if (hasPatternExpression(param)) {
138
+ return true;
139
+ }
140
+ }
141
+ return false;
142
+ }
143
+
144
+ function hasPatternExpression(pattern: BindingPattern | ParamPattern): boolean {
145
+ switch (pattern.type) {
146
+ case 'AssignmentPattern':
147
+ return true;
148
+ case 'ObjectPattern':
149
+ for (const property of pattern.properties) {
150
+ if (property.type === 'RestElement') {
151
+ if (hasPatternExpression(property.argument)) {
152
+ return true;
153
+ }
154
+ } else if (property.computed || hasPatternExpression(property.value)) {
155
+ return true;
156
+ }
157
+ }
158
+ return false;
159
+ case 'ArrayPattern':
160
+ for (const element of pattern.elements) {
161
+ if (element && hasPatternExpression(element)) {
162
+ return true;
163
+ }
164
+ }
165
+ return false;
166
+ case 'RestElement':
167
+ return hasPatternExpression(pattern.argument);
168
+ case 'TSParameterProperty':
169
+ return hasPatternExpression(pattern.parameter);
170
+ default:
171
+ return false;
172
+ }
173
+ }
174
+
126
175
  function exportName(name: ModuleExportName): string {
127
176
  return name.type === 'Literal' ? name.value : name.name;
128
177
  }
@@ -138,6 +187,9 @@ class Analyzer {
138
187
 
139
188
  private readonly pending: PendingReference[] = [];
140
189
 
190
+ /** Function bodies with a scope split from the scope of their parameters. */
191
+ private readonly bodies = new Set<Node>();
192
+
141
193
  constructor(program: Program) {
142
194
  this.root = {
143
195
  node: program,
@@ -191,6 +243,12 @@ class Analyzer {
191
243
  while (!target.isFunction && target.parent) {
192
244
  target = target.parent;
193
245
  }
246
+ // A body `var` named like a parameter starts with the parameter's value.
247
+ // It is kept as one binding with the parameter, which the redeclaration
248
+ // below marks as mutated, so neither is folded.
249
+ if (this.bodies.has(target.node) && target.parent?.bindings.has(identifier.name)) {
250
+ target = target.parent;
251
+ }
194
252
  }
195
253
  this.names.add(identifier.name);
196
254
  const existing = target.bindings.get(identifier.name);
@@ -324,12 +382,28 @@ class Analyzer {
324
382
  this.declarePattern(param, 'param', node);
325
383
  }
326
384
  if (node.body) {
327
- this.scopes.set(node.body, this.scope);
328
- this.visitStatements(node.body.body);
385
+ this.visitBody(node.body, node.params);
329
386
  }
330
387
  });
331
388
  }
332
389
 
390
+ /**
391
+ * Visits the block body of a function. When a parameter holds an expression,
392
+ * the body gets its own scope, so the expression cannot see the body's
393
+ * declarations.
394
+ */
395
+ private visitBody(body: FunctionBody, params: ParamPattern[]): void {
396
+ if (!hasParameterExpressions(params)) {
397
+ this.scopes.set(body, this.scope);
398
+ this.visitStatements(body.body);
399
+ return;
400
+ }
401
+ this.bodies.add(body);
402
+ this.withScope(body, true, () => {
403
+ this.visitStatements(body.body);
404
+ });
405
+ }
406
+
333
407
  private visitClass(node: Class): void {
334
408
  for (const decorator of node.decorators) {
335
409
  this.visit(decorator);
@@ -423,8 +497,7 @@ class Analyzer {
423
497
  this.declarePattern(param, 'param', node);
424
498
  }
425
499
  if (node.body.type === 'BlockStatement') {
426
- this.scopes.set(node.body, this.scope);
427
- this.visitStatements(node.body.body);
500
+ this.visitBody(node.body, node.params);
428
501
  } else {
429
502
  this.visit(node.body);
430
503
  }
@@ -570,15 +643,48 @@ class Analyzer {
570
643
  this.visitJSXName(node.closingElement.name);
571
644
  }
572
645
  break;
573
- case 'TSEnumDeclaration':
574
646
  case 'TSImportEqualsDeclaration':
575
647
  this.declare(node.id, 'other', node);
576
648
  break;
577
- case 'TSModuleDeclaration':
578
- if (node.id.type === 'Identifier') {
579
- this.declare(node.id, 'other', node);
649
+ case 'TSEnumDeclaration':
650
+ this.declare(node.id, 'other', node);
651
+ // A `declare enum` is stripped with the types.
652
+ if (node.declare) {
653
+ break;
580
654
  }
655
+ // An initializer can read earlier members by name, so they shadow outer bindings.
656
+ this.withScope(node, false, () => {
657
+ for (const member of node.body.members) {
658
+ if (member.id.type === 'Identifier') {
659
+ this.declare(member.id, 'other', member);
660
+ }
661
+ }
662
+ for (const member of node.body.members) {
663
+ if (member.initializer) {
664
+ this.visit(member.initializer);
665
+ }
666
+ }
667
+ });
581
668
  break;
669
+ case 'TSModuleDeclaration': {
670
+ // `namespace A.B {}` declares `A`. `declare module "m" {}` declares nothing.
671
+ let id: Node = node.id;
672
+ while (id.type === 'TSQualifiedName') {
673
+ id = id.left;
674
+ }
675
+ if (id.type === 'Identifier') {
676
+ this.declare(id, 'other', node);
677
+ }
678
+ // A `declare namespace` or `declare module` is stripped with the types.
679
+ // The body of any other one runs, and a `var` in it stays inside.
680
+ const { body } = node;
681
+ if (!node.declare && body) {
682
+ this.withScope(node, true, () => {
683
+ this.visitStatements(body.body);
684
+ });
685
+ }
686
+ break;
687
+ }
582
688
  default:
583
689
  forEachChild(node, (child) => {
584
690
  this.visit(child);