ticbuild 1.0.20 → 1.0.21

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.
Files changed (48) hide show
  1. package/README.md +5 -1
  2. package/dist/backend/importers/LuaCodeImporter.d.ts +4 -1
  3. package/dist/backend/importers/LuaCodeImporter.d.ts.map +1 -1
  4. package/dist/backend/importers/LuaCodeImporter.js +18 -8
  5. package/dist/backend/importers/LuaCodeImporter.js.map +1 -1
  6. package/dist/buildInfo.d.ts +4 -4
  7. package/dist/buildInfo.js +4 -4
  8. package/dist/frontend/build.d.ts.map +1 -1
  9. package/dist/frontend/build.js +0 -29
  10. package/dist/frontend/build.js.map +1 -1
  11. package/dist/frontend/buildReporter.d.ts +9 -0
  12. package/dist/frontend/buildReporter.d.ts.map +1 -1
  13. package/dist/frontend/buildReporter.js +23 -1
  14. package/dist/frontend/buildReporter.js.map +1 -1
  15. package/dist/frontend/buildReporter.test.js +138 -2
  16. package/dist/frontend/buildReporter.test.js.map +1 -1
  17. package/dist/frontend/core.d.ts.map +1 -1
  18. package/dist/frontend/core.js +128 -1
  19. package/dist/frontend/core.js.map +1 -1
  20. package/dist/utils/console.d.ts +3 -0
  21. package/dist/utils/console.d.ts.map +1 -1
  22. package/dist/utils/console.js +10 -0
  23. package/dist/utils/console.js.map +1 -1
  24. package/dist/utils/lua/lua_alias_expressions.d.ts +2 -0
  25. package/dist/utils/lua/lua_alias_expressions.d.ts.map +1 -1
  26. package/dist/utils/lua/lua_alias_expressions.js +29 -94
  27. package/dist/utils/lua/lua_alias_expressions.js.map +1 -1
  28. package/dist/utils/lua/lua_alias_expressions.test.d.ts +2 -0
  29. package/dist/utils/lua/lua_alias_expressions.test.d.ts.map +1 -0
  30. package/dist/utils/lua/lua_alias_expressions.test.js +212 -0
  31. package/dist/utils/lua/lua_alias_expressions.test.js.map +1 -0
  32. package/dist/utils/lua/lua_alias_literals.d.ts +2 -0
  33. package/dist/utils/lua/lua_alias_literals.d.ts.map +1 -1
  34. package/dist/utils/lua/lua_alias_literals.js +12 -79
  35. package/dist/utils/lua/lua_alias_literals.js.map +1 -1
  36. package/dist/utils/lua/lua_alias_shared.d.ts +49 -14
  37. package/dist/utils/lua/lua_alias_shared.d.ts.map +1 -1
  38. package/dist/utils/lua/lua_alias_shared.js +661 -184
  39. package/dist/utils/lua/lua_alias_shared.js.map +1 -1
  40. package/dist/utils/lua/lua_local_budget.test.d.ts +2 -0
  41. package/dist/utils/lua/lua_local_budget.test.d.ts.map +1 -0
  42. package/dist/utils/lua/lua_local_budget.test.js +167 -0
  43. package/dist/utils/lua/lua_local_budget.test.js.map +1 -0
  44. package/dist/utils/lua/lua_processor.d.ts +6 -0
  45. package/dist/utils/lua/lua_processor.d.ts.map +1 -1
  46. package/dist/utils/lua/lua_processor.js +18 -9
  47. package/dist/utils/lua/lua_processor.js.map +1 -1
  48. package/package.json +1 -1
@@ -1,11 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.AliasTracker = void 0;
3
+ exports.LUA_MAX_ACTIVE_LOCALS = exports.AliasTracker = void 0;
4
4
  exports.generateAliasName = generateAliasName;
5
5
  exports.cloneExpression = cloneExpression;
6
- exports.buildScopeHierarchy = buildScopeHierarchy;
7
6
  exports.findCommonAncestor = findCommonAncestor;
8
7
  exports.insertDeclarationsIntoScopes = insertDeclarationsIntoScopes;
8
+ exports.createEmptyAliasPassReport = createEmptyAliasPassReport;
9
+ exports.runAliasPasses = runAliasPasses;
9
10
  exports.runAliasPass = runAliasPass;
10
11
  const lua_ast_1 = require("./lua_ast");
11
12
  // ============================================================================
@@ -72,59 +73,60 @@ function cloneExpression(node) {
72
73
  }
73
74
  return baseClone;
74
75
  }
76
+ class LexicalBindingScope {
77
+ constructor(parent = null) {
78
+ this.parent = parent;
79
+ this.localNames = new Set();
80
+ }
81
+ createChild() {
82
+ return new LexicalBindingScope(this);
83
+ }
84
+ define(name) {
85
+ if (name)
86
+ this.localNames.add(name);
87
+ }
88
+ isShadowed(name) {
89
+ return this.localNames.has(name) || (this.parent?.isShadowed(name) ?? false);
90
+ }
91
+ }
75
92
  // Tracker for aliasable items
76
93
  class AliasTracker {
77
- constructor(prefix = "_") {
94
+ constructor(strategy, nextOrder) {
95
+ this.strategy = strategy;
96
+ this.nextOrder = nextOrder;
78
97
  this.items = new Map();
79
- this.aliasCounter = 0;
80
- this.prefix = prefix;
81
98
  }
82
99
  // Record an occurrence of an item in a given scope
83
100
  record(key, node, scope) {
84
101
  const existing = this.items.get(key);
85
102
  if (existing) {
86
103
  existing.count++;
104
+ existing.occurrences.push(node);
87
105
  if (!existing.scopes.includes(scope)) {
88
106
  existing.scopes.push(scope);
89
107
  }
108
+ return existing;
90
109
  }
91
110
  else {
92
- this.items.set(key, {
111
+ const info = {
93
112
  serialized: key,
94
113
  node: cloneExpression(node),
95
114
  count: 1,
96
115
  scopes: [scope],
97
- });
116
+ occurrences: [node],
117
+ order: this.nextOrder(),
118
+ strategy: this.strategy,
119
+ conflicts: new Set(),
120
+ };
121
+ this.items.set(key, info);
122
+ return info;
98
123
  }
99
124
  }
100
- // Get items that should be aliased based on a predicate
101
- getAliasableItems(predicate) {
102
- const result = [];
103
- for (const info of this.items.values()) {
104
- if (predicate(info)) {
105
- let aliasName;
106
- do {
107
- aliasName = generateAliasName(this.aliasCounter++, this.prefix);
108
- } while (lua_ast_1.LUA_RESERVED_WORDS.has(aliasName));
109
- info.aliasName = aliasName;
110
- result.push(info);
111
- }
112
- }
113
- return result;
114
- }
115
- // Look up an alias for an item by key
116
- getAlias(key) {
117
- const info = this.items.get(key);
118
- return info?.aliasName || null;
125
+ getItems() {
126
+ return Array.from(this.items.values());
119
127
  }
120
128
  }
121
129
  exports.AliasTracker = AliasTracker;
122
- // Build scope hierarchy map
123
- function buildScopeHierarchy(ast, processStatements) {
124
- const scopeParents = new WeakMap();
125
- processStatements(ast.body, ast, null, scopeParents);
126
- return scopeParents;
127
- }
128
130
  // Find common ancestor scope for multiple scopes
129
131
  function findCommonAncestor(scopes, scopeParents, rootScope) {
130
132
  if (scopes.length === 0)
@@ -182,12 +184,8 @@ function findCommonAncestor(scopes, scopeParents, rootScope) {
182
184
  return rootScope;
183
185
  }
184
186
  // Insert declarations into scopes
185
- function insertDeclarationsIntoScopes(ast, declarationsByScope) {
186
- // Helper to insert declarations at the beginning of a scope
187
- function insertDeclarations(scope) {
188
- const declarations = declarationsByScope.get(scope);
189
- if (!declarations || declarations.length === 0)
190
- return;
187
+ function insertDeclarationsIntoScopes(declarationsByScope, generatedDeclarations) {
188
+ declarationsByScope.forEach((declarations, scope) => {
191
189
  const aliasDeclarations = declarations.map((info) => ({
192
190
  type: "LocalStatement",
193
191
  variables: [
@@ -198,218 +196,697 @@ function insertDeclarationsIntoScopes(ast, declarationsByScope) {
198
196
  ],
199
197
  init: [info.node],
200
198
  }));
201
- let body;
202
- if (scope === ast) {
203
- body = ast.body;
204
- }
205
- else if (scope.body) {
206
- body = scope.body;
199
+ aliasDeclarations.forEach((declaration) => generatedDeclarations?.add(declaration));
200
+ scope.body.unshift(...aliasDeclarations);
201
+ });
202
+ }
203
+ exports.LUA_MAX_ACTIVE_LOCALS = 200;
204
+ function analyzeLocalPressure(ast, generatedDeclarations = new WeakSet()) {
205
+ const scopeByNode = new WeakMap();
206
+ const functions = [];
207
+ const functionByRoot = new Map();
208
+ const analyzedFunctions = new WeakSet();
209
+ function createScope(scope, functionRoot, parent) {
210
+ const pressureScope = {
211
+ scope,
212
+ functionRoot,
213
+ parent,
214
+ children: [],
215
+ directPeak: 0,
216
+ candidates: [],
217
+ };
218
+ parent?.children.push(pressureScope);
219
+ scopeByNode.set(scope, pressureScope);
220
+ return pressureScope;
221
+ }
222
+ function recordPoint(scope, counts) {
223
+ const total = counts.existing + counts.generated;
224
+ scope.directPeak = Math.max(scope.directPeak, total);
225
+ const fn = functionByRoot.get(scope.functionRoot);
226
+ if (total > fn.peakActiveLocals ||
227
+ (total === fn.peakActiveLocals && counts.generated > fn.generatedLocalsAtPeak)) {
228
+ fn.peakActiveLocals = total;
229
+ fn.existingLocalsAtPeak = counts.existing;
230
+ fn.generatedLocalsAtPeak = counts.generated;
207
231
  }
208
- else {
209
- return;
232
+ }
233
+ function analyzeExpression(node) {
234
+ switch (node.type) {
235
+ case "BinaryExpression":
236
+ case "LogicalExpression":
237
+ analyzeExpression(node.left);
238
+ analyzeExpression(node.right);
239
+ return;
240
+ case "UnaryExpression":
241
+ analyzeExpression(node.argument);
242
+ return;
243
+ case "CallExpression":
244
+ analyzeExpression(node.base);
245
+ node.arguments.forEach(analyzeExpression);
246
+ return;
247
+ case "TableCallExpression":
248
+ analyzeExpression(node.base);
249
+ analyzeExpression(node.arguments);
250
+ return;
251
+ case "StringCallExpression":
252
+ analyzeExpression(node.base);
253
+ analyzeExpression(node.argument);
254
+ return;
255
+ case "MemberExpression":
256
+ analyzeExpression(node.base);
257
+ return;
258
+ case "IndexExpression":
259
+ analyzeExpression(node.base);
260
+ analyzeExpression(node.index);
261
+ return;
262
+ case "TableConstructorExpression":
263
+ node.fields.forEach((field) => {
264
+ if (field.type === "TableKey")
265
+ analyzeExpression(field.key);
266
+ analyzeExpression(field.value);
267
+ });
268
+ return;
269
+ case "FunctionDeclaration":
270
+ analyzeFunction(node);
271
+ return;
272
+ default:
273
+ return;
210
274
  }
211
- body.unshift(...aliasDeclarations);
212
275
  }
213
- // Process statements recursively to insert into nested scopes
214
- function processStatementsForInsertion(stmts) {
215
- stmts.forEach((stmt) => {
276
+ function analyzeStatements(statements, scope, entryCounts) {
277
+ const counts = { ...entryCounts };
278
+ recordPoint(scope, counts);
279
+ for (const stmt of statements) {
216
280
  switch (stmt.type) {
281
+ case "LocalStatement": {
282
+ const generated = generatedDeclarations.has(stmt);
283
+ const declarationCount = stmt.variables.length;
284
+ const declarationCounts = {
285
+ existing: counts.existing + (generated ? 0 : declarationCount),
286
+ generated: counts.generated + (generated ? declarationCount : 0),
287
+ };
288
+ // Lua registers every name before compiling the initializer, so the
289
+ // declaration itself must fit even though its bindings are not visible yet.
290
+ recordPoint(scope, declarationCounts);
291
+ counts.existing = declarationCounts.existing;
292
+ counts.generated = declarationCounts.generated;
293
+ stmt.init.forEach(analyzeExpression);
294
+ break;
295
+ }
296
+ case "AssignmentStatement":
297
+ stmt.variables.forEach(analyzeExpression);
298
+ stmt.init.forEach(analyzeExpression);
299
+ break;
300
+ case "CallStatement":
301
+ analyzeExpression(stmt.expression);
302
+ break;
303
+ case "ReturnStatement":
304
+ stmt.arguments.forEach(analyzeExpression);
305
+ break;
217
306
  case "IfStatement":
218
307
  stmt.clauses.forEach((clause) => {
219
- insertDeclarations(clause);
220
- processStatementsForInsertion(clause.body);
308
+ if (clause.type !== "ElseClause")
309
+ analyzeExpression(clause.condition);
310
+ const child = createScope(clause, scope.functionRoot, scope);
311
+ analyzeStatements(clause.body, child, counts);
312
+ });
313
+ break;
314
+ case "WhileStatement": {
315
+ analyzeExpression(stmt.condition);
316
+ const child = createScope(stmt, scope.functionRoot, scope);
317
+ analyzeStatements(stmt.body, child, counts);
318
+ break;
319
+ }
320
+ case "RepeatStatement": {
321
+ const child = createScope(stmt, scope.functionRoot, scope);
322
+ const repeatCounts = analyzeStatements(stmt.body, child, counts);
323
+ analyzeExpression(stmt.condition);
324
+ recordPoint(child, repeatCounts);
325
+ break;
326
+ }
327
+ case "ForNumericStatement": {
328
+ stmt.start && analyzeExpression(stmt.start);
329
+ stmt.end && analyzeExpression(stmt.end);
330
+ if (stmt.step)
331
+ analyzeExpression(stmt.step);
332
+ const child = createScope(stmt, scope.functionRoot, scope);
333
+ analyzeStatements(stmt.body, child, { existing: counts.existing + 4, generated: counts.generated });
334
+ break;
335
+ }
336
+ case "ForGenericStatement": {
337
+ stmt.iterators.forEach(analyzeExpression);
338
+ const child = createScope(stmt, scope.functionRoot, scope);
339
+ analyzeStatements(stmt.body, child, {
340
+ existing: counts.existing + 3 + stmt.variables.length,
341
+ generated: counts.generated,
221
342
  });
222
343
  break;
223
- case "WhileStatement":
224
- case "RepeatStatement":
225
- case "ForNumericStatement":
226
- case "ForGenericStatement":
344
+ }
227
345
  case "FunctionDeclaration":
228
- case "DoStatement":
229
- insertDeclarations(stmt);
230
- processStatementsForInsertion(stmt.body);
346
+ if (stmt.isLocal && (0, lua_ast_1.isIdentifier)(stmt.identifier)) {
347
+ counts.existing++;
348
+ recordPoint(scope, counts);
349
+ }
350
+ analyzeFunction(stmt);
351
+ break;
352
+ case "DoStatement": {
353
+ const child = createScope(stmt, scope.functionRoot, scope);
354
+ analyzeStatements(stmt.body, child, counts);
355
+ break;
356
+ }
357
+ default:
231
358
  break;
232
359
  }
360
+ }
361
+ return counts;
362
+ }
363
+ function analyzeFunction(root) {
364
+ if (analyzedFunctions.has(root))
365
+ return;
366
+ analyzedFunctions.add(root);
367
+ let parameterCount = 0;
368
+ if (root.type === "FunctionDeclaration") {
369
+ parameterCount = root.parameters.filter(lua_ast_1.isIdentifier).length;
370
+ if (root.identifier?.type === "MemberExpression" && root.identifier.indexer === ":") {
371
+ parameterCount++;
372
+ }
373
+ }
374
+ const rootScope = createScope(root, root, null);
375
+ const fn = {
376
+ root,
377
+ rootScope,
378
+ peakActiveLocals: parameterCount,
379
+ existingLocalsAtPeak: parameterCount,
380
+ generatedLocalsAtPeak: 0,
381
+ };
382
+ functions.push(fn);
383
+ functionByRoot.set(root, fn);
384
+ analyzeStatements(root.body, rootScope, { existing: parameterCount, generated: 0 });
385
+ }
386
+ analyzeFunction(ast);
387
+ return { scopeByNode, functions, functionByRoot };
388
+ }
389
+ function allocateCandidates(root) {
390
+ const memo = new WeakMap();
391
+ const impossible = Number.NEGATIVE_INFINITY;
392
+ function solve(scope, inheritedAliases) {
393
+ let scopeMemo = memo.get(scope);
394
+ if (!scopeMemo) {
395
+ scopeMemo = new Map();
396
+ memo.set(scope, scopeMemo);
397
+ }
398
+ const cached = scopeMemo.get(inheritedAliases);
399
+ if (cached)
400
+ return cached;
401
+ if (inheritedAliases > 0 && scope.directPeak + inheritedAliases > exports.LUA_MAX_ACTIVE_LOCALS) {
402
+ const result = { value: impossible, selectedHere: 0 };
403
+ scopeMemo.set(inheritedAliases, result);
404
+ return result;
405
+ }
406
+ scope.candidates.sort((a, b) => (b.estimatedSavings ?? 0) - (a.estimatedSavings ?? 0) || a.order - b.order);
407
+ const prefixSavings = [0];
408
+ scope.candidates.forEach((candidate) => {
409
+ prefixSavings.push(prefixSavings[prefixSavings.length - 1] + (candidate.estimatedSavings ?? 0));
233
410
  });
411
+ const availableHere = Math.max(0, exports.LUA_MAX_ACTIVE_LOCALS - scope.directPeak - inheritedAliases);
412
+ const maxHere = Math.min(scope.candidates.length, availableHere);
413
+ let best = { value: impossible, selectedHere: 0 };
414
+ for (let selectedHere = 0; selectedHere <= maxHere; selectedHere++) {
415
+ const childInherited = inheritedAliases + selectedHere;
416
+ let value = prefixSavings[selectedHere];
417
+ let valid = true;
418
+ for (const child of scope.children) {
419
+ const childResult = solve(child, childInherited);
420
+ if (childResult.value === impossible) {
421
+ valid = false;
422
+ break;
423
+ }
424
+ value += childResult.value;
425
+ }
426
+ if (valid && value > best.value) {
427
+ best = { value, selectedHere };
428
+ }
429
+ }
430
+ scopeMemo.set(inheritedAliases, best);
431
+ return best;
432
+ }
433
+ const selected = new Set();
434
+ solve(root, 0);
435
+ function collect(scope, inheritedAliases) {
436
+ const decision = memo.get(scope).get(inheritedAliases);
437
+ scope.candidates.slice(0, decision.selectedHere).forEach((candidate) => selected.add(candidate));
438
+ const childInherited = inheritedAliases + decision.selectedHere;
439
+ scope.children.forEach((child) => collect(child, childInherited));
234
440
  }
235
- insertDeclarations(ast);
236
- processStatementsForInsertion(ast.body);
441
+ collect(root, 0);
442
+ return selected;
237
443
  }
238
- function runAliasPass(ast, strategy) {
239
- const tracker = new AliasTracker(strategy.prefix);
240
- function countExpr(node, currentScope) {
444
+ function functionName(root) {
445
+ if (root.type === "Chunk")
446
+ return "<main chunk>";
447
+ if (!root.identifier)
448
+ return "<anonymous>";
449
+ function expressionName(node) {
450
+ if (node.type === "Identifier")
451
+ return node.name;
452
+ if (node.type === "MemberExpression") {
453
+ const base = expressionName(node.base);
454
+ return base ? `${base}${node.indexer}${node.identifier.name}` : node.identifier.name;
455
+ }
456
+ return null;
457
+ }
458
+ return expressionName(root.identifier) ?? "<anonymous>";
459
+ }
460
+ function emptyRuleReport() {
461
+ return { accepted: 0, omitted: 0, estimatedBytesSaved: 0, estimatedBytesOmitted: 0 };
462
+ }
463
+ function createEmptyAliasPassReport() {
464
+ return { localLimit: exports.LUA_MAX_ACTIVE_LOCALS, constrainedFunctions: [] };
465
+ }
466
+ function runAliasPasses(ast, strategies) {
467
+ if (strategies.length === 0)
468
+ return { ast, report: createEmptyAliasPassReport() };
469
+ const unavailableNames = new Set();
470
+ (0, lua_ast_1.walkAST)(ast, (node) => {
471
+ if ((0, lua_ast_1.isIdentifier)(node))
472
+ unavailableNames.add(node.name);
473
+ });
474
+ let nextCandidateOrder = 0;
475
+ const strategyStates = strategies.map((strategy) => ({
476
+ strategy,
477
+ tracker: new AliasTracker(strategy, () => nextCandidateOrder++),
478
+ }));
479
+ const candidatesByNode = new WeakMap();
480
+ const scopeParents = new WeakMap();
481
+ function registerScope(scope, parentScope) {
482
+ scopeParents.set(scope, parentScope);
483
+ }
484
+ function countExpression(node, currentScope, bindings, ancestors = []) {
241
485
  if (!node)
242
486
  return;
243
- const key = strategy.serialize(node);
244
- if (key)
245
- tracker.record(key, node, currentScope);
487
+ const currentCandidates = [];
488
+ strategyStates.forEach(({ strategy, tracker }) => {
489
+ const key = strategy.serialize(node, bindings);
490
+ if (!key)
491
+ return;
492
+ const info = tracker.record(key, node, currentScope);
493
+ currentCandidates.push(info);
494
+ ancestors.forEach((ancestor) => {
495
+ if (ancestor === info)
496
+ return;
497
+ ancestor.conflicts.add(info);
498
+ info.conflicts.add(ancestor);
499
+ });
500
+ });
501
+ if (currentCandidates.length > 0)
502
+ candidatesByNode.set(node, currentCandidates);
503
+ const childAncestors = currentCandidates.length > 0 ? [...ancestors, ...currentCandidates] : ancestors;
246
504
  switch (node.type) {
247
505
  case "BinaryExpression":
248
506
  case "LogicalExpression":
249
- countExpr(node.left, currentScope);
250
- countExpr(node.right, currentScope);
251
- break;
507
+ countExpression(node.left, currentScope, bindings, childAncestors);
508
+ countExpression(node.right, currentScope, bindings, childAncestors);
509
+ return;
252
510
  case "UnaryExpression":
253
- countExpr(node.argument, currentScope);
254
- break;
511
+ countExpression(node.argument, currentScope, bindings, childAncestors);
512
+ return;
255
513
  case "CallExpression":
256
- countExpr(node.base, currentScope);
257
- if (node.arguments)
258
- node.arguments.forEach((arg) => countExpr(arg, currentScope));
259
- break;
514
+ countExpression(node.base, currentScope, bindings, childAncestors);
515
+ node.arguments.forEach((arg) => countExpression(arg, currentScope, bindings, childAncestors));
516
+ return;
260
517
  case "TableCallExpression":
261
- countExpr(node.base, currentScope);
262
- countExpr(node.arguments, currentScope);
263
- break;
518
+ countExpression(node.base, currentScope, bindings, childAncestors);
519
+ countExpression(node.arguments, currentScope, bindings, childAncestors);
520
+ return;
264
521
  case "StringCallExpression":
265
- countExpr(node.base, currentScope);
266
- break;
522
+ countExpression(node.base, currentScope, bindings, childAncestors);
523
+ return;
267
524
  case "MemberExpression":
268
- countExpr(node.base, currentScope);
269
- break;
525
+ countExpression(node.base, currentScope, bindings, childAncestors);
526
+ return;
270
527
  case "IndexExpression":
271
- countExpr(node.base, currentScope);
272
- countExpr(node.index, currentScope);
273
- break;
528
+ countExpression(node.base, currentScope, bindings, childAncestors);
529
+ countExpression(node.index, currentScope, bindings, childAncestors);
530
+ return;
274
531
  case "TableConstructorExpression":
275
- if (node.fields) {
276
- node.fields.forEach((field) => {
277
- if (field.type === "TableKey") {
278
- if (field.key)
279
- countExpr(field.key, currentScope);
280
- }
281
- if (field.value)
282
- countExpr(field.value, currentScope);
283
- });
284
- }
285
- break;
532
+ node.fields.forEach((field) => {
533
+ if (field.type === "TableKey")
534
+ countExpression(field.key, currentScope, bindings, childAncestors);
535
+ countExpression(field.value, currentScope, bindings, childAncestors);
536
+ });
537
+ return;
538
+ case "FunctionDeclaration": {
539
+ registerScope(node, currentScope);
540
+ const functionBindings = bindings.createChild();
541
+ node.parameters.forEach((parameter) => {
542
+ if ((0, lua_ast_1.isIdentifier)(parameter))
543
+ functionBindings.define(parameter.name);
544
+ });
545
+ countBlock(node.body, node, functionBindings);
546
+ return;
547
+ }
548
+ default:
549
+ return;
286
550
  }
287
551
  }
288
- function processScope(stmts, currentScope, parentScope, scopeParents) {
289
- if (parentScope)
290
- scopeParents.set(currentScope, parentScope);
291
- stmts.forEach((stmt) => countInStatement(stmt, currentScope, scopeParents));
552
+ function countAssignmentTarget(node, currentScope, bindings) {
553
+ switch (node.type) {
554
+ case "MemberExpression":
555
+ countExpression(node.base, currentScope, bindings);
556
+ return;
557
+ case "IndexExpression":
558
+ countExpression(node.base, currentScope, bindings);
559
+ countExpression(node.index, currentScope, bindings);
560
+ return;
561
+ default:
562
+ return;
563
+ }
292
564
  }
293
- function countInStatement(stmt, currentScope, scopeParents) {
294
- if (!stmt)
295
- return;
565
+ function countBlock(statements, currentScope, bindings) {
566
+ statements.forEach((statement) => countStatement(statement, currentScope, bindings));
567
+ }
568
+ function countStatement(stmt, currentScope, bindings) {
296
569
  switch (stmt.type) {
297
570
  case "LocalStatement":
298
- if (stmt.init)
299
- stmt.init.forEach((expr) => countExpr(expr, currentScope));
300
- break;
571
+ stmt.init.forEach((expression) => countExpression(expression, currentScope, bindings));
572
+ stmt.variables.forEach((variable) => bindings.define(variable.name));
573
+ return;
301
574
  case "AssignmentStatement":
302
- stmt.variables.forEach((v) => countExpr(v, currentScope));
303
- stmt.init.forEach((expr) => countExpr(expr, currentScope));
304
- break;
575
+ stmt.variables.forEach((variable) => countAssignmentTarget(variable, currentScope, bindings));
576
+ stmt.init.forEach((expression) => countExpression(expression, currentScope, bindings));
577
+ return;
305
578
  case "CallStatement":
306
- countExpr(stmt.expression, currentScope);
307
- break;
579
+ countExpression(stmt.expression, currentScope, bindings);
580
+ return;
308
581
  case "ReturnStatement":
309
- stmt.arguments.forEach((arg) => countExpr(arg, currentScope));
310
- break;
582
+ stmt.arguments.forEach((argument) => countExpression(argument, currentScope, bindings));
583
+ return;
311
584
  case "IfStatement":
312
585
  stmt.clauses.forEach((clause) => {
313
- if (clause.type !== "ElseClause" && clause.condition)
314
- countExpr(clause.condition, currentScope);
315
- processScope(clause.body, stmt, currentScope, scopeParents);
586
+ if (clause.type !== "ElseClause")
587
+ countExpression(clause.condition, currentScope, bindings);
588
+ registerScope(clause, currentScope);
589
+ countBlock(clause.body, clause, bindings.createChild());
316
590
  });
317
- break;
591
+ return;
318
592
  case "WhileStatement":
319
- countExpr(stmt.condition, currentScope);
320
- processScope(stmt.body, stmt, currentScope, scopeParents);
321
- break;
322
- case "RepeatStatement":
323
- processScope(stmt.body, stmt, currentScope, scopeParents);
324
- countExpr(stmt.condition, currentScope);
325
- break;
326
- case "ForNumericStatement":
327
- countExpr(stmt.start, currentScope);
328
- countExpr(stmt.end, currentScope);
593
+ countExpression(stmt.condition, currentScope, bindings);
594
+ registerScope(stmt, currentScope);
595
+ countBlock(stmt.body, stmt, bindings.createChild());
596
+ return;
597
+ case "RepeatStatement": {
598
+ registerScope(stmt, currentScope);
599
+ const repeatBindings = bindings.createChild();
600
+ countBlock(stmt.body, stmt, repeatBindings);
601
+ countExpression(stmt.condition, stmt, repeatBindings);
602
+ return;
603
+ }
604
+ case "ForNumericStatement": {
605
+ countExpression(stmt.start, currentScope, bindings);
606
+ countExpression(stmt.end, currentScope, bindings);
329
607
  if (stmt.step)
330
- countExpr(stmt.step, currentScope);
331
- processScope(stmt.body, stmt, currentScope, scopeParents);
332
- break;
333
- case "ForGenericStatement":
334
- stmt.iterators.forEach((it) => countExpr(it, currentScope));
335
- processScope(stmt.body, stmt, currentScope, scopeParents);
336
- break;
337
- case "FunctionDeclaration":
338
- processScope(stmt.body, stmt, currentScope, scopeParents);
339
- break;
608
+ countExpression(stmt.step, currentScope, bindings);
609
+ registerScope(stmt, currentScope);
610
+ const forBindings = bindings.createChild();
611
+ forBindings.define(stmt.variable.name);
612
+ countBlock(stmt.body, stmt, forBindings);
613
+ return;
614
+ }
615
+ case "ForGenericStatement": {
616
+ stmt.iterators.forEach((iterator) => countExpression(iterator, currentScope, bindings));
617
+ registerScope(stmt, currentScope);
618
+ const forBindings = bindings.createChild();
619
+ stmt.variables.forEach((variable) => forBindings.define(variable.name));
620
+ countBlock(stmt.body, stmt, forBindings);
621
+ return;
622
+ }
623
+ case "FunctionDeclaration": {
624
+ if (stmt.isLocal && (0, lua_ast_1.isIdentifier)(stmt.identifier)) {
625
+ bindings.define(stmt.identifier.name);
626
+ }
627
+ else if (stmt.identifier) {
628
+ countAssignmentTarget(stmt.identifier, currentScope, bindings);
629
+ }
630
+ registerScope(stmt, currentScope);
631
+ const functionBindings = bindings.createChild();
632
+ stmt.parameters.forEach((parameter) => {
633
+ if ((0, lua_ast_1.isIdentifier)(parameter))
634
+ functionBindings.define(parameter.name);
635
+ });
636
+ countBlock(stmt.body, stmt, functionBindings);
637
+ return;
638
+ }
340
639
  case "DoStatement":
341
- processScope(stmt.body, stmt, currentScope, scopeParents);
342
- break;
640
+ registerScope(stmt, currentScope);
641
+ countBlock(stmt.body, stmt, bindings.createChild());
642
+ return;
643
+ default:
644
+ return;
343
645
  }
344
646
  }
345
- const scopeParents = buildScopeHierarchy(ast, processScope);
346
- const aliasable = tracker.getAliasableItems(strategy.shouldAlias);
347
- if (aliasable.length === 0)
348
- return ast;
349
- aliasable.forEach((info) => {
647
+ countBlock(ast.body, ast, new LexicalBindingScope());
648
+ const allCandidates = strategyStates.flatMap(({ tracker }) => tracker.getItems());
649
+ allCandidates.forEach((info) => {
350
650
  info.targetScope = findCommonAncestor(info.scopes, scopeParents, ast);
351
651
  });
652
+ const provisionalNames = new Set(unavailableNames);
653
+ const provisionalCounters = new Map();
654
+ const profitableCandidates = [];
655
+ [...allCandidates]
656
+ .sort((a, b) => a.order - b.order)
657
+ .forEach((info) => {
658
+ let counter = provisionalCounters.get(info.strategy.prefix) ?? 0;
659
+ let aliasName;
660
+ do {
661
+ aliasName = generateAliasName(counter++, info.strategy.prefix);
662
+ } while (lua_ast_1.LUA_RESERVED_WORDS.has(aliasName) || provisionalNames.has(aliasName));
663
+ const savings = info.strategy.estimateSavings(info, aliasName.length);
664
+ if (savings <= 0)
665
+ return;
666
+ provisionalCounters.set(info.strategy.prefix, counter);
667
+ provisionalNames.add(aliasName);
668
+ info.aliasName = aliasName;
669
+ info.estimatedSavings = savings;
670
+ profitableCandidates.push(info);
671
+ });
672
+ if (profitableCandidates.length === 0) {
673
+ return { ast, report: createEmptyAliasPassReport() };
674
+ }
675
+ // Selecting an outer expression removes its nested occurrences. Resolve
676
+ // those rare cross-strategy conflicts after capacity allocation, then rerun
677
+ // the allocator so a discarded overlap cannot leave a usable slot empty.
678
+ const conflictExcluded = new Set();
679
+ let retainedCandidates = [];
680
+ let selectedCandidates = new Set();
681
+ let baselinePressure;
682
+ while (true) {
683
+ retainedCandidates = profitableCandidates.filter((candidate) => !conflictExcluded.has(candidate));
684
+ baselinePressure = analyzeLocalPressure(ast);
685
+ retainedCandidates.forEach((candidate) => {
686
+ const pressureScope = baselinePressure.scopeByNode.get(candidate.targetScope);
687
+ pressureScope?.candidates.push(candidate);
688
+ });
689
+ selectedCandidates = new Set();
690
+ baselinePressure.functions.forEach((fn) => {
691
+ allocateCandidates(fn.rootScope).forEach((candidate) => selectedCandidates.add(candidate));
692
+ });
693
+ const selectedByBenefit = [...selectedCandidates].sort((a, b) => (b.estimatedSavings ?? 0) - (a.estimatedSavings ?? 0) || a.order - b.order);
694
+ const conflictWinners = [];
695
+ const newlyExcluded = [];
696
+ selectedByBenefit.forEach((candidate) => {
697
+ if (conflictWinners.some((winner) => candidate.conflicts.has(winner))) {
698
+ newlyExcluded.push(candidate);
699
+ }
700
+ else {
701
+ conflictWinners.push(candidate);
702
+ }
703
+ });
704
+ if (newlyExcluded.length === 0)
705
+ break;
706
+ newlyExcluded.forEach((candidate) => conflictExcluded.add(candidate));
707
+ }
708
+ retainedCandidates.forEach((candidate) => {
709
+ candidate.selected = selectedCandidates.has(candidate);
710
+ });
711
+ const assignedNames = new Set(unavailableNames);
712
+ const aliasCounters = new Map();
713
+ retainedCandidates.forEach((candidate) => {
714
+ candidate.aliasName = undefined;
715
+ });
716
+ [...selectedCandidates]
717
+ .sort((a, b) => a.order - b.order)
718
+ .forEach((candidate) => {
719
+ let counter = aliasCounters.get(candidate.strategy.prefix) ?? 0;
720
+ let aliasName;
721
+ do {
722
+ aliasName = generateAliasName(counter++, candidate.strategy.prefix);
723
+ } while (lua_ast_1.LUA_RESERVED_WORDS.has(aliasName) || assignedNames.has(aliasName));
724
+ aliasCounters.set(candidate.strategy.prefix, counter);
725
+ assignedNames.add(aliasName);
726
+ candidate.aliasName = aliasName;
727
+ candidate.estimatedSavings = candidate.strategy.estimateSavings(candidate, aliasName.length);
728
+ });
352
729
  const declarationsByScope = new Map();
353
- aliasable.forEach((info) => {
730
+ [...selectedCandidates]
731
+ .sort((a, b) => a.order - b.order)
732
+ .forEach((info) => {
354
733
  const scope = info.targetScope;
355
734
  if (!declarationsByScope.has(scope))
356
735
  declarationsByScope.set(scope, []);
357
736
  declarationsByScope.get(scope).push(info);
358
737
  });
359
- function replaceInStatement(stmt) {
360
- if (!stmt)
361
- return;
738
+ function replaceExpression(node) {
739
+ const selected = candidatesByNode.get(node)?.find((candidate) => candidate.selected);
740
+ if (selected?.aliasName) {
741
+ return { type: "Identifier", name: selected.aliasName };
742
+ }
743
+ switch (node.type) {
744
+ case "BinaryExpression":
745
+ case "LogicalExpression":
746
+ node.left = replaceExpression(node.left);
747
+ node.right = replaceExpression(node.right);
748
+ return node;
749
+ case "UnaryExpression":
750
+ node.argument = replaceExpression(node.argument);
751
+ return node;
752
+ case "CallExpression":
753
+ node.base = replaceExpression(node.base);
754
+ node.arguments = node.arguments.map(replaceExpression);
755
+ return node;
756
+ case "TableCallExpression":
757
+ node.base = replaceExpression(node.base);
758
+ node.arguments = replaceExpression(node.arguments);
759
+ return node;
760
+ case "StringCallExpression":
761
+ node.base = replaceExpression(node.base);
762
+ return node;
763
+ case "MemberExpression":
764
+ node.base = replaceExpression(node.base);
765
+ return node;
766
+ case "IndexExpression":
767
+ node.base = replaceExpression(node.base);
768
+ node.index = replaceExpression(node.index);
769
+ return node;
770
+ case "TableConstructorExpression":
771
+ node.fields.forEach((field) => {
772
+ if (field.type === "TableKey")
773
+ field.key = replaceExpression(field.key);
774
+ field.value = replaceExpression(field.value);
775
+ });
776
+ return node;
777
+ case "FunctionDeclaration":
778
+ node.body.forEach(replaceStatement);
779
+ return node;
780
+ default:
781
+ return node;
782
+ }
783
+ }
784
+ function replaceAssignmentTarget(node) {
785
+ if (node.type === "MemberExpression") {
786
+ node.base = replaceExpression(node.base);
787
+ }
788
+ else if (node.type === "IndexExpression") {
789
+ node.base = replaceExpression(node.base);
790
+ node.index = replaceExpression(node.index);
791
+ }
792
+ }
793
+ function replaceStatement(stmt) {
362
794
  switch (stmt.type) {
363
795
  case "LocalStatement":
364
- if (stmt.init)
365
- stmt.init = stmt.init.map((expr) => strategy.replaceExpression(expr, tracker));
366
- break;
796
+ stmt.init = stmt.init.map(replaceExpression);
797
+ return;
367
798
  case "AssignmentStatement":
368
- stmt.variables = stmt.variables.map((v) => strategy.replaceExpression(v, tracker));
369
- stmt.init = stmt.init.map((expr) => strategy.replaceExpression(expr, tracker));
370
- break;
799
+ stmt.variables.forEach(replaceAssignmentTarget);
800
+ stmt.init = stmt.init.map(replaceExpression);
801
+ return;
371
802
  case "CallStatement":
372
- stmt.expression = strategy.replaceExpression(stmt.expression, tracker);
373
- break;
803
+ stmt.expression = replaceExpression(stmt.expression);
804
+ return;
374
805
  case "ReturnStatement":
375
- stmt.arguments = stmt.arguments.map((arg) => strategy.replaceExpression(arg, tracker));
376
- break;
806
+ stmt.arguments = stmt.arguments.map(replaceExpression);
807
+ return;
377
808
  case "IfStatement":
378
809
  stmt.clauses.forEach((clause) => {
379
- if (clause.type !== "ElseClause" && clause.condition)
380
- clause.condition = strategy.replaceExpression(clause.condition, tracker);
381
- clause.body.forEach((s) => replaceInStatement(s));
810
+ if (clause.type !== "ElseClause")
811
+ clause.condition = replaceExpression(clause.condition);
812
+ clause.body.forEach(replaceStatement);
382
813
  });
383
- break;
814
+ return;
384
815
  case "WhileStatement":
385
- stmt.condition = strategy.replaceExpression(stmt.condition, tracker);
386
- stmt.body.forEach((s) => replaceInStatement(s));
387
- break;
816
+ stmt.condition = replaceExpression(stmt.condition);
817
+ stmt.body.forEach(replaceStatement);
818
+ return;
388
819
  case "RepeatStatement":
389
- stmt.body.forEach((s) => replaceInStatement(s));
390
- stmt.condition = strategy.replaceExpression(stmt.condition, tracker);
391
- break;
820
+ stmt.body.forEach(replaceStatement);
821
+ stmt.condition = replaceExpression(stmt.condition);
822
+ return;
392
823
  case "ForNumericStatement":
393
- stmt.start = strategy.replaceExpression(stmt.start, tracker);
394
- stmt.end = strategy.replaceExpression(stmt.end, tracker);
824
+ stmt.start = replaceExpression(stmt.start);
825
+ stmt.end = replaceExpression(stmt.end);
395
826
  if (stmt.step)
396
- stmt.step = strategy.replaceExpression(stmt.step, tracker);
397
- stmt.body.forEach((s) => replaceInStatement(s));
398
- break;
827
+ stmt.step = replaceExpression(stmt.step);
828
+ stmt.body.forEach(replaceStatement);
829
+ return;
399
830
  case "ForGenericStatement":
400
- stmt.iterators = stmt.iterators.map((it) => strategy.replaceExpression(it, tracker));
401
- stmt.body.forEach((s) => replaceInStatement(s));
402
- break;
831
+ stmt.iterators = stmt.iterators.map(replaceExpression);
832
+ stmt.body.forEach(replaceStatement);
833
+ return;
403
834
  case "FunctionDeclaration":
404
- stmt.body.forEach((s) => replaceInStatement(s));
405
- break;
835
+ if (!stmt.isLocal && stmt.identifier)
836
+ replaceAssignmentTarget(stmt.identifier);
837
+ stmt.body.forEach(replaceStatement);
838
+ return;
406
839
  case "DoStatement":
407
- stmt.body.forEach((s) => replaceInStatement(s));
408
- break;
840
+ stmt.body.forEach(replaceStatement);
841
+ return;
842
+ default:
843
+ return;
409
844
  }
410
845
  }
411
- ast.body.forEach((stmt) => replaceInStatement(stmt));
412
- insertDeclarationsIntoScopes(ast, declarationsByScope);
413
- return ast;
846
+ ast.body.forEach(replaceStatement);
847
+ const generatedDeclarations = new WeakSet();
848
+ insertDeclarationsIntoScopes(declarationsByScope, generatedDeclarations);
849
+ const finalPressure = analyzeLocalPressure(ast, generatedDeclarations);
850
+ const constrainedFunctions = [];
851
+ baselinePressure.functions.forEach((baselineFn) => {
852
+ const candidatesForFunction = retainedCandidates.filter((candidate) => {
853
+ return baselinePressure.scopeByNode.get(candidate.targetScope)?.functionRoot === baselineFn.root;
854
+ });
855
+ const omitted = candidatesForFunction.filter((candidate) => !candidate.selected);
856
+ if (omitted.length === 0)
857
+ return;
858
+ const rules = {
859
+ aliasLiterals: emptyRuleReport(),
860
+ aliasRepeatedExpressions: emptyRuleReport(),
861
+ };
862
+ candidatesForFunction.forEach((candidate) => {
863
+ const rule = rules[candidate.strategy.rule];
864
+ if (candidate.selected) {
865
+ rule.accepted++;
866
+ rule.estimatedBytesSaved += candidate.estimatedSavings ?? 0;
867
+ }
868
+ else {
869
+ rule.omitted++;
870
+ rule.estimatedBytesOmitted += candidate.estimatedSavings ?? 0;
871
+ }
872
+ });
873
+ const finalFn = finalPressure.functionByRoot.get(baselineFn.root);
874
+ constrainedFunctions.push({
875
+ functionName: functionName(baselineFn.root),
876
+ sourceLine: baselineFn.root.loc?.start.line ?? 1,
877
+ localLimit: exports.LUA_MAX_ACTIVE_LOCALS,
878
+ peakActiveLocals: finalFn.peakActiveLocals,
879
+ existingLocalsAtPeak: finalFn.existingLocalsAtPeak,
880
+ generatedLocalsAtPeak: finalFn.generatedLocalsAtPeak,
881
+ rules,
882
+ });
883
+ });
884
+ return {
885
+ ast,
886
+ report: { localLimit: exports.LUA_MAX_ACTIVE_LOCALS, constrainedFunctions },
887
+ };
888
+ }
889
+ function runAliasPass(ast, strategy) {
890
+ return runAliasPasses(ast, [strategy]).ast;
414
891
  }
415
892
  //# sourceMappingURL=lua_alias_shared.js.map