luau-obfuscator 1.0.0 → 1.0.1
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/.github/workflows/release.yml +56 -56
- package/dist/index.cjs +2014 -44
- package/dist/index.d.cts +34 -2
- package/dist/index.d.ts +34 -2
- package/dist/index.js +2014 -44
- package/generated/final.luau +63004 -817
- package/generated/smoketest.luau +24339 -0
- package/package.json +2 -2
- package/scripts/example.luau +1174 -1174
- package/scripts/smoketest.luau +115 -0
- package/scripts/test.js +16 -8
- package/src/config.ts +2 -1
- package/src/passes/ConstantArray.ts +89 -89
- package/src/passes/EncryptNumbers.ts +121 -65
- package/src/passes/EncryptStrings.ts +162 -82
- package/src/passes/GlobalMapping.ts +193 -193
- package/src/passes/InsertJunk.ts +184 -184
- package/src/passes/Minify.ts +5 -5
- package/src/passes/NumbersToExpressions.ts +180 -2
- package/src/passes/RenameVariables.ts +2 -9
- package/src/passes/StringsToExpressions.ts +167 -2
- package/src/passes/StripTypes.ts +191 -191
- package/src/passes/Vmify.ts +73 -0
- package/src/passes/WrapInFunction.ts +31 -31
- package/src/passes/nodeFactory.ts +17 -1
- package/src/passes/vmify/chunk.ts +50 -0
- package/src/passes/vmify/compiler.ts +1026 -0
- package/src/passes/vmify/names.ts +78 -0
- package/src/passes/vmify/opcodes.ts +80 -0
- package/src/passes/vmify/registers.ts +63 -0
- package/src/passes/vmify/runtime.ts +334 -0
- package/src/passes/vmify/scope-walk.ts +175 -0
- package/src/passes/vmify/serialize.ts +68 -0
- package/src/pipeline.ts +3 -1
- package/tsconfig.json +20 -20
- package/tsup.config.ts +9 -9
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// src/index.ts
|
|
2
|
-
import { luauparser } from "luau-parser";
|
|
2
|
+
import { luauparser as luauparser3 } from "luau-parser";
|
|
3
3
|
|
|
4
4
|
// src/config.ts
|
|
5
5
|
var ObfuscateDefault = {
|
|
@@ -354,6 +354,15 @@ function computedField(key, value) {
|
|
|
354
354
|
function positionalField(value) {
|
|
355
355
|
return { type: "TableFieldPositional", value };
|
|
356
356
|
}
|
|
357
|
+
function namedField(name, value) {
|
|
358
|
+
return { type: "TableFieldNamed", name: identifier(name), value };
|
|
359
|
+
}
|
|
360
|
+
function booleanLiteral(value) {
|
|
361
|
+
return { type: "BooleanLiteral", value, line: POS, column: POS };
|
|
362
|
+
}
|
|
363
|
+
function nilLiteral() {
|
|
364
|
+
return { type: "NilLiteral", line: POS, column: POS };
|
|
365
|
+
}
|
|
357
366
|
function localStatement(name, init) {
|
|
358
367
|
return {
|
|
359
368
|
type: "LocalStatement",
|
|
@@ -418,14 +427,21 @@ function ifClause(condition, body) {
|
|
|
418
427
|
function ifStatement(clauses, alternate) {
|
|
419
428
|
return { type: "IfStatement", clauses, alternate, line: POS, column: POS };
|
|
420
429
|
}
|
|
430
|
+
function whileStatement(condition, body) {
|
|
431
|
+
return { type: "WhileStatement", condition, body, line: POS, column: POS };
|
|
432
|
+
}
|
|
421
433
|
function vararg() {
|
|
422
434
|
return { type: "VarargExpression", line: POS, column: POS };
|
|
423
435
|
}
|
|
424
436
|
|
|
425
437
|
// src/passes/StringsToExpressions.ts
|
|
438
|
+
var CONTROL_FLOW_PROBABILITY_DEFAULT = 0.6;
|
|
426
439
|
function randomInt(min, max) {
|
|
427
440
|
return Math.floor(Math.random() * (max - min + 1)) + min;
|
|
428
441
|
}
|
|
442
|
+
function randomName() {
|
|
443
|
+
return "_" + globalThis.crypto.randomUUID().replace(/-/g, "");
|
|
444
|
+
}
|
|
429
445
|
function toUtf8Bytes(value) {
|
|
430
446
|
return Array.from(new TextEncoder().encode(value));
|
|
431
447
|
}
|
|
@@ -449,12 +465,106 @@ function buildConcatChain(chunks) {
|
|
|
449
465
|
}
|
|
450
466
|
return expr;
|
|
451
467
|
}
|
|
468
|
+
function shuffledIndices(n) {
|
|
469
|
+
const arr = Array.from({ length: n }, (_, i) => i);
|
|
470
|
+
for (let i = n - 1; i > 0; i--) {
|
|
471
|
+
const j = randomInt(0, i);
|
|
472
|
+
[arr[i], arr[j]] = [arr[j], arr[i]];
|
|
473
|
+
}
|
|
474
|
+
return arr;
|
|
475
|
+
}
|
|
476
|
+
function iife(statements) {
|
|
477
|
+
return call(paren(functionExpression(functionBody([], block(statements)))), []);
|
|
478
|
+
}
|
|
479
|
+
function buildShuffledTables(chunks) {
|
|
480
|
+
const n = chunks.length;
|
|
481
|
+
const storageOrder = shuffledIndices(n);
|
|
482
|
+
const storeVar = randomName();
|
|
483
|
+
const orderVar = randomName();
|
|
484
|
+
const storeFields = storageOrder.map((originalIdx) => positionalField(stringCharCall(chunks[originalIdx])));
|
|
485
|
+
const order = new Array(n);
|
|
486
|
+
for (let slot = 0; slot < n; slot++) {
|
|
487
|
+
order[storageOrder[slot]] = slot + 1;
|
|
488
|
+
}
|
|
489
|
+
const orderFields = order.map((slot) => positionalField(numberLiteral(slot)));
|
|
490
|
+
return {
|
|
491
|
+
storeVar,
|
|
492
|
+
orderVar,
|
|
493
|
+
stmts: [
|
|
494
|
+
localStatement(storeVar, table(storeFields)),
|
|
495
|
+
localStatement(orderVar, table(orderFields))
|
|
496
|
+
]
|
|
497
|
+
};
|
|
498
|
+
}
|
|
499
|
+
function buildForLoopStringExpr(chunks) {
|
|
500
|
+
const { storeVar, orderVar, stmts } = buildShuffledTables(chunks);
|
|
501
|
+
const accVar = randomName();
|
|
502
|
+
const iVar = randomName();
|
|
503
|
+
return iife([
|
|
504
|
+
...stmts,
|
|
505
|
+
localStatement(accVar, stringLiteral("")),
|
|
506
|
+
numericForStatement(
|
|
507
|
+
iVar,
|
|
508
|
+
numberLiteral(1),
|
|
509
|
+
unary("#", identifier(orderVar)),
|
|
510
|
+
block([
|
|
511
|
+
assignmentStatement(
|
|
512
|
+
[identifier(accVar)],
|
|
513
|
+
[
|
|
514
|
+
binary(
|
|
515
|
+
"..",
|
|
516
|
+
identifier(accVar),
|
|
517
|
+
index(identifier(storeVar), index(identifier(orderVar), identifier(iVar)))
|
|
518
|
+
)
|
|
519
|
+
]
|
|
520
|
+
)
|
|
521
|
+
])
|
|
522
|
+
),
|
|
523
|
+
returnStatement([identifier(accVar)])
|
|
524
|
+
]);
|
|
525
|
+
}
|
|
526
|
+
function buildRecursiveStringExpr(chunks) {
|
|
527
|
+
const { storeVar, orderVar, stmts } = buildShuffledTables(chunks);
|
|
528
|
+
const recName = randomName();
|
|
529
|
+
const iParam = randomName();
|
|
530
|
+
const accParam = randomName();
|
|
531
|
+
const body = block([
|
|
532
|
+
ifStatement([
|
|
533
|
+
ifClause(
|
|
534
|
+
binary(">", identifier(iParam), unary("#", identifier(orderVar))),
|
|
535
|
+
block([returnStatement([identifier(accParam)])])
|
|
536
|
+
)
|
|
537
|
+
]),
|
|
538
|
+
returnStatement([
|
|
539
|
+
call(identifier(recName), [
|
|
540
|
+
binary("+", identifier(iParam), numberLiteral(1)),
|
|
541
|
+
binary(
|
|
542
|
+
"..",
|
|
543
|
+
identifier(accParam),
|
|
544
|
+
index(identifier(storeVar), index(identifier(orderVar), identifier(iParam)))
|
|
545
|
+
)
|
|
546
|
+
])
|
|
547
|
+
])
|
|
548
|
+
]);
|
|
549
|
+
return iife([
|
|
550
|
+
...stmts,
|
|
551
|
+
localFunctionStatement(recName, functionBody([functionParam(iParam), functionParam(accParam)], body)),
|
|
552
|
+
returnStatement([call(identifier(recName), [numberLiteral(1), stringLiteral("")])])
|
|
553
|
+
]);
|
|
554
|
+
}
|
|
555
|
+
function pickControlFlowStrategy() {
|
|
556
|
+
return Math.random() < 0.5 ? "forLoop" : "recursive";
|
|
557
|
+
}
|
|
452
558
|
function runStringsToExpressions(program, options) {
|
|
559
|
+
const controlFlowProbability = options.controlFlowProbability ?? CONTROL_FLOW_PROBABILITY_DEFAULT;
|
|
453
560
|
transformExpressions(program, (expr) => {
|
|
454
561
|
if (expr.type !== "StringLiteral") return;
|
|
455
562
|
if (expr.value.length === 0) return;
|
|
456
563
|
const bytes = toUtf8Bytes(expr.value);
|
|
457
564
|
const chunks = splitByteChunks(bytes, options.min, options.max);
|
|
565
|
+
if (chunks.length > 1 && Math.random() < controlFlowProbability) {
|
|
566
|
+
return pickControlFlowStrategy() === "forLoop" ? buildForLoopStringExpr(chunks) : buildRecursiveStringExpr(chunks);
|
|
567
|
+
}
|
|
458
568
|
return buildConcatChain(chunks);
|
|
459
569
|
});
|
|
460
570
|
}
|
|
@@ -462,12 +572,19 @@ function runStringsToExpressions(program, options) {
|
|
|
462
572
|
// src/passes/NumbersToExpressions.ts
|
|
463
573
|
var MAX_DEPTH = 1;
|
|
464
574
|
var NEST_PROBABILITY = 0.35;
|
|
575
|
+
var CONTROL_FLOW_PROBABILITY_DEFAULT2 = 0.35;
|
|
465
576
|
function randomInt2(min, max) {
|
|
466
577
|
return Math.floor(Math.random() * (max - min + 1)) + min;
|
|
467
578
|
}
|
|
579
|
+
function randomName2() {
|
|
580
|
+
return "_" + globalThis.crypto.randomUUID().replace(/-/g, "");
|
|
581
|
+
}
|
|
468
582
|
function randSign() {
|
|
469
583
|
return Math.random() < 0.5 ? 1 : -1;
|
|
470
584
|
}
|
|
585
|
+
function iife2(statements) {
|
|
586
|
+
return call(paren(functionExpression(functionBody([], block(statements)))), []);
|
|
587
|
+
}
|
|
471
588
|
function pickStrategy(value, min, max) {
|
|
472
589
|
const candidates = ["add", "sub"];
|
|
473
590
|
if (value !== 0) {
|
|
@@ -517,27 +634,120 @@ function buildNumberExpr(value, min, max, depth = 0) {
|
|
|
517
634
|
}
|
|
518
635
|
return paren(inner);
|
|
519
636
|
}
|
|
637
|
+
function randomPartition(value, n, min, max) {
|
|
638
|
+
const parts = [];
|
|
639
|
+
let remaining = value;
|
|
640
|
+
for (let i = 0; i < n - 1; i++) {
|
|
641
|
+
const part = randomInt2(min, max) * randSign();
|
|
642
|
+
parts.push(part);
|
|
643
|
+
remaining -= part;
|
|
644
|
+
}
|
|
645
|
+
parts.push(remaining);
|
|
646
|
+
return parts;
|
|
647
|
+
}
|
|
648
|
+
function buildForLoopNumberExpr(value, min, max) {
|
|
649
|
+
const n = randomInt2(3, 6);
|
|
650
|
+
const steps = randomPartition(value, n, min, max);
|
|
651
|
+
const accVar = randomName2();
|
|
652
|
+
const stepsVar = randomName2();
|
|
653
|
+
const iVar = randomName2();
|
|
654
|
+
const stmts = [
|
|
655
|
+
localStatement(stepsVar, table(steps.map((s) => positionalField(numberLiteral(s))))),
|
|
656
|
+
localStatement(accVar, numberLiteral(0)),
|
|
657
|
+
numericForStatement(
|
|
658
|
+
iVar,
|
|
659
|
+
numberLiteral(1),
|
|
660
|
+
unary("#", identifier(stepsVar)),
|
|
661
|
+
block([
|
|
662
|
+
assignmentStatement(
|
|
663
|
+
[identifier(accVar)],
|
|
664
|
+
[binary("+", identifier(accVar), index(identifier(stepsVar), identifier(iVar)))]
|
|
665
|
+
)
|
|
666
|
+
])
|
|
667
|
+
),
|
|
668
|
+
returnStatement([identifier(accVar)])
|
|
669
|
+
];
|
|
670
|
+
return iife2(stmts);
|
|
671
|
+
}
|
|
672
|
+
function buildWhileLoopNumberExpr(value, min, max) {
|
|
673
|
+
const n = randomInt2(3, 6);
|
|
674
|
+
const step = randomInt2(min, max) * randSign();
|
|
675
|
+
const base = value - n * step;
|
|
676
|
+
const accVar = randomName2();
|
|
677
|
+
const nVar = randomName2();
|
|
678
|
+
const stmts = [
|
|
679
|
+
localStatement(accVar, numberLiteral(base)),
|
|
680
|
+
localStatement(nVar, numberLiteral(n)),
|
|
681
|
+
whileStatement(
|
|
682
|
+
binary(">", identifier(nVar), numberLiteral(0)),
|
|
683
|
+
block([
|
|
684
|
+
assignmentStatement([identifier(accVar)], [binary("+", identifier(accVar), numberLiteral(step))]),
|
|
685
|
+
assignmentStatement([identifier(nVar)], [binary("-", identifier(nVar), numberLiteral(1))])
|
|
686
|
+
])
|
|
687
|
+
),
|
|
688
|
+
returnStatement([identifier(accVar)])
|
|
689
|
+
];
|
|
690
|
+
return iife2(stmts);
|
|
691
|
+
}
|
|
692
|
+
function buildRecursiveNumberExpr(value, min, max) {
|
|
693
|
+
const n = randomInt2(3, 6);
|
|
694
|
+
const step = randomInt2(min, max) * randSign();
|
|
695
|
+
const base = value - n * step;
|
|
696
|
+
const recName = randomName2();
|
|
697
|
+
const nParam = randomName2();
|
|
698
|
+
const body = block([
|
|
699
|
+
ifStatement([
|
|
700
|
+
ifClause(
|
|
701
|
+
binary("<=", identifier(nParam), numberLiteral(0)),
|
|
702
|
+
block([returnStatement([numberLiteral(base)])])
|
|
703
|
+
)
|
|
704
|
+
]),
|
|
705
|
+
returnStatement([
|
|
706
|
+
binary(
|
|
707
|
+
"+",
|
|
708
|
+
numberLiteral(step),
|
|
709
|
+
call(identifier(recName), [binary("-", identifier(nParam), numberLiteral(1))])
|
|
710
|
+
)
|
|
711
|
+
])
|
|
712
|
+
]);
|
|
713
|
+
return iife2([
|
|
714
|
+
localFunctionStatement(recName, functionBody([functionParam(nParam)], body)),
|
|
715
|
+
returnStatement([call(identifier(recName), [numberLiteral(n)])])
|
|
716
|
+
]);
|
|
717
|
+
}
|
|
718
|
+
function pickControlFlowStrategy2() {
|
|
719
|
+
const options = ["forLoop", "whileLoop", "recursive"];
|
|
720
|
+
return options[randomInt2(0, options.length - 1)];
|
|
721
|
+
}
|
|
722
|
+
function buildControlFlowNumberExpr(value, min, max) {
|
|
723
|
+
switch (pickControlFlowStrategy2()) {
|
|
724
|
+
case "forLoop":
|
|
725
|
+
return buildForLoopNumberExpr(value, min, max);
|
|
726
|
+
case "whileLoop":
|
|
727
|
+
return buildWhileLoopNumberExpr(value, min, max);
|
|
728
|
+
case "recursive":
|
|
729
|
+
return buildRecursiveNumberExpr(value, min, max);
|
|
730
|
+
}
|
|
731
|
+
}
|
|
520
732
|
function runNumbersToExpressions(program, options) {
|
|
733
|
+
const controlFlowProbability = options.controlFlowProbability ?? CONTROL_FLOW_PROBABILITY_DEFAULT2;
|
|
521
734
|
transformExpressions(program, (expr) => {
|
|
522
735
|
if (expr.type !== "NumberLiteral") return;
|
|
736
|
+
if (Number.isInteger(expr.value) && Math.random() < controlFlowProbability) {
|
|
737
|
+
return buildControlFlowNumberExpr(expr.value, options.min, options.max);
|
|
738
|
+
}
|
|
523
739
|
return buildNumberExpr(expr.value, options.min, options.max);
|
|
524
740
|
});
|
|
525
741
|
}
|
|
526
742
|
|
|
527
743
|
// src/passes/RenameVariables.ts
|
|
528
744
|
import { analyzeScopes, isGlobal } from "luau-parser";
|
|
529
|
-
var counter = 0;
|
|
530
|
-
function defaultRandomName() {
|
|
531
|
-
counter += 1;
|
|
532
|
-
return `_l${counter.toString(36)}`;
|
|
533
|
-
}
|
|
534
745
|
function runRenameVariables(program, options) {
|
|
535
746
|
const analysis = analyzeScopes(program);
|
|
536
|
-
const makeName = options.random ?? defaultRandomName;
|
|
537
747
|
for (const binding of analysis.bindings.values()) {
|
|
538
748
|
if (isGlobal(binding)) continue;
|
|
539
749
|
if (binding.kind === "self") continue;
|
|
540
|
-
const newName =
|
|
750
|
+
const newName = options.random();
|
|
541
751
|
binding.name = newName;
|
|
542
752
|
if (binding.declarationNode) {
|
|
543
753
|
binding.declarationNode.name = newName;
|
|
@@ -752,21 +962,72 @@ function runConstantArray(program, options) {
|
|
|
752
962
|
}
|
|
753
963
|
|
|
754
964
|
// src/passes/EncryptStrings.ts
|
|
965
|
+
var MIN_KEY_LEN = 4;
|
|
966
|
+
var MAX_KEY_LEN = 12;
|
|
755
967
|
function randomInt4(min, max) {
|
|
756
968
|
return Math.floor(Math.random() * (max - min + 1)) + min;
|
|
757
969
|
}
|
|
758
|
-
function
|
|
970
|
+
function randomName3() {
|
|
759
971
|
return "_" + globalThis.crypto.randomUUID().replace(/-/g, "");
|
|
760
972
|
}
|
|
761
973
|
function toUtf8Bytes2(value) {
|
|
762
974
|
return Array.from(new TextEncoder().encode(value));
|
|
763
975
|
}
|
|
976
|
+
function lrotate32(x, disp) {
|
|
977
|
+
const d = (disp % 32 + 32) % 32;
|
|
978
|
+
const xu = x >>> 0;
|
|
979
|
+
if (d === 0) return xu;
|
|
980
|
+
return (xu << d | xu >>> 32 - d) >>> 0;
|
|
981
|
+
}
|
|
982
|
+
function keystreamByte(keys, mult, i) {
|
|
983
|
+
const nKeys = keys.length;
|
|
984
|
+
const keyByte = keys[(i - 1) % nKeys];
|
|
985
|
+
const rotated = lrotate32(keyByte, i % 8) & 255;
|
|
986
|
+
const posByte = i * mult & 255;
|
|
987
|
+
return (rotated ^ posByte) & 255;
|
|
988
|
+
}
|
|
989
|
+
function obfuscatedNumber(value) {
|
|
990
|
+
const variant = randomInt4(0, 2);
|
|
991
|
+
if (variant === 0) {
|
|
992
|
+
const a2 = randomInt4(0, value);
|
|
993
|
+
return binary("+", numberLiteral(a2), numberLiteral(value - a2));
|
|
994
|
+
}
|
|
995
|
+
if (variant === 1) {
|
|
996
|
+
const a2 = randomInt4(0, 16777215);
|
|
997
|
+
return binary("-", numberLiteral(value + a2), numberLiteral(a2));
|
|
998
|
+
}
|
|
999
|
+
const a = randomInt4(0, 16777215);
|
|
1000
|
+
const b = (value ^ a) >>> 0;
|
|
1001
|
+
return call(member(identifier("bit32"), "bxor"), [numberLiteral(a), numberLiteral(b)]);
|
|
1002
|
+
}
|
|
764
1003
|
function buildDecoderStatement(name) {
|
|
765
|
-
const dataParam =
|
|
766
|
-
const
|
|
767
|
-
const
|
|
768
|
-
const
|
|
1004
|
+
const dataParam = randomName3();
|
|
1005
|
+
const keysParam = randomName3();
|
|
1006
|
+
const multParam = randomName3();
|
|
1007
|
+
const outVar = randomName3();
|
|
1008
|
+
const iVar = randomName3();
|
|
1009
|
+
const nKeysVar = randomName3();
|
|
1010
|
+
const idxExpr = binary(
|
|
1011
|
+
"+",
|
|
1012
|
+
binary("%", binary("-", identifier(iVar), numberLiteral(1)), identifier(nKeysVar)),
|
|
1013
|
+
numberLiteral(1)
|
|
1014
|
+
);
|
|
1015
|
+
const keyByte = index(identifier(keysParam), idxExpr);
|
|
1016
|
+
const mixed = call(member(identifier("bit32"), "band"), [
|
|
1017
|
+
call(member(identifier("bit32"), "lrotate"), [keyByte, binary("%", identifier(iVar), numberLiteral(8))]),
|
|
1018
|
+
numberLiteral(255)
|
|
1019
|
+
]);
|
|
1020
|
+
const posByte = call(member(identifier("bit32"), "band"), [
|
|
1021
|
+
binary("*", identifier(iVar), identifier(multParam)),
|
|
1022
|
+
numberLiteral(255)
|
|
1023
|
+
]);
|
|
1024
|
+
const keystream = call(member(identifier("bit32"), "bxor"), [mixed, posByte]);
|
|
1025
|
+
const finalByte = call(member(identifier("bit32"), "bxor"), [
|
|
1026
|
+
index(identifier(dataParam), identifier(iVar)),
|
|
1027
|
+
keystream
|
|
1028
|
+
]);
|
|
769
1029
|
const body = block([
|
|
1030
|
+
localStatement(nKeysVar, unary("#", identifier(keysParam))),
|
|
770
1031
|
localStatement(outVar, table([])),
|
|
771
1032
|
numericForStatement(
|
|
772
1033
|
iVar,
|
|
@@ -775,30 +1036,33 @@ function buildDecoderStatement(name) {
|
|
|
775
1036
|
block([
|
|
776
1037
|
assignmentStatement(
|
|
777
1038
|
[index(identifier(outVar), identifier(iVar))],
|
|
778
|
-
[call(member(identifier("string"), "char"), [
|
|
779
|
-
call(member(identifier("bit32"), "bxor"), [
|
|
780
|
-
index(identifier(dataParam), identifier(iVar)),
|
|
781
|
-
identifier(keyParam)
|
|
782
|
-
])
|
|
783
|
-
])]
|
|
1039
|
+
[call(member(identifier("string"), "char"), [finalByte])]
|
|
784
1040
|
)
|
|
785
1041
|
])
|
|
786
1042
|
),
|
|
787
1043
|
returnStatement([call(member(identifier("table"), "concat"), [identifier(outVar)])])
|
|
788
1044
|
]);
|
|
789
|
-
return localFunctionStatement(
|
|
1045
|
+
return localFunctionStatement(
|
|
1046
|
+
name,
|
|
1047
|
+
functionBody([functionParam(dataParam), functionParam(keysParam), functionParam(multParam)], body)
|
|
1048
|
+
);
|
|
790
1049
|
}
|
|
791
1050
|
function runEncryptStrings(program, _options) {
|
|
792
|
-
const decoderName =
|
|
1051
|
+
const decoderName = randomName3();
|
|
793
1052
|
let used = false;
|
|
794
1053
|
transformExpressions(program, (expr) => {
|
|
795
1054
|
if (expr.type !== "StringLiteral") return;
|
|
796
1055
|
if (expr.value.length === 0) return;
|
|
797
1056
|
used = true;
|
|
798
|
-
const
|
|
799
|
-
const
|
|
800
|
-
const
|
|
801
|
-
|
|
1057
|
+
const keyLen = randomInt4(MIN_KEY_LEN, MAX_KEY_LEN);
|
|
1058
|
+
const keys = Array.from({ length: keyLen }, () => randomInt4(1, 255));
|
|
1059
|
+
const mult = randomInt4(1, 255);
|
|
1060
|
+
const plainBytes = toUtf8Bytes2(expr.value);
|
|
1061
|
+
const cipherBytes = plainBytes.map((b, idx) => b ^ keystreamByte(keys, mult, idx + 1));
|
|
1062
|
+
const dataTable = table(cipherBytes.map((b) => positionalField(numberLiteral(b))));
|
|
1063
|
+
const keysTable = table(keys.map((k) => positionalField(obfuscatedNumber(k))));
|
|
1064
|
+
const multExpr = obfuscatedNumber(mult);
|
|
1065
|
+
return call(identifier(decoderName), [dataTable, keysTable, multExpr]);
|
|
802
1066
|
});
|
|
803
1067
|
if (!used) return;
|
|
804
1068
|
program.body.statements.unshift(buildDecoderStatement(decoderName));
|
|
@@ -806,10 +1070,11 @@ function runEncryptStrings(program, _options) {
|
|
|
806
1070
|
|
|
807
1071
|
// src/passes/EncryptNumbers.ts
|
|
808
1072
|
var UINT32_MAX = 4294967295;
|
|
1073
|
+
var MOD32 = 4294967296;
|
|
809
1074
|
function randomInt5(min, max) {
|
|
810
1075
|
return Math.floor(Math.random() * (max - min + 1)) + min;
|
|
811
1076
|
}
|
|
812
|
-
function
|
|
1077
|
+
function randomName4() {
|
|
813
1078
|
return "_" + globalThis.crypto.randomUUID().replace(/-/g, "");
|
|
814
1079
|
}
|
|
815
1080
|
function isEncryptable(value) {
|
|
@@ -818,24 +1083,60 @@ function isEncryptable(value) {
|
|
|
818
1083
|
function xor32(a, b) {
|
|
819
1084
|
return (a ^ b) >>> 0;
|
|
820
1085
|
}
|
|
1086
|
+
function modAdd32(a, b) {
|
|
1087
|
+
return ((a + b) % MOD32 + MOD32) % MOD32;
|
|
1088
|
+
}
|
|
1089
|
+
function obfuscatedNumber2(value) {
|
|
1090
|
+
const variant = randomInt5(0, 2);
|
|
1091
|
+
if (variant === 0) {
|
|
1092
|
+
const a2 = randomInt5(0, value);
|
|
1093
|
+
return binary("+", numberLiteral(a2), numberLiteral(value - a2));
|
|
1094
|
+
}
|
|
1095
|
+
if (variant === 1) {
|
|
1096
|
+
const a2 = randomInt5(0, 16777215);
|
|
1097
|
+
return binary("-", numberLiteral(value + a2), numberLiteral(a2));
|
|
1098
|
+
}
|
|
1099
|
+
const a = randomInt5(0, 16777215);
|
|
1100
|
+
const b = xor32(value, a);
|
|
1101
|
+
return call(member(identifier("bit32"), "bxor"), [numberLiteral(a), numberLiteral(b)]);
|
|
1102
|
+
}
|
|
821
1103
|
function buildDecoderStatement2(name) {
|
|
822
|
-
const
|
|
823
|
-
const
|
|
1104
|
+
const xParam = randomName4();
|
|
1105
|
+
const keyAParam = randomName4();
|
|
1106
|
+
const keyBParam = randomName4();
|
|
1107
|
+
const tVar = randomName4();
|
|
824
1108
|
const body = block([
|
|
825
|
-
|
|
1109
|
+
localStatement(
|
|
1110
|
+
tVar,
|
|
1111
|
+
binary(
|
|
1112
|
+
"%",
|
|
1113
|
+
binary("-", identifier(xParam), identifier(keyBParam)),
|
|
1114
|
+
numberLiteral(MOD32)
|
|
1115
|
+
)
|
|
1116
|
+
),
|
|
1117
|
+
returnStatement([call(member(identifier("bit32"), "bxor"), [identifier(tVar), identifier(keyAParam)])])
|
|
826
1118
|
]);
|
|
827
|
-
return localFunctionStatement(
|
|
1119
|
+
return localFunctionStatement(
|
|
1120
|
+
name,
|
|
1121
|
+
functionBody([functionParam(xParam), functionParam(keyAParam), functionParam(keyBParam)], body)
|
|
1122
|
+
);
|
|
828
1123
|
}
|
|
829
1124
|
function runEncryptNumbers(program, _options) {
|
|
830
|
-
const decoderName =
|
|
1125
|
+
const decoderName = randomName4();
|
|
831
1126
|
let used = false;
|
|
832
1127
|
transformExpressions(program, (expr) => {
|
|
833
1128
|
if (expr.type !== "NumberLiteral") return;
|
|
834
1129
|
if (!isEncryptable(expr.value)) return;
|
|
835
1130
|
used = true;
|
|
836
|
-
const
|
|
837
|
-
const
|
|
838
|
-
|
|
1131
|
+
const keyA = randomInt5(1, 16777215);
|
|
1132
|
+
const keyB = randomInt5(1, 16777215);
|
|
1133
|
+
const t1 = xor32(expr.value, keyA);
|
|
1134
|
+
const encoded = modAdd32(t1, keyB);
|
|
1135
|
+
return call(identifier(decoderName), [
|
|
1136
|
+
obfuscatedNumber2(encoded),
|
|
1137
|
+
obfuscatedNumber2(keyA),
|
|
1138
|
+
obfuscatedNumber2(keyB)
|
|
1139
|
+
]);
|
|
839
1140
|
});
|
|
840
1141
|
if (!used) return;
|
|
841
1142
|
program.body.statements.unshift(buildDecoderStatement2(decoderName));
|
|
@@ -845,7 +1146,7 @@ function runEncryptNumbers(program, _options) {
|
|
|
845
1146
|
function randomInt6(min, max) {
|
|
846
1147
|
return Math.floor(Math.random() * (max - min + 1)) + min;
|
|
847
1148
|
}
|
|
848
|
-
function
|
|
1149
|
+
function randomName5() {
|
|
849
1150
|
return "_" + globalThis.crypto.randomUUID().replace(/-/g, "");
|
|
850
1151
|
}
|
|
851
1152
|
function junkNumberExpr() {
|
|
@@ -854,12 +1155,12 @@ function junkNumberExpr() {
|
|
|
854
1155
|
}
|
|
855
1156
|
function buildJunkStatement() {
|
|
856
1157
|
const variants = [
|
|
857
|
-
() => localStatement(
|
|
858
|
-
() => doStatement(block([localStatement(
|
|
1158
|
+
() => localStatement(randomName5(), junkNumberExpr()),
|
|
1159
|
+
() => doStatement(block([localStatement(randomName5(), junkNumberExpr())])),
|
|
859
1160
|
() => ifStatement([
|
|
860
1161
|
ifClause(
|
|
861
1162
|
binary("==", numberLiteral(randomInt6(1, 999)), numberLiteral(randomInt6(1, 999))),
|
|
862
|
-
block([localStatement(
|
|
1163
|
+
block([localStatement(randomName5(), junkNumberExpr())])
|
|
863
1164
|
)
|
|
864
1165
|
])
|
|
865
1166
|
];
|
|
@@ -1002,12 +1303,1681 @@ function runInsertJunk(program, options) {
|
|
|
1002
1303
|
function runWrapInFunction(program, _options) {
|
|
1003
1304
|
const innerBody = program.body;
|
|
1004
1305
|
const wrapper = functionExpression(functionBody([], innerBody, true));
|
|
1005
|
-
const
|
|
1006
|
-
program.body = block([returnStatement([
|
|
1306
|
+
const iife3 = call(paren(wrapper), [vararg()]);
|
|
1307
|
+
program.body = block([returnStatement([iife3])]);
|
|
1308
|
+
}
|
|
1309
|
+
|
|
1310
|
+
// src/passes/Vmify.ts
|
|
1311
|
+
import { luauparser as luauparser2 } from "luau-parser";
|
|
1312
|
+
|
|
1313
|
+
// src/passes/vmify/compiler.ts
|
|
1314
|
+
import { luauparser } from "luau-parser";
|
|
1315
|
+
|
|
1316
|
+
// src/passes/vmify/opcodes.ts
|
|
1317
|
+
var Opcode = /* @__PURE__ */ ((Opcode2) => {
|
|
1318
|
+
Opcode2[Opcode2["MOVE"] = 0] = "MOVE";
|
|
1319
|
+
Opcode2[Opcode2["LOADK"] = 1] = "LOADK";
|
|
1320
|
+
Opcode2[Opcode2["LOADBOOL"] = 2] = "LOADBOOL";
|
|
1321
|
+
Opcode2[Opcode2["LOADNIL"] = 3] = "LOADNIL";
|
|
1322
|
+
Opcode2[Opcode2["GETUPVAL"] = 4] = "GETUPVAL";
|
|
1323
|
+
Opcode2[Opcode2["SETUPVAL"] = 5] = "SETUPVAL";
|
|
1324
|
+
Opcode2[Opcode2["GETGLOBAL"] = 6] = "GETGLOBAL";
|
|
1325
|
+
Opcode2[Opcode2["SETGLOBAL"] = 7] = "SETGLOBAL";
|
|
1326
|
+
Opcode2[Opcode2["GETTABLE"] = 8] = "GETTABLE";
|
|
1327
|
+
Opcode2[Opcode2["SETTABLE"] = 9] = "SETTABLE";
|
|
1328
|
+
Opcode2[Opcode2["NEWTABLE"] = 10] = "NEWTABLE";
|
|
1329
|
+
Opcode2[Opcode2["SELF"] = 11] = "SELF";
|
|
1330
|
+
Opcode2[Opcode2["ADD"] = 12] = "ADD";
|
|
1331
|
+
Opcode2[Opcode2["SUB"] = 13] = "SUB";
|
|
1332
|
+
Opcode2[Opcode2["MUL"] = 14] = "MUL";
|
|
1333
|
+
Opcode2[Opcode2["DIV"] = 15] = "DIV";
|
|
1334
|
+
Opcode2[Opcode2["MOD"] = 16] = "MOD";
|
|
1335
|
+
Opcode2[Opcode2["POW"] = 17] = "POW";
|
|
1336
|
+
Opcode2[Opcode2["CONCAT"] = 18] = "CONCAT";
|
|
1337
|
+
Opcode2[Opcode2["UNM"] = 19] = "UNM";
|
|
1338
|
+
Opcode2[Opcode2["NOT"] = 20] = "NOT";
|
|
1339
|
+
Opcode2[Opcode2["LEN"] = 21] = "LEN";
|
|
1340
|
+
Opcode2[Opcode2["JMP"] = 22] = "JMP";
|
|
1341
|
+
Opcode2[Opcode2["EQ"] = 23] = "EQ";
|
|
1342
|
+
Opcode2[Opcode2["LT"] = 24] = "LT";
|
|
1343
|
+
Opcode2[Opcode2["LE"] = 25] = "LE";
|
|
1344
|
+
Opcode2[Opcode2["TEST"] = 26] = "TEST";
|
|
1345
|
+
Opcode2[Opcode2["CALL"] = 27] = "CALL";
|
|
1346
|
+
Opcode2[Opcode2["RETURN"] = 28] = "RETURN";
|
|
1347
|
+
Opcode2[Opcode2["FORPREP"] = 29] = "FORPREP";
|
|
1348
|
+
Opcode2[Opcode2["FORLOOP"] = 30] = "FORLOOP";
|
|
1349
|
+
Opcode2[Opcode2["CLOSURE"] = 31] = "CLOSURE";
|
|
1350
|
+
Opcode2[Opcode2["VARARG"] = 32] = "VARARG";
|
|
1351
|
+
Opcode2[Opcode2["SETLIST"] = 33] = "SETLIST";
|
|
1352
|
+
Opcode2[Opcode2["IDIV"] = 34] = "IDIV";
|
|
1353
|
+
return Opcode2;
|
|
1354
|
+
})(Opcode || {});
|
|
1355
|
+
function RK(regOrConstIdx, isConst) {
|
|
1356
|
+
return isConst ? -(regOrConstIdx + 1) : regOrConstIdx;
|
|
1357
|
+
}
|
|
1358
|
+
var OPCODE_COUNT = Object.keys(Opcode).filter((k) => Number.isNaN(Number(k))).length;
|
|
1359
|
+
function createOpcodeMap(random = Math.random) {
|
|
1360
|
+
const perm = Array.from({ length: OPCODE_COUNT }, (_, i) => i);
|
|
1361
|
+
for (let i = perm.length - 1; i > 0; i--) {
|
|
1362
|
+
const j = Math.floor(random() * (i + 1));
|
|
1363
|
+
const tmp = perm[i];
|
|
1364
|
+
perm[i] = perm[j];
|
|
1365
|
+
perm[j] = tmp;
|
|
1366
|
+
}
|
|
1367
|
+
return perm;
|
|
1368
|
+
}
|
|
1369
|
+
|
|
1370
|
+
// src/passes/vmify/chunk.ts
|
|
1371
|
+
function createProto(id) {
|
|
1372
|
+
return {
|
|
1373
|
+
id,
|
|
1374
|
+
numParams: 0,
|
|
1375
|
+
hasVarargs: false,
|
|
1376
|
+
maxRegs: 0,
|
|
1377
|
+
code: [],
|
|
1378
|
+
consts: [],
|
|
1379
|
+
upvalDescs: [],
|
|
1380
|
+
protos: []
|
|
1381
|
+
};
|
|
1382
|
+
}
|
|
1383
|
+
function internConst(proto, value) {
|
|
1384
|
+
for (let i = 0; i < proto.consts.length; i++) {
|
|
1385
|
+
if (proto.consts[i] === value) return i;
|
|
1386
|
+
}
|
|
1387
|
+
proto.consts.push(value);
|
|
1388
|
+
return proto.consts.length - 1;
|
|
1389
|
+
}
|
|
1390
|
+
|
|
1391
|
+
// src/passes/vmify/registers.ts
|
|
1392
|
+
var RegisterAllocator = class {
|
|
1393
|
+
/** 현재 스코프에서 지역변수가 차지하고 있는, 즉 "보호된" 레지스터 개수. */
|
|
1394
|
+
localCount = 0;
|
|
1395
|
+
/** 다음에 할당할 임시 레지스터 인덱스. */
|
|
1396
|
+
freereg = 0;
|
|
1397
|
+
/** 지금까지 이 함수에서 동시에 살아있었던 최대 레지스터 수(Proto.maxRegs에 기록). */
|
|
1398
|
+
maxUsed = 0;
|
|
1399
|
+
/** 지역변수 하나를 위한 슬롯을 새로 확정한다. 반환값이 그 변수의 레지스터 번호. */
|
|
1400
|
+
declareLocal() {
|
|
1401
|
+
const slot = this.localCount;
|
|
1402
|
+
this.localCount++;
|
|
1403
|
+
if (this.freereg < this.localCount) this.freereg = this.localCount;
|
|
1404
|
+
this.track();
|
|
1405
|
+
return slot;
|
|
1406
|
+
}
|
|
1407
|
+
/** 블록/함수 스코프가 끝날 때, 그 스코프에서 선언된 지역변수 슬롯들을 반납. */
|
|
1408
|
+
releaseLocalsTo(savedLocalCount) {
|
|
1409
|
+
this.localCount = savedLocalCount;
|
|
1410
|
+
this.freereg = savedLocalCount;
|
|
1411
|
+
}
|
|
1412
|
+
saveLocalCount() {
|
|
1413
|
+
return this.localCount;
|
|
1414
|
+
}
|
|
1415
|
+
/** 표현식 평가용 임시 레지스터 하나 할당. */
|
|
1416
|
+
allocTemp() {
|
|
1417
|
+
const r = this.freereg;
|
|
1418
|
+
this.freereg++;
|
|
1419
|
+
this.track();
|
|
1420
|
+
return r;
|
|
1421
|
+
}
|
|
1422
|
+
/**
|
|
1423
|
+
* 임시 레지스터 n개를 반납(freereg를 내림). 지역변수 보호 슬롯 밑으로는
|
|
1424
|
+
* 절대 안 내려가도록 clamp — 호출 순서가 꼬여도 지역변수는 항상 안전.
|
|
1425
|
+
*/
|
|
1426
|
+
freeTemp(toReg) {
|
|
1427
|
+
this.freereg = Math.max(toReg, this.localCount);
|
|
1428
|
+
}
|
|
1429
|
+
/** 지금 이 시점의 freereg. 임시 레지스터 블록 할당 전 저장해뒀다가 freeTemp에 씀. */
|
|
1430
|
+
top() {
|
|
1431
|
+
return this.freereg;
|
|
1432
|
+
}
|
|
1433
|
+
track() {
|
|
1434
|
+
if (this.freereg > this.maxUsed) this.maxUsed = this.freereg;
|
|
1435
|
+
}
|
|
1436
|
+
};
|
|
1437
|
+
|
|
1438
|
+
// src/passes/vmify/scope-walk.ts
|
|
1439
|
+
function buildEnclosingFunctionMap(program) {
|
|
1440
|
+
const ownerOf = /* @__PURE__ */ new Map();
|
|
1441
|
+
const parentOf = /* @__PURE__ */ new Map();
|
|
1442
|
+
const topMarker = { tag: "top" };
|
|
1443
|
+
parentOf.set(topMarker, void 0);
|
|
1444
|
+
function mark(node, fn) {
|
|
1445
|
+
ownerOf.set(node, fn);
|
|
1446
|
+
}
|
|
1447
|
+
function walkBlock2(block2, fn) {
|
|
1448
|
+
for (const stmt of block2.statements) walkStatement2(stmt, fn);
|
|
1449
|
+
}
|
|
1450
|
+
function walkFunctionBody2(fb, parent) {
|
|
1451
|
+
const self = { tag: "fn", node: fb };
|
|
1452
|
+
parentOf.set(self, parent);
|
|
1453
|
+
mark(fb, self);
|
|
1454
|
+
for (const p of fb.params) mark(p, self);
|
|
1455
|
+
walkBlock2(fb.body, self);
|
|
1456
|
+
}
|
|
1457
|
+
function walkExpr(expr, fn) {
|
|
1458
|
+
mark(expr, fn);
|
|
1459
|
+
switch (expr.type) {
|
|
1460
|
+
case "Identifier":
|
|
1461
|
+
mark(expr, fn);
|
|
1462
|
+
break;
|
|
1463
|
+
case "InterpolatedStringExpression":
|
|
1464
|
+
for (const part of expr.parts) if (part.kind === "expression") walkExpr(part.expression, fn);
|
|
1465
|
+
break;
|
|
1466
|
+
case "FunctionExpression":
|
|
1467
|
+
walkFunctionBody2(expr.func, fn);
|
|
1468
|
+
break;
|
|
1469
|
+
case "TableExpression":
|
|
1470
|
+
for (const field of expr.fields) {
|
|
1471
|
+
if (field.type === "TableFieldPositional") walkExpr(field.value, fn);
|
|
1472
|
+
else if (field.type === "TableFieldNamed") walkExpr(field.value, fn);
|
|
1473
|
+
else {
|
|
1474
|
+
walkExpr(field.key, fn);
|
|
1475
|
+
walkExpr(field.value, fn);
|
|
1476
|
+
}
|
|
1477
|
+
}
|
|
1478
|
+
break;
|
|
1479
|
+
case "BinaryExpression":
|
|
1480
|
+
walkExpr(expr.left, fn);
|
|
1481
|
+
walkExpr(expr.right, fn);
|
|
1482
|
+
break;
|
|
1483
|
+
case "UnaryExpression":
|
|
1484
|
+
walkExpr(expr.argument, fn);
|
|
1485
|
+
break;
|
|
1486
|
+
case "MemberExpression":
|
|
1487
|
+
walkExpr(expr.object, fn);
|
|
1488
|
+
break;
|
|
1489
|
+
case "IndexExpression":
|
|
1490
|
+
walkExpr(expr.object, fn);
|
|
1491
|
+
walkExpr(expr.index, fn);
|
|
1492
|
+
break;
|
|
1493
|
+
case "CallExpression":
|
|
1494
|
+
walkExpr(expr.callee, fn);
|
|
1495
|
+
for (const a of expr.arguments) walkExpr(a, fn);
|
|
1496
|
+
break;
|
|
1497
|
+
case "MethodCallExpression":
|
|
1498
|
+
walkExpr(expr.object, fn);
|
|
1499
|
+
for (const a of expr.arguments) walkExpr(a, fn);
|
|
1500
|
+
break;
|
|
1501
|
+
case "ParenthesizedExpression":
|
|
1502
|
+
case "TypeAssertionExpression":
|
|
1503
|
+
walkExpr(expr.expression, fn);
|
|
1504
|
+
break;
|
|
1505
|
+
case "IfElseExpression":
|
|
1506
|
+
for (const c of expr.clauses) {
|
|
1507
|
+
walkExpr(c.condition, fn);
|
|
1508
|
+
walkExpr(c.body, fn);
|
|
1509
|
+
}
|
|
1510
|
+
walkExpr(expr.alternate, fn);
|
|
1511
|
+
break;
|
|
1512
|
+
}
|
|
1513
|
+
}
|
|
1514
|
+
function walkStatement2(stmt, fn) {
|
|
1515
|
+
mark(stmt, fn);
|
|
1516
|
+
switch (stmt.type) {
|
|
1517
|
+
case "LocalStatement":
|
|
1518
|
+
for (const n of stmt.names) mark(n, fn);
|
|
1519
|
+
for (const e of stmt.init) walkExpr(e, fn);
|
|
1520
|
+
return;
|
|
1521
|
+
case "LocalFunctionStatement":
|
|
1522
|
+
mark(stmt.name, fn);
|
|
1523
|
+
walkFunctionBody2(stmt.func, fn);
|
|
1524
|
+
return;
|
|
1525
|
+
case "FunctionDeclarationStatement":
|
|
1526
|
+
mark(stmt.target.base, fn);
|
|
1527
|
+
walkFunctionBody2(stmt.func, fn);
|
|
1528
|
+
return;
|
|
1529
|
+
case "AssignmentStatement":
|
|
1530
|
+
for (const t of stmt.targets) walkExpr(t, fn);
|
|
1531
|
+
for (const v of stmt.values) walkExpr(v, fn);
|
|
1532
|
+
return;
|
|
1533
|
+
case "CompoundAssignmentStatement":
|
|
1534
|
+
walkExpr(stmt.target, fn);
|
|
1535
|
+
walkExpr(stmt.value, fn);
|
|
1536
|
+
return;
|
|
1537
|
+
case "CallStatement":
|
|
1538
|
+
walkExpr(stmt.expression, fn);
|
|
1539
|
+
return;
|
|
1540
|
+
case "DoStatement":
|
|
1541
|
+
walkBlock2(stmt.body, fn);
|
|
1542
|
+
return;
|
|
1543
|
+
case "WhileStatement":
|
|
1544
|
+
walkExpr(stmt.condition, fn);
|
|
1545
|
+
walkBlock2(stmt.body, fn);
|
|
1546
|
+
return;
|
|
1547
|
+
case "RepeatStatement":
|
|
1548
|
+
walkBlock2(stmt.body, fn);
|
|
1549
|
+
walkExpr(stmt.condition, fn);
|
|
1550
|
+
return;
|
|
1551
|
+
case "IfStatement":
|
|
1552
|
+
for (const c of stmt.clauses) {
|
|
1553
|
+
walkExpr(c.condition, fn);
|
|
1554
|
+
walkBlock2(c.body, fn);
|
|
1555
|
+
}
|
|
1556
|
+
if (stmt.alternate) walkBlock2(stmt.alternate, fn);
|
|
1557
|
+
return;
|
|
1558
|
+
case "NumericForStatement":
|
|
1559
|
+
mark(stmt.variable, fn);
|
|
1560
|
+
walkExpr(stmt.start, fn);
|
|
1561
|
+
walkExpr(stmt.end, fn);
|
|
1562
|
+
if (stmt.step) walkExpr(stmt.step, fn);
|
|
1563
|
+
walkBlock2(stmt.body, fn);
|
|
1564
|
+
return;
|
|
1565
|
+
case "GenericForStatement":
|
|
1566
|
+
for (const v of stmt.variables) mark(v, fn);
|
|
1567
|
+
for (const it of stmt.iterators) walkExpr(it, fn);
|
|
1568
|
+
walkBlock2(stmt.body, fn);
|
|
1569
|
+
return;
|
|
1570
|
+
case "ReturnStatement":
|
|
1571
|
+
for (const a of stmt.arguments) walkExpr(a, fn);
|
|
1572
|
+
return;
|
|
1573
|
+
default:
|
|
1574
|
+
return;
|
|
1575
|
+
}
|
|
1576
|
+
}
|
|
1577
|
+
walkBlock2(program.body, topMarker);
|
|
1578
|
+
return { ownerOf, parentOf, topMarker };
|
|
1579
|
+
}
|
|
1580
|
+
function ownerFunctionOf(map, node) {
|
|
1581
|
+
const fn = map.ownerOf.get(node);
|
|
1582
|
+
if (!fn) throw new Error("scope-walk: node was not visited \u2014 walker/compiler are out of sync");
|
|
1583
|
+
return fn;
|
|
1584
|
+
}
|
|
1585
|
+
|
|
1586
|
+
// src/passes/vmify/compiler.ts
|
|
1587
|
+
var BOX_FIELD = "v";
|
|
1588
|
+
var DEFAULT_BUILTIN_GLOBALS = [
|
|
1589
|
+
"game",
|
|
1590
|
+
"script",
|
|
1591
|
+
"workspace",
|
|
1592
|
+
"print",
|
|
1593
|
+
"warn",
|
|
1594
|
+
"error",
|
|
1595
|
+
"pairs",
|
|
1596
|
+
"ipairs",
|
|
1597
|
+
"pcall",
|
|
1598
|
+
"xpcall",
|
|
1599
|
+
"type",
|
|
1600
|
+
"typeof",
|
|
1601
|
+
"tostring",
|
|
1602
|
+
"tonumber",
|
|
1603
|
+
"select",
|
|
1604
|
+
"unpack",
|
|
1605
|
+
"table",
|
|
1606
|
+
"string",
|
|
1607
|
+
"math",
|
|
1608
|
+
"os",
|
|
1609
|
+
"task",
|
|
1610
|
+
"Instance",
|
|
1611
|
+
"Vector3",
|
|
1612
|
+
"CFrame",
|
|
1613
|
+
"Color3",
|
|
1614
|
+
"require",
|
|
1615
|
+
"setmetatable",
|
|
1616
|
+
"getmetatable",
|
|
1617
|
+
"rawget",
|
|
1618
|
+
"rawset",
|
|
1619
|
+
"rawequal",
|
|
1620
|
+
"next"
|
|
1621
|
+
];
|
|
1622
|
+
var VmCompiler = class {
|
|
1623
|
+
constructor(program, builtinGlobals = DEFAULT_BUILTIN_GLOBALS, opcodeMap) {
|
|
1624
|
+
this.program = program;
|
|
1625
|
+
this.opcodeMap = opcodeMap;
|
|
1626
|
+
this.analysis = luauparser.analyzeScopes(program, { builtinGlobals });
|
|
1627
|
+
this.enclosing = buildEnclosingFunctionMap(program);
|
|
1628
|
+
for (const [id, binding] of this.analysis.bindings) {
|
|
1629
|
+
if (binding.declarationNode) this.declToBinding.set(binding.declarationNode, id);
|
|
1630
|
+
}
|
|
1631
|
+
this.computeCaptured();
|
|
1632
|
+
}
|
|
1633
|
+
program;
|
|
1634
|
+
opcodeMap;
|
|
1635
|
+
analysis;
|
|
1636
|
+
enclosing;
|
|
1637
|
+
captured = /* @__PURE__ */ new Set();
|
|
1638
|
+
protoIdCounter = 0;
|
|
1639
|
+
declToBinding = /* @__PURE__ */ new Map();
|
|
1640
|
+
computeCaptured() {
|
|
1641
|
+
for (const binding of this.analysis.bindings.values()) {
|
|
1642
|
+
if (binding.kind === "global") continue;
|
|
1643
|
+
if (!binding.declarationNode) continue;
|
|
1644
|
+
const ownerFn = ownerFunctionOf(this.enclosing, binding.declarationNode);
|
|
1645
|
+
for (const ref of binding.references) {
|
|
1646
|
+
const refFn = ownerFunctionOf(this.enclosing, ref);
|
|
1647
|
+
if (refFn !== ownerFn) {
|
|
1648
|
+
this.captured.add(binding.id);
|
|
1649
|
+
break;
|
|
1650
|
+
}
|
|
1651
|
+
}
|
|
1652
|
+
}
|
|
1653
|
+
}
|
|
1654
|
+
compile() {
|
|
1655
|
+
const top = this.newFuncState(void 0, this.enclosing.topMarker);
|
|
1656
|
+
top.proto.hasVarargs = true;
|
|
1657
|
+
this.compileBlock(this.program.body, top);
|
|
1658
|
+
this.emit(top, 28 /* RETURN */, 0, 1, 0);
|
|
1659
|
+
top.proto.maxRegs = top.regs.maxUsed;
|
|
1660
|
+
return top.proto;
|
|
1661
|
+
}
|
|
1662
|
+
newFuncState(parent, marker) {
|
|
1663
|
+
return {
|
|
1664
|
+
proto: createProto(this.protoIdCounter++),
|
|
1665
|
+
parent,
|
|
1666
|
+
marker,
|
|
1667
|
+
regs: new RegisterAllocator(),
|
|
1668
|
+
localSlots: /* @__PURE__ */ new Map(),
|
|
1669
|
+
upvalIndexByBinding: /* @__PURE__ */ new Map(),
|
|
1670
|
+
breakPatchStack: [],
|
|
1671
|
+
continuePatchStack: []
|
|
1672
|
+
};
|
|
1673
|
+
}
|
|
1674
|
+
emit(state, op, a, b, c, comment) {
|
|
1675
|
+
const physicalOp = this.opcodeMap ? this.opcodeMap[op] : op;
|
|
1676
|
+
state.proto.code.push({ op: physicalOp, a, b, c, comment });
|
|
1677
|
+
return state.proto.code.length - 1;
|
|
1678
|
+
}
|
|
1679
|
+
konst(state, value) {
|
|
1680
|
+
return internConst(state.proto, value);
|
|
1681
|
+
}
|
|
1682
|
+
bindingIdOf(node) {
|
|
1683
|
+
return this.analysis.bindingOf.get(node);
|
|
1684
|
+
}
|
|
1685
|
+
getOrCreateUpval(state, bindingId) {
|
|
1686
|
+
const existing = state.upvalIndexByBinding.get(bindingId);
|
|
1687
|
+
if (existing !== void 0) return existing;
|
|
1688
|
+
const parent = state.parent;
|
|
1689
|
+
if (!parent) throw new Error("vmify: binding not found in any enclosing function (compiler bug)");
|
|
1690
|
+
const parentLocal = parent.localSlots.get(bindingId);
|
|
1691
|
+
const idx = state.proto.upvalDescs.length;
|
|
1692
|
+
if (parentLocal) {
|
|
1693
|
+
state.proto.upvalDescs.push({ kind: "local", index: parentLocal.reg });
|
|
1694
|
+
} else {
|
|
1695
|
+
const parentUpvalIdx = this.getOrCreateUpval(parent, bindingId);
|
|
1696
|
+
state.proto.upvalDescs.push({ kind: "upval", index: parentUpvalIdx });
|
|
1697
|
+
}
|
|
1698
|
+
state.upvalIndexByBinding.set(bindingId, idx);
|
|
1699
|
+
return idx;
|
|
1700
|
+
}
|
|
1701
|
+
bindingIsLocalSomewhereUp(state, bindingId) {
|
|
1702
|
+
let s = state;
|
|
1703
|
+
while (s) {
|
|
1704
|
+
if (s.localSlots.has(bindingId)) return true;
|
|
1705
|
+
s = s.parent;
|
|
1706
|
+
}
|
|
1707
|
+
return false;
|
|
1708
|
+
}
|
|
1709
|
+
declareLocalBinding(state, bindingId) {
|
|
1710
|
+
const reg = state.regs.declareLocal();
|
|
1711
|
+
state.localSlots.set(bindingId, { reg, boxed: this.captured.has(bindingId) });
|
|
1712
|
+
if (this.captured.has(bindingId)) this.emitNewBox(state, reg);
|
|
1713
|
+
return reg;
|
|
1714
|
+
}
|
|
1715
|
+
emitNewBox(state, reg) {
|
|
1716
|
+
this.emit(state, 10 /* NEWTABLE */, reg, 0, 0, "box");
|
|
1717
|
+
}
|
|
1718
|
+
emitLoadBinding(state, bindingId, dest) {
|
|
1719
|
+
const local = state.localSlots.get(bindingId);
|
|
1720
|
+
if (local) {
|
|
1721
|
+
if (local.boxed) {
|
|
1722
|
+
const k = this.konst(state, BOX_FIELD);
|
|
1723
|
+
this.emit(state, 8 /* GETTABLE */, dest, local.reg, RK(k, true));
|
|
1724
|
+
} else if (dest !== local.reg) {
|
|
1725
|
+
this.emit(state, 0 /* MOVE */, dest, local.reg, 0);
|
|
1726
|
+
}
|
|
1727
|
+
return;
|
|
1728
|
+
}
|
|
1729
|
+
if (this.bindingIsLocalSomewhereUp(state, bindingId)) {
|
|
1730
|
+
const idx = this.getOrCreateUpval(state, bindingId);
|
|
1731
|
+
this.emit(state, 4 /* GETUPVAL */, dest, idx, 0);
|
|
1732
|
+
const k = this.konst(state, BOX_FIELD);
|
|
1733
|
+
this.emit(state, 8 /* GETTABLE */, dest, dest, RK(k, true));
|
|
1734
|
+
return;
|
|
1735
|
+
}
|
|
1736
|
+
const binding = this.analysis.bindings.get(bindingId);
|
|
1737
|
+
const nameIdx = this.konst(state, binding.name);
|
|
1738
|
+
this.emit(state, 6 /* GETGLOBAL */, dest, nameIdx, 0);
|
|
1739
|
+
}
|
|
1740
|
+
emitStoreBinding(state, bindingId, src) {
|
|
1741
|
+
const local = state.localSlots.get(bindingId);
|
|
1742
|
+
if (local) {
|
|
1743
|
+
if (local.boxed) {
|
|
1744
|
+
const k = this.konst(state, BOX_FIELD);
|
|
1745
|
+
this.emit(state, 9 /* SETTABLE */, local.reg, RK(k, true), src);
|
|
1746
|
+
} else if (src !== local.reg) {
|
|
1747
|
+
this.emit(state, 0 /* MOVE */, local.reg, src, 0);
|
|
1748
|
+
}
|
|
1749
|
+
return;
|
|
1750
|
+
}
|
|
1751
|
+
if (this.bindingIsLocalSomewhereUp(state, bindingId)) {
|
|
1752
|
+
const idx = this.getOrCreateUpval(state, bindingId);
|
|
1753
|
+
const tmp = state.regs.allocTemp();
|
|
1754
|
+
this.emit(state, 4 /* GETUPVAL */, tmp, idx, 0);
|
|
1755
|
+
const k = this.konst(state, BOX_FIELD);
|
|
1756
|
+
this.emit(state, 9 /* SETTABLE */, tmp, RK(k, true), src);
|
|
1757
|
+
state.regs.freeTemp(tmp);
|
|
1758
|
+
return;
|
|
1759
|
+
}
|
|
1760
|
+
const binding = this.analysis.bindings.get(bindingId);
|
|
1761
|
+
const nameIdx = this.konst(state, binding.name);
|
|
1762
|
+
this.emit(state, 7 /* SETGLOBAL */, src, nameIdx, 0);
|
|
1763
|
+
}
|
|
1764
|
+
compileBlock(block2, state) {
|
|
1765
|
+
const saved = state.regs.saveLocalCount();
|
|
1766
|
+
for (const stmt of block2.statements) this.compileStatement(stmt, state);
|
|
1767
|
+
state.regs.releaseLocalsTo(saved);
|
|
1768
|
+
}
|
|
1769
|
+
compileStatement(stmt, state) {
|
|
1770
|
+
switch (stmt.type) {
|
|
1771
|
+
case "LocalStatement": {
|
|
1772
|
+
const bindingIds = stmt.names.map((n) => this.bindingIdOfDecl(n));
|
|
1773
|
+
for (const id of bindingIds) this.declareLocalBinding(state, id);
|
|
1774
|
+
const boundary = state.regs.top();
|
|
1775
|
+
let filledUpTo = 0;
|
|
1776
|
+
if (stmt.init.length > 0) {
|
|
1777
|
+
for (let i = 0; i < stmt.init.length - 1; i++) {
|
|
1778
|
+
this.compileExprTo(stmt.init[i], state, boundary + i);
|
|
1779
|
+
}
|
|
1780
|
+
const lastIdx = stmt.init.length - 1;
|
|
1781
|
+
const remaining = Math.max(bindingIds.length - lastIdx, 1);
|
|
1782
|
+
this.compileExprMultiInto(stmt.init[lastIdx], state, boundary + lastIdx, remaining);
|
|
1783
|
+
filledUpTo = lastIdx + remaining;
|
|
1784
|
+
}
|
|
1785
|
+
for (let i = filledUpTo; i < bindingIds.length; i++) {
|
|
1786
|
+
this.emit(state, 3 /* LOADNIL */, boundary + i, boundary + i, 0);
|
|
1787
|
+
}
|
|
1788
|
+
for (let i = 0; i < bindingIds.length; i++) {
|
|
1789
|
+
this.emitStoreBinding(state, bindingIds[i], boundary + i);
|
|
1790
|
+
}
|
|
1791
|
+
state.regs.freeTemp(boundary);
|
|
1792
|
+
return;
|
|
1793
|
+
}
|
|
1794
|
+
case "AssignmentStatement": {
|
|
1795
|
+
const valueRegs = stmt.values.map((e) => this.compileExpr(e, state));
|
|
1796
|
+
stmt.targets.forEach((target, i) => {
|
|
1797
|
+
const srcReg = valueRegs[i] ?? valueRegs[valueRegs.length - 1];
|
|
1798
|
+
this.compileAssignTarget(target, srcReg, state);
|
|
1799
|
+
});
|
|
1800
|
+
return;
|
|
1801
|
+
}
|
|
1802
|
+
case "CompoundAssignmentStatement":
|
|
1803
|
+
this.compileCompoundAssignment(stmt, state);
|
|
1804
|
+
return;
|
|
1805
|
+
case "CallStatement":
|
|
1806
|
+
this.compileExpr(stmt.expression, state, true);
|
|
1807
|
+
return;
|
|
1808
|
+
case "IfStatement":
|
|
1809
|
+
this.compileIf(stmt, state);
|
|
1810
|
+
return;
|
|
1811
|
+
case "WhileStatement":
|
|
1812
|
+
this.compileWhile(stmt, state);
|
|
1813
|
+
return;
|
|
1814
|
+
case "RepeatStatement":
|
|
1815
|
+
this.compileRepeat(stmt, state);
|
|
1816
|
+
return;
|
|
1817
|
+
case "NumericForStatement":
|
|
1818
|
+
this.compileNumericFor(stmt, state);
|
|
1819
|
+
return;
|
|
1820
|
+
case "GenericForStatement":
|
|
1821
|
+
this.compileGenericFor(stmt, state);
|
|
1822
|
+
return;
|
|
1823
|
+
case "DoStatement":
|
|
1824
|
+
this.compileBlock(stmt.body, state);
|
|
1825
|
+
return;
|
|
1826
|
+
case "ReturnStatement": {
|
|
1827
|
+
if (stmt.arguments.length === 0) {
|
|
1828
|
+
this.emit(state, 28 /* RETURN */, state.regs.top(), 1, 0);
|
|
1829
|
+
return;
|
|
1830
|
+
}
|
|
1831
|
+
if (stmt.arguments.length === 1 && this.isMultiValueExpr(stmt.arguments[0])) {
|
|
1832
|
+
const base = state.regs.top();
|
|
1833
|
+
this.compileExprOpenInto(stmt.arguments[0], state, base);
|
|
1834
|
+
this.emit(state, 28 /* RETURN */, base, 0, 0);
|
|
1835
|
+
state.regs.freeTemp(base);
|
|
1836
|
+
return;
|
|
1837
|
+
}
|
|
1838
|
+
const boundary = state.regs.top();
|
|
1839
|
+
for (let i = 0; i < stmt.arguments.length - 1; i++) {
|
|
1840
|
+
this.compileExprTo(stmt.arguments[i], state, boundary + i);
|
|
1841
|
+
}
|
|
1842
|
+
const lastIdx = stmt.arguments.length - 1;
|
|
1843
|
+
if (this.isMultiValueExpr(stmt.arguments[lastIdx])) {
|
|
1844
|
+
this.compileExprOpenInto(stmt.arguments[lastIdx], state, boundary + lastIdx);
|
|
1845
|
+
this.emit(state, 28 /* RETURN */, boundary, 0, 0);
|
|
1846
|
+
} else {
|
|
1847
|
+
this.compileExprTo(stmt.arguments[lastIdx], state, boundary + lastIdx);
|
|
1848
|
+
this.emit(state, 28 /* RETURN */, boundary, stmt.arguments.length + 1, 0);
|
|
1849
|
+
}
|
|
1850
|
+
state.regs.freeTemp(boundary);
|
|
1851
|
+
return;
|
|
1852
|
+
}
|
|
1853
|
+
case "LocalFunctionStatement": {
|
|
1854
|
+
const bindingId = this.bindingIdOfDecl(stmt.name);
|
|
1855
|
+
const reg = this.declareLocalBinding(state, bindingId);
|
|
1856
|
+
const protoIdx = this.compileFunctionBody(stmt.func, state);
|
|
1857
|
+
const boxed = state.localSlots.get(bindingId).boxed;
|
|
1858
|
+
if (boxed) {
|
|
1859
|
+
const tmp = state.regs.allocTemp();
|
|
1860
|
+
this.emitClosure(state, tmp, protoIdx);
|
|
1861
|
+
this.emitStoreBinding(state, bindingId, tmp);
|
|
1862
|
+
state.regs.freeTemp(tmp);
|
|
1863
|
+
} else {
|
|
1864
|
+
this.emitClosure(state, reg, protoIdx);
|
|
1865
|
+
}
|
|
1866
|
+
return;
|
|
1867
|
+
}
|
|
1868
|
+
case "FunctionDeclarationStatement":
|
|
1869
|
+
this.compileFunctionDeclaration(stmt, state);
|
|
1870
|
+
return;
|
|
1871
|
+
case "BreakStatement": {
|
|
1872
|
+
if (state.breakPatchStack.length === 0) throw new Error("vmify: break outside loop");
|
|
1873
|
+
const idx = this.emit(state, 22 /* JMP */, 0, 0, 0, "break");
|
|
1874
|
+
state.breakPatchStack[state.breakPatchStack.length - 1].push(idx);
|
|
1875
|
+
return;
|
|
1876
|
+
}
|
|
1877
|
+
case "ContinueStatement": {
|
|
1878
|
+
if (state.continuePatchStack.length === 0) throw new Error("vmify: continue outside loop");
|
|
1879
|
+
const idx = this.emit(state, 22 /* JMP */, 0, 0, 0, "continue");
|
|
1880
|
+
state.continuePatchStack[state.continuePatchStack.length - 1].push(idx);
|
|
1881
|
+
return;
|
|
1882
|
+
}
|
|
1883
|
+
case "TypeAliasStatement":
|
|
1884
|
+
case "ExportTypeAliasStatement":
|
|
1885
|
+
return;
|
|
1886
|
+
default: {
|
|
1887
|
+
const _exhaustive = stmt;
|
|
1888
|
+
throw new Error(`vmify: unhandled statement ${_exhaustive.type}`);
|
|
1889
|
+
}
|
|
1890
|
+
}
|
|
1891
|
+
}
|
|
1892
|
+
compileAssignTarget(target, srcReg, state) {
|
|
1893
|
+
if (target.type === "Identifier") {
|
|
1894
|
+
const bindingId = this.bindingIdOf(target);
|
|
1895
|
+
if (bindingId === void 0) throw new Error("vmify: unresolved identifier target");
|
|
1896
|
+
this.emitStoreBinding(state, bindingId, srcReg);
|
|
1897
|
+
return;
|
|
1898
|
+
}
|
|
1899
|
+
if (target.type === "MemberExpression") {
|
|
1900
|
+
const objReg = this.compileExpr(target.object, state);
|
|
1901
|
+
const k = this.konst(state, target.property.name);
|
|
1902
|
+
this.emit(state, 9 /* SETTABLE */, objReg, RK(k, true), srcReg);
|
|
1903
|
+
state.regs.freeTemp(objReg);
|
|
1904
|
+
return;
|
|
1905
|
+
}
|
|
1906
|
+
if (target.type === "IndexExpression") {
|
|
1907
|
+
const objReg = this.compileExpr(target.object, state);
|
|
1908
|
+
const keyReg = this.compileExpr(target.index, state);
|
|
1909
|
+
this.emit(state, 9 /* SETTABLE */, objReg, keyReg, srcReg);
|
|
1910
|
+
state.regs.freeTemp(objReg);
|
|
1911
|
+
return;
|
|
1912
|
+
}
|
|
1913
|
+
throw new Error(`vmify: unsupported assignment target ${target.type}`);
|
|
1914
|
+
}
|
|
1915
|
+
compileCompoundAssignment(stmt, state) {
|
|
1916
|
+
const opMap = {
|
|
1917
|
+
"+=": 12 /* ADD */,
|
|
1918
|
+
"-=": 13 /* SUB */,
|
|
1919
|
+
"*=": 14 /* MUL */,
|
|
1920
|
+
"/=": 15 /* DIV */,
|
|
1921
|
+
"//=": 34 /* IDIV */,
|
|
1922
|
+
"%=": 16 /* MOD */,
|
|
1923
|
+
"^=": 17 /* POW */,
|
|
1924
|
+
"..=": 18 /* CONCAT */
|
|
1925
|
+
};
|
|
1926
|
+
const op = opMap[stmt.operator];
|
|
1927
|
+
if (!op) throw new Error(`vmify: unsupported compound operator ${stmt.operator}`);
|
|
1928
|
+
const target = stmt.target;
|
|
1929
|
+
if (target.type === "Identifier") {
|
|
1930
|
+
const bindingId = this.bindingIdOf(target);
|
|
1931
|
+
if (bindingId === void 0) throw new Error("vmify: unresolved identifier target");
|
|
1932
|
+
const cur = state.regs.allocTemp();
|
|
1933
|
+
this.emitLoadBinding(state, bindingId, cur);
|
|
1934
|
+
const rhs = this.compileExpr(stmt.value, state);
|
|
1935
|
+
this.emit(state, op, cur, cur, rhs);
|
|
1936
|
+
state.regs.freeTemp(rhs);
|
|
1937
|
+
this.emitStoreBinding(state, bindingId, cur);
|
|
1938
|
+
state.regs.freeTemp(cur);
|
|
1939
|
+
return;
|
|
1940
|
+
}
|
|
1941
|
+
if (target.type === "MemberExpression") {
|
|
1942
|
+
const objReg = this.compileExpr(target.object, state);
|
|
1943
|
+
const k = this.konst(state, target.property.name);
|
|
1944
|
+
const cur = state.regs.allocTemp();
|
|
1945
|
+
this.emit(state, 8 /* GETTABLE */, cur, objReg, RK(k, true));
|
|
1946
|
+
const rhs = this.compileExpr(stmt.value, state);
|
|
1947
|
+
this.emit(state, op, cur, cur, rhs);
|
|
1948
|
+
this.emit(state, 9 /* SETTABLE */, objReg, RK(k, true), cur);
|
|
1949
|
+
state.regs.freeTemp(objReg);
|
|
1950
|
+
return;
|
|
1951
|
+
}
|
|
1952
|
+
if (target.type === "IndexExpression") {
|
|
1953
|
+
const objReg = this.compileExpr(target.object, state);
|
|
1954
|
+
const keyReg = this.compileExpr(target.index, state);
|
|
1955
|
+
const cur = state.regs.allocTemp();
|
|
1956
|
+
this.emit(state, 8 /* GETTABLE */, cur, objReg, keyReg);
|
|
1957
|
+
const rhs = this.compileExpr(stmt.value, state);
|
|
1958
|
+
this.emit(state, op, cur, cur, rhs);
|
|
1959
|
+
this.emit(state, 9 /* SETTABLE */, objReg, keyReg, cur);
|
|
1960
|
+
state.regs.freeTemp(objReg);
|
|
1961
|
+
return;
|
|
1962
|
+
}
|
|
1963
|
+
throw new Error(`vmify: unsupported compound assignment target ${target.type}`);
|
|
1964
|
+
}
|
|
1965
|
+
compileFunctionDeclaration(stmt, state) {
|
|
1966
|
+
const protoIdx = this.compileFunctionBody(stmt.func, state);
|
|
1967
|
+
const fnReg = state.regs.allocTemp();
|
|
1968
|
+
this.emitClosure(state, fnReg, protoIdx);
|
|
1969
|
+
const target = stmt.target;
|
|
1970
|
+
if (target.path.length === 0 && !target.method) {
|
|
1971
|
+
const bindingId = this.bindingIdOf(target.base);
|
|
1972
|
+
if (bindingId === void 0) throw new Error("vmify: unresolved function name");
|
|
1973
|
+
this.emitStoreBinding(state, bindingId, fnReg);
|
|
1974
|
+
state.regs.freeTemp(fnReg);
|
|
1975
|
+
return;
|
|
1976
|
+
}
|
|
1977
|
+
const baseBindingId = this.bindingIdOf(target.base);
|
|
1978
|
+
if (baseBindingId === void 0) throw new Error("vmify: unresolved function name base");
|
|
1979
|
+
let objReg = state.regs.allocTemp();
|
|
1980
|
+
this.emitLoadBinding(state, baseBindingId, objReg);
|
|
1981
|
+
const navigateSegments = target.method ? target.path : target.path.slice(0, -1);
|
|
1982
|
+
for (const seg of navigateSegments) {
|
|
1983
|
+
const k2 = this.konst(state, seg.name);
|
|
1984
|
+
const next = state.regs.allocTemp();
|
|
1985
|
+
this.emit(state, 8 /* GETTABLE */, next, objReg, RK(k2, true));
|
|
1986
|
+
objReg = next;
|
|
1987
|
+
}
|
|
1988
|
+
const finalKeyName = target.method ? target.method.name : target.path[target.path.length - 1].name;
|
|
1989
|
+
const k = this.konst(state, finalKeyName);
|
|
1990
|
+
this.emit(state, 9 /* SETTABLE */, objReg, RK(k, true), fnReg);
|
|
1991
|
+
state.regs.freeTemp(fnReg);
|
|
1992
|
+
}
|
|
1993
|
+
compileIf(stmt, state) {
|
|
1994
|
+
const endPatches = [];
|
|
1995
|
+
for (const clause of stmt.clauses) {
|
|
1996
|
+
const condReg = this.compileExpr(clause.condition, state);
|
|
1997
|
+
this.emit(state, 26 /* TEST */, condReg, 0, 1);
|
|
1998
|
+
const jmpOverBody = this.emit(state, 22 /* JMP */, 0, 0, 0, "skip-then");
|
|
1999
|
+
state.regs.freeTemp(condReg);
|
|
2000
|
+
this.compileBlock(clause.body, state);
|
|
2001
|
+
const jmpToEnd = this.emit(state, 22 /* JMP */, 0, 0, 0, "then->end");
|
|
2002
|
+
endPatches.push(jmpToEnd);
|
|
2003
|
+
this.patchJump(state, jmpOverBody, state.proto.code.length);
|
|
2004
|
+
}
|
|
2005
|
+
if (stmt.alternate) this.compileBlock(stmt.alternate, state);
|
|
2006
|
+
for (const p of endPatches) this.patchJump(state, p, state.proto.code.length);
|
|
2007
|
+
}
|
|
2008
|
+
compileWhile(stmt, state) {
|
|
2009
|
+
const loopStart = state.proto.code.length;
|
|
2010
|
+
const condReg = this.compileExpr(stmt.condition, state);
|
|
2011
|
+
this.emit(state, 26 /* TEST */, condReg, 0, 1);
|
|
2012
|
+
const exitJmp = this.emit(state, 22 /* JMP */, 0, 0, 0, "while-exit");
|
|
2013
|
+
state.regs.freeTemp(condReg);
|
|
2014
|
+
state.breakPatchStack.push([]);
|
|
2015
|
+
state.continuePatchStack.push([]);
|
|
2016
|
+
this.compileBlock(stmt.body, state);
|
|
2017
|
+
this.emit(state, 22 /* JMP */, loopStart - state.proto.code.length, 0, 0, "while-back");
|
|
2018
|
+
const target = state.proto.code.length;
|
|
2019
|
+
this.patchJump(state, exitJmp, target);
|
|
2020
|
+
for (const b of state.breakPatchStack.pop()) this.patchJump(state, b, target);
|
|
2021
|
+
for (const c of state.continuePatchStack.pop()) this.patchJump(state, c, loopStart);
|
|
2022
|
+
}
|
|
2023
|
+
compileRepeat(stmt, state) {
|
|
2024
|
+
const loopStart = state.proto.code.length;
|
|
2025
|
+
state.breakPatchStack.push([]);
|
|
2026
|
+
state.continuePatchStack.push([]);
|
|
2027
|
+
const saved = state.regs.saveLocalCount();
|
|
2028
|
+
for (const s of stmt.body.statements) this.compileStatement(s, state);
|
|
2029
|
+
const condCheckStart = state.proto.code.length;
|
|
2030
|
+
const condReg = this.compileExpr(stmt.condition, state);
|
|
2031
|
+
this.emit(state, 26 /* TEST */, condReg, 0, 1);
|
|
2032
|
+
const jmpBack = this.emit(state, 22 /* JMP */, 0, 0, 0, "repeat-back");
|
|
2033
|
+
state.regs.freeTemp(condReg);
|
|
2034
|
+
this.patchJump(state, jmpBack, loopStart);
|
|
2035
|
+
state.regs.releaseLocalsTo(saved);
|
|
2036
|
+
const endIdx = state.proto.code.length;
|
|
2037
|
+
for (const b of state.breakPatchStack.pop()) this.patchJump(state, b, endIdx);
|
|
2038
|
+
for (const c of state.continuePatchStack.pop()) this.patchJump(state, c, condCheckStart);
|
|
2039
|
+
}
|
|
2040
|
+
compileNumericFor(stmt, state) {
|
|
2041
|
+
const saved = state.regs.saveLocalCount();
|
|
2042
|
+
const base = state.regs.declareLocal();
|
|
2043
|
+
state.regs.declareLocal();
|
|
2044
|
+
state.regs.declareLocal();
|
|
2045
|
+
const cursor = state.regs.declareLocal();
|
|
2046
|
+
const startTmp = this.compileExpr(stmt.start, state);
|
|
2047
|
+
this.emit(state, 0 /* MOVE */, base, startTmp, 0);
|
|
2048
|
+
state.regs.freeTemp(startTmp);
|
|
2049
|
+
const endTmp = this.compileExpr(stmt.end, state);
|
|
2050
|
+
this.emit(state, 0 /* MOVE */, base + 1, endTmp, 0);
|
|
2051
|
+
state.regs.freeTemp(endTmp);
|
|
2052
|
+
const stepTmp = stmt.step ? this.compileExpr(stmt.step, state) : this.loadConst(state, 1);
|
|
2053
|
+
this.emit(state, 0 /* MOVE */, base + 2, stepTmp, 0);
|
|
2054
|
+
state.regs.freeTemp(stepTmp);
|
|
2055
|
+
const prep = this.emit(state, 29 /* FORPREP */, base, 0, 0, "forprep");
|
|
2056
|
+
const loopBodyStart = state.proto.code.length;
|
|
2057
|
+
const bindingId = this.bindingIdOfDecl(stmt.variable);
|
|
2058
|
+
const captured = this.captured.has(bindingId);
|
|
2059
|
+
let varReg;
|
|
2060
|
+
if (captured) {
|
|
2061
|
+
varReg = state.regs.declareLocal();
|
|
2062
|
+
this.emitNewBox(state, varReg);
|
|
2063
|
+
const k = this.konst(state, BOX_FIELD);
|
|
2064
|
+
this.emit(state, 9 /* SETTABLE */, varReg, RK(k, true), cursor);
|
|
2065
|
+
} else {
|
|
2066
|
+
varReg = cursor;
|
|
2067
|
+
}
|
|
2068
|
+
state.localSlots.set(bindingId, { reg: varReg, boxed: captured });
|
|
2069
|
+
state.breakPatchStack.push([]);
|
|
2070
|
+
state.continuePatchStack.push([]);
|
|
2071
|
+
this.compileBlock(stmt.body, state);
|
|
2072
|
+
const loopInstr = this.emit(state, 30 /* FORLOOP */, base, 0, 0, "forloop");
|
|
2073
|
+
this.patchJumpField(state, prep, loopInstr, "b");
|
|
2074
|
+
this.patchJumpField(state, loopInstr, loopBodyStart, "b");
|
|
2075
|
+
const endIdx = state.proto.code.length;
|
|
2076
|
+
for (const b of state.breakPatchStack.pop()) this.patchJump(state, b, endIdx);
|
|
2077
|
+
for (const c of state.continuePatchStack.pop()) this.patchJump(state, c, loopInstr);
|
|
2078
|
+
state.regs.releaseLocalsTo(saved);
|
|
2079
|
+
}
|
|
2080
|
+
compileGenericFor(stmt, state) {
|
|
2081
|
+
const saved = state.regs.saveLocalCount();
|
|
2082
|
+
const base = state.regs.declareLocal();
|
|
2083
|
+
state.regs.declareLocal();
|
|
2084
|
+
state.regs.declareLocal();
|
|
2085
|
+
const iterators = stmt.iterators;
|
|
2086
|
+
if (iterators.length === 1 && iterators[0].type === "CallExpression") {
|
|
2087
|
+
const firstReg = this.compileCallMultiInto(iterators[0], state, 3);
|
|
2088
|
+
for (let i = 0; i < 3; i++) this.emit(state, 0 /* MOVE */, base + i, firstReg + i, 0);
|
|
2089
|
+
state.regs.freeTemp(firstReg);
|
|
2090
|
+
} else {
|
|
2091
|
+
for (let i = 0; i < 3; i++) {
|
|
2092
|
+
if (i < iterators.length) {
|
|
2093
|
+
const r = this.compileExpr(iterators[i], state);
|
|
2094
|
+
this.emit(state, 0 /* MOVE */, base + i, r, 0);
|
|
2095
|
+
state.regs.freeTemp(r);
|
|
2096
|
+
} else {
|
|
2097
|
+
this.emit(state, 3 /* LOADNIL */, base + i, base + i, 0);
|
|
2098
|
+
}
|
|
2099
|
+
}
|
|
2100
|
+
}
|
|
2101
|
+
const loopStart = state.proto.code.length;
|
|
2102
|
+
const nVars = stmt.variables.length;
|
|
2103
|
+
const callBase = state.regs.top();
|
|
2104
|
+
const fnSlot = state.regs.allocTemp();
|
|
2105
|
+
const stateSlot = state.regs.allocTemp();
|
|
2106
|
+
const ctrlSlot = state.regs.allocTemp();
|
|
2107
|
+
this.emit(state, 0 /* MOVE */, fnSlot, base, 0);
|
|
2108
|
+
this.emit(state, 0 /* MOVE */, stateSlot, base + 1, 0);
|
|
2109
|
+
this.emit(state, 0 /* MOVE */, ctrlSlot, base + 2, 0);
|
|
2110
|
+
this.emit(state, 27 /* CALL */, fnSlot, 3, nVars + 1);
|
|
2111
|
+
state.regs.freeTemp(callBase);
|
|
2112
|
+
const resultRegs = [];
|
|
2113
|
+
for (let i = 0; i < nVars; i++) resultRegs.push(state.regs.declareLocal());
|
|
2114
|
+
const firstResult = resultRegs[0];
|
|
2115
|
+
this.emit(state, 26 /* TEST */, firstResult, 0, 1);
|
|
2116
|
+
const exitJmp = this.emit(state, 22 /* JMP */, 0, 0, 0, "generic-for-exit");
|
|
2117
|
+
this.emit(state, 0 /* MOVE */, base + 2, firstResult, 0);
|
|
2118
|
+
for (let i = 0; i < nVars; i++) {
|
|
2119
|
+
const bindingId = this.bindingIdOfDecl(stmt.variables[i]);
|
|
2120
|
+
if (this.captured.has(bindingId)) {
|
|
2121
|
+
const boxReg = state.regs.declareLocal();
|
|
2122
|
+
state.localSlots.set(bindingId, { reg: boxReg, boxed: true });
|
|
2123
|
+
this.emitNewBox(state, boxReg);
|
|
2124
|
+
const k = this.konst(state, BOX_FIELD);
|
|
2125
|
+
this.emit(state, 9 /* SETTABLE */, boxReg, RK(k, true), resultRegs[i]);
|
|
2126
|
+
} else {
|
|
2127
|
+
state.localSlots.set(bindingId, { reg: resultRegs[i], boxed: false });
|
|
2128
|
+
}
|
|
2129
|
+
}
|
|
2130
|
+
state.breakPatchStack.push([]);
|
|
2131
|
+
state.continuePatchStack.push([]);
|
|
2132
|
+
this.compileBlock(stmt.body, state);
|
|
2133
|
+
this.emit(state, 22 /* JMP */, loopStart - state.proto.code.length, 0, 0, "generic-for-back");
|
|
2134
|
+
const endIdx = state.proto.code.length;
|
|
2135
|
+
this.patchJump(state, exitJmp, endIdx);
|
|
2136
|
+
for (const b of state.breakPatchStack.pop()) this.patchJump(state, b, endIdx);
|
|
2137
|
+
for (const c of state.continuePatchStack.pop()) this.patchJump(state, c, loopStart);
|
|
2138
|
+
state.regs.releaseLocalsTo(saved);
|
|
2139
|
+
}
|
|
2140
|
+
compileCallMultiInto(callExpr, state, wantCount) {
|
|
2141
|
+
const base = this.compileExpr(callExpr.callee, state);
|
|
2142
|
+
this.compileArgsContiguous(callExpr.arguments, state, base + 1);
|
|
2143
|
+
this.emit(state, 27 /* CALL */, base, callExpr.arguments.length + 1, wantCount + 1);
|
|
2144
|
+
return base;
|
|
2145
|
+
}
|
|
2146
|
+
loadConst(state, value) {
|
|
2147
|
+
const reg = state.regs.allocTemp();
|
|
2148
|
+
const k = this.konst(state, value);
|
|
2149
|
+
this.emit(state, 1 /* LOADK */, reg, k, 0);
|
|
2150
|
+
return reg;
|
|
2151
|
+
}
|
|
2152
|
+
patchJump(state, instrIdx, targetIdx) {
|
|
2153
|
+
this.patchJumpField(state, instrIdx, targetIdx, "a");
|
|
2154
|
+
}
|
|
2155
|
+
patchJumpField(state, instrIdx, targetIdx, field) {
|
|
2156
|
+
state.proto.code[instrIdx][field] = targetIdx - instrIdx;
|
|
2157
|
+
}
|
|
2158
|
+
bindingIdOfDecl(node) {
|
|
2159
|
+
const id = this.declToBinding.get(node);
|
|
2160
|
+
if (id === void 0) throw new Error("vmify: could not resolve declaration binding (compiler bug)");
|
|
2161
|
+
return id;
|
|
2162
|
+
}
|
|
2163
|
+
/** expr을 컴파일해서 결과가 정확히 target 레지스터에 오도록 강제(필요하면 MOVE 한 번 추가). */
|
|
2164
|
+
compileExprTo(expr, state, target) {
|
|
2165
|
+
const r = this.compileExpr(expr, state);
|
|
2166
|
+
if (r !== target) this.emit(state, 0 /* MOVE */, target, r, 0);
|
|
2167
|
+
state.regs.freeTemp(target + 1);
|
|
2168
|
+
}
|
|
2169
|
+
/**
|
|
2170
|
+
* CALL/RETURN처럼 "레지스터 base부터 연속으로 n개"를 요구하는 명령을 위해, 인자 표현식
|
|
2171
|
+
* 목록을 base, base+1, base+2 ...에 강제로 배치한다. 단순히 순서대로 compileExpr만
|
|
2172
|
+
* 호출하면 개별 인자는 각자 "자기 자신의 결과+1"이 다음 top이 되는 게 맞지만, 그 인자가
|
|
2173
|
+
* 복합 표현식(예: 이항연산 `i > 2`)이라 내부에서 스크래치 레지스터를 여러 개 쓰면 다음
|
|
2174
|
+
* 인자와의 사이에 빈틈이 생겨 CALL/RETURN이 잘못된 레지스터를 읽게 된다 — 그래서 매
|
|
2175
|
+
* 인자마다 목표 레지스터를 명시하고 필요하면 MOVE로 맞춰준다.
|
|
2176
|
+
*/
|
|
2177
|
+
compileArgsContiguous(exprs, state, base) {
|
|
2178
|
+
for (let i = 0; i < exprs.length; i++) this.compileExprTo(exprs[i], state, base + i);
|
|
2179
|
+
}
|
|
2180
|
+
/** Call/MethodCall/Vararg처럼 "여러 값"을 낼 수 있는 표현식인지. */
|
|
2181
|
+
isMultiValueExpr(expr) {
|
|
2182
|
+
return expr.type === "CallExpression" || expr.type === "MethodCallExpression" || expr.type === "VarargExpression";
|
|
2183
|
+
}
|
|
2184
|
+
/**
|
|
2185
|
+
* expr을 컴파일해서 "정확히 wantCount개"의 값을 base..base+wantCount-1에 채운다
|
|
2186
|
+
* (모자라면 nil로 패딩). Call/MethodCall/Vararg만 1개 이상을 낼 수 있고, 그 외
|
|
2187
|
+
* 표현식은 항상 1개만 내므로 나머지는 자동으로 nil 패딩된다.
|
|
2188
|
+
*/
|
|
2189
|
+
compileExprMultiInto(expr, state, base, wantCount) {
|
|
2190
|
+
if (wantCount <= 0) return;
|
|
2191
|
+
if (expr.type === "CallExpression") {
|
|
2192
|
+
const calleeReg = this.compileExpr(expr.callee, state);
|
|
2193
|
+
const b = this.compileCallArgsAndGetB(expr.arguments, state, calleeReg + 1);
|
|
2194
|
+
this.emit(state, 27 /* CALL */, calleeReg, b, wantCount + 1);
|
|
2195
|
+
for (let i = 0; i < wantCount; i++) {
|
|
2196
|
+
if (calleeReg + i !== base + i) this.emit(state, 0 /* MOVE */, base + i, calleeReg + i, 0);
|
|
2197
|
+
}
|
|
2198
|
+
state.regs.freeTemp(base + wantCount);
|
|
2199
|
+
return;
|
|
2200
|
+
}
|
|
2201
|
+
if (expr.type === "MethodCallExpression") {
|
|
2202
|
+
const objReg = this.compileExpr(expr.object, state);
|
|
2203
|
+
const k = this.konst(state, expr.method.name);
|
|
2204
|
+
const fnSlot = state.regs.allocTemp();
|
|
2205
|
+
this.emit(state, 11 /* SELF */, fnSlot, objReg, RK(k, true));
|
|
2206
|
+
state.regs.allocTemp();
|
|
2207
|
+
const argB = this.compileCallArgsAndGetB(expr.arguments, state, fnSlot + 2);
|
|
2208
|
+
const b = argB === 0 ? 0 : expr.arguments.length + 2;
|
|
2209
|
+
this.emit(state, 27 /* CALL */, fnSlot, b, wantCount + 1);
|
|
2210
|
+
for (let i = 0; i < wantCount; i++) {
|
|
2211
|
+
if (fnSlot + i !== base + i) this.emit(state, 0 /* MOVE */, base + i, fnSlot + i, 0);
|
|
2212
|
+
}
|
|
2213
|
+
state.regs.freeTemp(base + wantCount);
|
|
2214
|
+
return;
|
|
2215
|
+
}
|
|
2216
|
+
if (expr.type === "VarargExpression") {
|
|
2217
|
+
this.emit(state, 32 /* VARARG */, base, wantCount + 1, 0);
|
|
2218
|
+
state.regs.freeTemp(base + wantCount);
|
|
2219
|
+
return;
|
|
2220
|
+
}
|
|
2221
|
+
this.compileExprTo(expr, state, base);
|
|
2222
|
+
for (let i = 1; i < wantCount; i++) this.emit(state, 3 /* LOADNIL */, base + i, base + i, 0);
|
|
2223
|
+
}
|
|
2224
|
+
/**
|
|
2225
|
+
* expr을 컴파일해서 "런타임이 결정하는 개수만큼" base부터 이어서 채운다(frame.multiTop
|
|
2226
|
+
* 갱신). Call/MethodCall/Vararg가 아니면 그냥 1개로 취급(compileExprTo와 동일).
|
|
2227
|
+
* `return f()`나 `g(a, f())`의 마지막 인자처럼 다중값을 그대로 전파할 때 씀.
|
|
2228
|
+
*/
|
|
2229
|
+
compileExprOpenInto(expr, state, base) {
|
|
2230
|
+
if (expr.type === "CallExpression") {
|
|
2231
|
+
const calleeReg = this.compileExpr(expr.callee, state);
|
|
2232
|
+
if (calleeReg !== base) this.emit(state, 0 /* MOVE */, base, calleeReg, 0);
|
|
2233
|
+
state.regs.freeTemp(base + 1);
|
|
2234
|
+
const b = this.compileCallArgsAndGetB(expr.arguments, state, base + 1);
|
|
2235
|
+
this.emit(state, 27 /* CALL */, base, b, 0);
|
|
2236
|
+
return;
|
|
2237
|
+
}
|
|
2238
|
+
if (expr.type === "MethodCallExpression") {
|
|
2239
|
+
const objReg = this.compileExpr(expr.object, state);
|
|
2240
|
+
const k = this.konst(state, expr.method.name);
|
|
2241
|
+
const fnSlot = state.regs.allocTemp();
|
|
2242
|
+
this.emit(state, 11 /* SELF */, fnSlot, objReg, RK(k, true));
|
|
2243
|
+
state.regs.allocTemp();
|
|
2244
|
+
if (fnSlot !== base) {
|
|
2245
|
+
this.emit(state, 0 /* MOVE */, base, fnSlot, 0);
|
|
2246
|
+
this.emit(state, 0 /* MOVE */, base + 1, fnSlot + 1, 0);
|
|
2247
|
+
}
|
|
2248
|
+
state.regs.freeTemp(base + 2);
|
|
2249
|
+
const argB = this.compileCallArgsAndGetB(expr.arguments, state, base + 2);
|
|
2250
|
+
const b = argB === 0 ? 0 : expr.arguments.length + 2;
|
|
2251
|
+
this.emit(state, 27 /* CALL */, base, b, 0);
|
|
2252
|
+
return;
|
|
2253
|
+
}
|
|
2254
|
+
if (expr.type === "VarargExpression") {
|
|
2255
|
+
this.emit(state, 32 /* VARARG */, base, 0, 0);
|
|
2256
|
+
return;
|
|
2257
|
+
}
|
|
2258
|
+
this.compileExprTo(expr, state, base);
|
|
2259
|
+
}
|
|
2260
|
+
/**
|
|
2261
|
+
* 호출 인자 목록을 base부터 컴파일. 마지막 인자가 다중값 가능한 표현식이면 열어서
|
|
2262
|
+
* 끝까지 전파(`f(a, g())`가 g()의 모든 반환값을 다 넘기도록)하고 CALL의 b로 쓸 값(0)을
|
|
2263
|
+
* 반환한다. 아니면 고정 개수(b=args.length+1)를 반환.
|
|
2264
|
+
*/
|
|
2265
|
+
compileCallArgsAndGetB(args, state, base) {
|
|
2266
|
+
if (args.length === 0) return 1;
|
|
2267
|
+
for (let i = 0; i < args.length - 1; i++) this.compileExprTo(args[i], state, base + i);
|
|
2268
|
+
const last = args[args.length - 1];
|
|
2269
|
+
const lastBase = base + args.length - 1;
|
|
2270
|
+
if (this.isMultiValueExpr(last)) {
|
|
2271
|
+
this.compileExprOpenInto(last, state, lastBase);
|
|
2272
|
+
return 0;
|
|
2273
|
+
}
|
|
2274
|
+
this.compileExprTo(last, state, lastBase);
|
|
2275
|
+
return args.length + 1;
|
|
2276
|
+
}
|
|
2277
|
+
compileExpr(expr, state, discard = false) {
|
|
2278
|
+
switch (expr.type) {
|
|
2279
|
+
case "NilLiteral": {
|
|
2280
|
+
const r = state.regs.allocTemp();
|
|
2281
|
+
this.emit(state, 3 /* LOADNIL */, r, r, 0);
|
|
2282
|
+
return r;
|
|
2283
|
+
}
|
|
2284
|
+
case "BooleanLiteral": {
|
|
2285
|
+
const r = state.regs.allocTemp();
|
|
2286
|
+
this.emit(state, 2 /* LOADBOOL */, r, expr.value ? 1 : 0, 0);
|
|
2287
|
+
return r;
|
|
2288
|
+
}
|
|
2289
|
+
case "NumberLiteral":
|
|
2290
|
+
return this.loadConst(state, expr.value);
|
|
2291
|
+
case "StringLiteral":
|
|
2292
|
+
return this.loadConst(state, expr.value);
|
|
2293
|
+
case "Identifier": {
|
|
2294
|
+
const bindingId = this.bindingIdOf(expr);
|
|
2295
|
+
if (bindingId === void 0) throw new Error("vmify: unresolved identifier");
|
|
2296
|
+
const r = state.regs.allocTemp();
|
|
2297
|
+
this.emitLoadBinding(state, bindingId, r);
|
|
2298
|
+
return r;
|
|
2299
|
+
}
|
|
2300
|
+
case "ParenthesizedExpression":
|
|
2301
|
+
return this.compileExpr(expr.expression, state);
|
|
2302
|
+
case "TypeAssertionExpression":
|
|
2303
|
+
return this.compileExpr(expr.expression, state);
|
|
2304
|
+
case "BinaryExpression": {
|
|
2305
|
+
if (expr.operator === "and" || expr.operator === "or") {
|
|
2306
|
+
return this.compileLogical(expr.operator, expr.left, expr.right, state);
|
|
2307
|
+
}
|
|
2308
|
+
let leftExpr = expr.left;
|
|
2309
|
+
let rightExpr = expr.right;
|
|
2310
|
+
let op;
|
|
2311
|
+
let swap = false;
|
|
2312
|
+
let negate = false;
|
|
2313
|
+
switch (expr.operator) {
|
|
2314
|
+
case "+":
|
|
2315
|
+
op = 12 /* ADD */;
|
|
2316
|
+
break;
|
|
2317
|
+
case "-":
|
|
2318
|
+
op = 13 /* SUB */;
|
|
2319
|
+
break;
|
|
2320
|
+
case "*":
|
|
2321
|
+
op = 14 /* MUL */;
|
|
2322
|
+
break;
|
|
2323
|
+
case "/":
|
|
2324
|
+
op = 15 /* DIV */;
|
|
2325
|
+
break;
|
|
2326
|
+
case "//":
|
|
2327
|
+
op = 34 /* IDIV */;
|
|
2328
|
+
break;
|
|
2329
|
+
case "%":
|
|
2330
|
+
op = 16 /* MOD */;
|
|
2331
|
+
break;
|
|
2332
|
+
case "^":
|
|
2333
|
+
op = 17 /* POW */;
|
|
2334
|
+
break;
|
|
2335
|
+
case "..":
|
|
2336
|
+
op = 18 /* CONCAT */;
|
|
2337
|
+
break;
|
|
2338
|
+
case "==":
|
|
2339
|
+
op = 23 /* EQ */;
|
|
2340
|
+
break;
|
|
2341
|
+
case "~=":
|
|
2342
|
+
op = 23 /* EQ */;
|
|
2343
|
+
negate = true;
|
|
2344
|
+
break;
|
|
2345
|
+
case "<":
|
|
2346
|
+
op = 24 /* LT */;
|
|
2347
|
+
break;
|
|
2348
|
+
case "<=":
|
|
2349
|
+
op = 25 /* LE */;
|
|
2350
|
+
break;
|
|
2351
|
+
case ">":
|
|
2352
|
+
op = 24 /* LT */;
|
|
2353
|
+
swap = true;
|
|
2354
|
+
break;
|
|
2355
|
+
case ">=":
|
|
2356
|
+
op = 25 /* LE */;
|
|
2357
|
+
swap = true;
|
|
2358
|
+
break;
|
|
2359
|
+
default:
|
|
2360
|
+
throw new Error(`vmify: unsupported binary operator ${expr.operator}`);
|
|
2361
|
+
}
|
|
2362
|
+
if (swap) {
|
|
2363
|
+
const t = leftExpr;
|
|
2364
|
+
leftExpr = rightExpr;
|
|
2365
|
+
rightExpr = t;
|
|
2366
|
+
}
|
|
2367
|
+
const l = this.compileExpr(leftExpr, state);
|
|
2368
|
+
const r = this.compileExpr(rightExpr, state);
|
|
2369
|
+
const dest = state.regs.allocTemp();
|
|
2370
|
+
this.emit(state, op, dest, l, r);
|
|
2371
|
+
if (negate) this.emit(state, 20 /* NOT */, dest, dest, 0);
|
|
2372
|
+
state.regs.freeTemp(dest + 1);
|
|
2373
|
+
return dest;
|
|
2374
|
+
}
|
|
2375
|
+
case "UnaryExpression": {
|
|
2376
|
+
const argReg = this.compileExpr(expr.argument, state);
|
|
2377
|
+
const dest = state.regs.allocTemp();
|
|
2378
|
+
const op = expr.operator === "-" ? 19 /* UNM */ : expr.operator === "not" ? 20 /* NOT */ : 21 /* LEN */;
|
|
2379
|
+
this.emit(state, op, dest, argReg, 0);
|
|
2380
|
+
state.regs.freeTemp(dest + 1);
|
|
2381
|
+
return dest;
|
|
2382
|
+
}
|
|
2383
|
+
case "TableExpression": {
|
|
2384
|
+
const dest = state.regs.allocTemp();
|
|
2385
|
+
this.emit(state, 10 /* NEWTABLE */, dest, 0, 0);
|
|
2386
|
+
let posIndex = 1;
|
|
2387
|
+
for (let fi = 0; fi < expr.fields.length; fi++) {
|
|
2388
|
+
const field = expr.fields[fi];
|
|
2389
|
+
const isLast = fi === expr.fields.length - 1;
|
|
2390
|
+
if (field.type === "TableFieldPositional") {
|
|
2391
|
+
if (isLast && this.isMultiValueExpr(field.value)) {
|
|
2392
|
+
const valuesBase = state.regs.allocTemp();
|
|
2393
|
+
this.compileExprOpenInto(field.value, state, valuesBase);
|
|
2394
|
+
this.emit(state, 33 /* SETLIST */, dest, valuesBase, posIndex);
|
|
2395
|
+
state.regs.freeTemp(valuesBase);
|
|
2396
|
+
} else {
|
|
2397
|
+
const v = this.compileExpr(field.value, state);
|
|
2398
|
+
const k = this.konst(state, posIndex++);
|
|
2399
|
+
this.emit(state, 9 /* SETTABLE */, dest, RK(k, true), v);
|
|
2400
|
+
state.regs.freeTemp(v);
|
|
2401
|
+
}
|
|
2402
|
+
} else if (field.type === "TableFieldNamed") {
|
|
2403
|
+
const v = this.compileExpr(field.value, state);
|
|
2404
|
+
const k = this.konst(state, field.name.name);
|
|
2405
|
+
this.emit(state, 9 /* SETTABLE */, dest, RK(k, true), v);
|
|
2406
|
+
state.regs.freeTemp(v);
|
|
2407
|
+
} else {
|
|
2408
|
+
const k = this.compileExpr(field.key, state);
|
|
2409
|
+
const v = this.compileExpr(field.value, state);
|
|
2410
|
+
this.emit(state, 9 /* SETTABLE */, dest, k, v);
|
|
2411
|
+
state.regs.freeTemp(k);
|
|
2412
|
+
}
|
|
2413
|
+
}
|
|
2414
|
+
return dest;
|
|
2415
|
+
}
|
|
2416
|
+
case "MemberExpression": {
|
|
2417
|
+
const objReg = this.compileExpr(expr.object, state);
|
|
2418
|
+
const k = this.konst(state, expr.property.name);
|
|
2419
|
+
const dest = state.regs.allocTemp();
|
|
2420
|
+
this.emit(state, 8 /* GETTABLE */, dest, objReg, RK(k, true));
|
|
2421
|
+
state.regs.freeTemp(dest + 1);
|
|
2422
|
+
return dest;
|
|
2423
|
+
}
|
|
2424
|
+
case "IndexExpression": {
|
|
2425
|
+
const objReg = this.compileExpr(expr.object, state);
|
|
2426
|
+
const keyReg = this.compileExpr(expr.index, state);
|
|
2427
|
+
const dest = state.regs.allocTemp();
|
|
2428
|
+
this.emit(state, 8 /* GETTABLE */, dest, objReg, keyReg);
|
|
2429
|
+
state.regs.freeTemp(dest + 1);
|
|
2430
|
+
return dest;
|
|
2431
|
+
}
|
|
2432
|
+
case "CallExpression": {
|
|
2433
|
+
const base = this.compileExpr(expr.callee, state);
|
|
2434
|
+
const b = this.compileCallArgsAndGetB(expr.arguments, state, base + 1);
|
|
2435
|
+
this.emit(state, 27 /* CALL */, base, b, discard ? 1 : 2);
|
|
2436
|
+
state.regs.freeTemp(base + (discard ? 0 : 1));
|
|
2437
|
+
return base;
|
|
2438
|
+
}
|
|
2439
|
+
case "MethodCallExpression": {
|
|
2440
|
+
const objReg = this.compileExpr(expr.object, state);
|
|
2441
|
+
const k = this.konst(state, expr.method.name);
|
|
2442
|
+
const fnSlot = state.regs.allocTemp();
|
|
2443
|
+
this.emit(state, 11 /* SELF */, fnSlot, objReg, RK(k, true));
|
|
2444
|
+
state.regs.allocTemp();
|
|
2445
|
+
const argB = this.compileCallArgsAndGetB(expr.arguments, state, fnSlot + 2);
|
|
2446
|
+
const b = argB === 0 ? 0 : expr.arguments.length + 2;
|
|
2447
|
+
this.emit(state, 27 /* CALL */, fnSlot, b, discard ? 1 : 2);
|
|
2448
|
+
state.regs.freeTemp(fnSlot + (discard ? 0 : 1));
|
|
2449
|
+
return fnSlot;
|
|
2450
|
+
}
|
|
2451
|
+
case "FunctionExpression": {
|
|
2452
|
+
const protoIdx = this.compileFunctionBody(expr.func, state);
|
|
2453
|
+
const dest = state.regs.allocTemp();
|
|
2454
|
+
this.emitClosure(state, dest, protoIdx);
|
|
2455
|
+
return dest;
|
|
2456
|
+
}
|
|
2457
|
+
case "InterpolatedStringExpression": {
|
|
2458
|
+
let acc = null;
|
|
2459
|
+
for (const part of expr.parts) {
|
|
2460
|
+
const partReg = part.kind === "string" ? this.loadConst(state, part.value) : this.compileExpr(part.expression, state);
|
|
2461
|
+
if (acc === null) {
|
|
2462
|
+
acc = partReg;
|
|
2463
|
+
} else {
|
|
2464
|
+
const dest = state.regs.allocTemp();
|
|
2465
|
+
this.emit(state, 18 /* CONCAT */, dest, acc, partReg);
|
|
2466
|
+
state.regs.freeTemp(dest + 1);
|
|
2467
|
+
acc = dest;
|
|
2468
|
+
}
|
|
2469
|
+
}
|
|
2470
|
+
return acc ?? this.loadConst(state, "");
|
|
2471
|
+
}
|
|
2472
|
+
case "VarargExpression": {
|
|
2473
|
+
const r = state.regs.allocTemp();
|
|
2474
|
+
this.emit(state, 32 /* VARARG */, r, 2, 0, "vararg (1 value)");
|
|
2475
|
+
return r;
|
|
2476
|
+
}
|
|
2477
|
+
case "IfElseExpression": {
|
|
2478
|
+
const dest = state.regs.allocTemp();
|
|
2479
|
+
const endPatches = [];
|
|
2480
|
+
for (const clause of expr.clauses) {
|
|
2481
|
+
const condReg = this.compileExpr(clause.condition, state);
|
|
2482
|
+
this.emit(state, 26 /* TEST */, condReg, 0, 1);
|
|
2483
|
+
const skip = this.emit(state, 22 /* JMP */, 0, 0, 0);
|
|
2484
|
+
state.regs.freeTemp(condReg);
|
|
2485
|
+
const bodyReg = this.compileExpr(clause.body, state);
|
|
2486
|
+
if (bodyReg !== dest) this.emit(state, 0 /* MOVE */, dest, bodyReg, 0);
|
|
2487
|
+
state.regs.freeTemp(dest + 1);
|
|
2488
|
+
const toEnd = this.emit(state, 22 /* JMP */, 0, 0, 0);
|
|
2489
|
+
endPatches.push(toEnd);
|
|
2490
|
+
this.patchJump(state, skip, state.proto.code.length);
|
|
2491
|
+
}
|
|
2492
|
+
const altReg = this.compileExpr(expr.alternate, state);
|
|
2493
|
+
if (altReg !== dest) this.emit(state, 0 /* MOVE */, dest, altReg, 0);
|
|
2494
|
+
state.regs.freeTemp(dest + 1);
|
|
2495
|
+
for (const p of endPatches) this.patchJump(state, p, state.proto.code.length);
|
|
2496
|
+
return dest;
|
|
2497
|
+
}
|
|
2498
|
+
default: {
|
|
2499
|
+
const _exhaustive = expr;
|
|
2500
|
+
throw new Error(`vmify: unhandled expression ${_exhaustive.type}`);
|
|
2501
|
+
}
|
|
2502
|
+
}
|
|
2503
|
+
}
|
|
2504
|
+
compileLogical(operator, left, right, state) {
|
|
2505
|
+
const dest = this.compileExpr(left, state);
|
|
2506
|
+
this.emit(state, 26 /* TEST */, dest, 0, operator === "and" ? 1 : 0, `${operator} short-circuit`);
|
|
2507
|
+
const skip = this.emit(state, 22 /* JMP */, 0, 0, 0);
|
|
2508
|
+
state.regs.freeTemp(dest);
|
|
2509
|
+
const rightReg = this.compileExpr(right, state);
|
|
2510
|
+
if (rightReg !== dest) this.emit(state, 0 /* MOVE */, dest, rightReg, 0);
|
|
2511
|
+
this.patchJump(state, skip, state.proto.code.length);
|
|
2512
|
+
state.regs.freeTemp(dest + 1);
|
|
2513
|
+
return dest;
|
|
2514
|
+
}
|
|
2515
|
+
emitClosure(state, dest, protoIdx) {
|
|
2516
|
+
this.emit(state, 31 /* CLOSURE */, dest, protoIdx, 0);
|
|
2517
|
+
const proto = state.proto.protos[protoIdx];
|
|
2518
|
+
for (const desc of proto.upvalDescs) {
|
|
2519
|
+
if (desc.kind === "local") this.emit(state, 0 /* MOVE */, 0, desc.index, 0, "capture local");
|
|
2520
|
+
else this.emit(state, 4 /* GETUPVAL */, 0, desc.index, 0, "capture upval");
|
|
2521
|
+
}
|
|
2522
|
+
}
|
|
2523
|
+
compileFunctionBody(fb, parent) {
|
|
2524
|
+
const marker = ownerFunctionOf(this.enclosing, fb);
|
|
2525
|
+
const child = this.newFuncState(parent, marker);
|
|
2526
|
+
child.proto.numParams = fb.params.length;
|
|
2527
|
+
child.proto.hasVarargs = fb.hasVarargs;
|
|
2528
|
+
const naturalRegs = fb.params.map(() => child.regs.declareLocal());
|
|
2529
|
+
for (let i = 0; i < fb.params.length; i++) {
|
|
2530
|
+
const bindingId = this.bindingIdOfDecl(fb.params[i]);
|
|
2531
|
+
if (this.captured.has(bindingId)) {
|
|
2532
|
+
const boxReg = child.regs.declareLocal();
|
|
2533
|
+
this.emitNewBox(child, boxReg);
|
|
2534
|
+
const k = this.konst(child, BOX_FIELD);
|
|
2535
|
+
this.emit(child, 9 /* SETTABLE */, boxReg, RK(k, true), naturalRegs[i]);
|
|
2536
|
+
child.localSlots.set(bindingId, { reg: boxReg, boxed: true });
|
|
2537
|
+
} else {
|
|
2538
|
+
child.localSlots.set(bindingId, { reg: naturalRegs[i], boxed: false });
|
|
2539
|
+
}
|
|
2540
|
+
}
|
|
2541
|
+
this.compileBlock(fb.body, child);
|
|
2542
|
+
this.emit(child, 28 /* RETURN */, 0, 1, 0);
|
|
2543
|
+
child.proto.maxRegs = child.regs.maxUsed;
|
|
2544
|
+
parent.proto.protos.push(child.proto);
|
|
2545
|
+
return parent.proto.protos.length - 1;
|
|
2546
|
+
}
|
|
2547
|
+
};
|
|
2548
|
+
|
|
2549
|
+
// src/passes/vmify/serialize.ts
|
|
2550
|
+
function serializeConsts(consts) {
|
|
2551
|
+
const fields = consts.map((v) => positionalField(serializeConstValue(v)));
|
|
2552
|
+
return table(fields);
|
|
2553
|
+
}
|
|
2554
|
+
function serializeConstValue(v) {
|
|
2555
|
+
if (v === null) return nilLiteral();
|
|
2556
|
+
if (typeof v === "string") return stringLiteral(v);
|
|
2557
|
+
if (typeof v === "number") return numberLiteral(v);
|
|
2558
|
+
return booleanLiteral(v);
|
|
2559
|
+
}
|
|
2560
|
+
function serializeInstrs(proto, names) {
|
|
2561
|
+
const fields = proto.code.map((instr) => positionalField(
|
|
2562
|
+
table([
|
|
2563
|
+
namedField(names.op, numberLiteral(instr.op)),
|
|
2564
|
+
namedField(names.a, numberLiteral(instr.a)),
|
|
2565
|
+
namedField(names.b, numberLiteral(instr.b)),
|
|
2566
|
+
namedField(names.c, numberLiteral(instr.c))
|
|
2567
|
+
])
|
|
2568
|
+
));
|
|
2569
|
+
return table(fields);
|
|
2570
|
+
}
|
|
2571
|
+
function serializeUpvalDescs(proto, names) {
|
|
2572
|
+
const fields = proto.upvalDescs.map((d) => positionalField(
|
|
2573
|
+
table([
|
|
2574
|
+
namedField(names.kind, stringLiteral(d.kind)),
|
|
2575
|
+
namedField(names.index, numberLiteral(d.index))
|
|
2576
|
+
])
|
|
2577
|
+
));
|
|
2578
|
+
return table(fields);
|
|
2579
|
+
}
|
|
2580
|
+
function serializeProto(proto, names) {
|
|
2581
|
+
const fields = [
|
|
2582
|
+
namedField(names.numParams, numberLiteral(proto.numParams)),
|
|
2583
|
+
namedField(names.hasVarargs, booleanLiteral(proto.hasVarargs)),
|
|
2584
|
+
namedField(names.maxRegs, numberLiteral(proto.maxRegs)),
|
|
2585
|
+
namedField(names.code, serializeInstrs(proto, names)),
|
|
2586
|
+
namedField(names.consts, serializeConsts(proto.consts)),
|
|
2587
|
+
namedField(names.upvalDescs, serializeUpvalDescs(proto, names)),
|
|
2588
|
+
namedField(names.protos, table(proto.protos.map((p) => positionalField(serializeProto(p, names)))))
|
|
2589
|
+
];
|
|
2590
|
+
return table(fields);
|
|
2591
|
+
}
|
|
2592
|
+
|
|
2593
|
+
// src/passes/vmify/runtime.ts
|
|
2594
|
+
function buildVmRuntimeSource(names, opcodeMap) {
|
|
2595
|
+
const N = names;
|
|
2596
|
+
const op = (o) => opcodeMap[o];
|
|
2597
|
+
return `
|
|
2598
|
+
local ${N.handlers} = {}
|
|
2599
|
+
|
|
2600
|
+
local function ${N.dispatch}(${N.frame}, pc)
|
|
2601
|
+
local instr = ${N.frame}.${N.code}[pc]
|
|
2602
|
+
return ${N.handlers}[instr.${N.op}](${N.frame}, pc, instr)
|
|
2603
|
+
end
|
|
2604
|
+
|
|
2605
|
+
local function ${N.rk}(${N.frame}, x)
|
|
2606
|
+
if x < 0 then
|
|
2607
|
+
return ${N.frame}.${N.K}[-x - 1 + 1]
|
|
2608
|
+
else
|
|
2609
|
+
return ${N.frame}.${N.R}[x]
|
|
2610
|
+
end
|
|
2611
|
+
end
|
|
2612
|
+
|
|
2613
|
+
-- MOVE
|
|
2614
|
+
${N.handlers}[${op(0 /* MOVE */)}] = function(${N.frame}, pc, instr)
|
|
2615
|
+
${N.frame}.${N.R}[instr.${N.a}] = ${N.frame}.${N.R}[instr.${N.b}]
|
|
2616
|
+
return ${N.dispatch}(${N.frame}, pc + 1)
|
|
2617
|
+
end
|
|
2618
|
+
|
|
2619
|
+
-- LOADK
|
|
2620
|
+
${N.handlers}[${op(1 /* LOADK */)}] = function(${N.frame}, pc, instr)
|
|
2621
|
+
${N.frame}.${N.R}[instr.${N.a}] = ${N.frame}.${N.K}[instr.${N.b} + 1]
|
|
2622
|
+
return ${N.dispatch}(${N.frame}, pc + 1)
|
|
2623
|
+
end
|
|
2624
|
+
|
|
2625
|
+
-- LOADBOOL
|
|
2626
|
+
${N.handlers}[${op(2 /* LOADBOOL */)}] = function(${N.frame}, pc, instr)
|
|
2627
|
+
${N.frame}.${N.R}[instr.${N.a}] = (instr.${N.b} ~= 0)
|
|
2628
|
+
return ${N.dispatch}(${N.frame}, pc + 1)
|
|
2629
|
+
end
|
|
2630
|
+
|
|
2631
|
+
-- LOADNIL
|
|
2632
|
+
${N.handlers}[${op(3 /* LOADNIL */)}] = function(${N.frame}, pc, instr)
|
|
2633
|
+
for i = instr.${N.a}, instr.${N.b} do ${N.frame}.${N.R}[i] = nil end
|
|
2634
|
+
return ${N.dispatch}(${N.frame}, pc + 1)
|
|
2635
|
+
end
|
|
2636
|
+
|
|
2637
|
+
-- GETUPVAL
|
|
2638
|
+
${N.handlers}[${op(4 /* GETUPVAL */)}] = function(${N.frame}, pc, instr)
|
|
2639
|
+
${N.frame}.${N.R}[instr.${N.a}] = ${N.frame}.${N.upvals}[instr.${N.b} + 1]
|
|
2640
|
+
return ${N.dispatch}(${N.frame}, pc + 1)
|
|
2641
|
+
end
|
|
2642
|
+
|
|
2643
|
+
-- SETUPVAL
|
|
2644
|
+
${N.handlers}[${op(5 /* SETUPVAL */)}] = function(${N.frame}, pc, instr)
|
|
2645
|
+
${N.frame}.${N.upvals}[instr.${N.b} + 1] = ${N.frame}.${N.R}[instr.${N.a}]
|
|
2646
|
+
return ${N.dispatch}(${N.frame}, pc + 1)
|
|
2647
|
+
end
|
|
2648
|
+
|
|
2649
|
+
-- GETGLOBAL (b\uB294 RK\uAC00 \uC544\uB2C8\uB77C \uC0C1\uC218\uD480 \uC21C\uC218 \uC778\uB371\uC2A4)
|
|
2650
|
+
${N.handlers}[${op(6 /* GETGLOBAL */)}] = function(${N.frame}, pc, instr)
|
|
2651
|
+
${N.frame}.${N.R}[instr.${N.a}] = ${N.globals}[${N.frame}.${N.K}[instr.${N.b} + 1]]
|
|
2652
|
+
return ${N.dispatch}(${N.frame}, pc + 1)
|
|
2653
|
+
end
|
|
2654
|
+
|
|
2655
|
+
-- SETGLOBAL
|
|
2656
|
+
${N.handlers}[${op(7 /* SETGLOBAL */)}] = function(${N.frame}, pc, instr)
|
|
2657
|
+
${N.globals}[${N.frame}.${N.K}[instr.${N.b} + 1]] = ${N.frame}.${N.R}[instr.${N.a}]
|
|
2658
|
+
return ${N.dispatch}(${N.frame}, pc + 1)
|
|
2659
|
+
end
|
|
2660
|
+
|
|
2661
|
+
-- GETTABLE
|
|
2662
|
+
${N.handlers}[${op(8 /* GETTABLE */)}] = function(${N.frame}, pc, instr)
|
|
2663
|
+
${N.frame}.${N.R}[instr.${N.a}] = ${N.frame}.${N.R}[instr.${N.b}][${N.rk}(${N.frame}, instr.${N.c})]
|
|
2664
|
+
return ${N.dispatch}(${N.frame}, pc + 1)
|
|
2665
|
+
end
|
|
2666
|
+
|
|
2667
|
+
-- SETTABLE
|
|
2668
|
+
${N.handlers}[${op(9 /* SETTABLE */)}] = function(${N.frame}, pc, instr)
|
|
2669
|
+
${N.frame}.${N.R}[instr.${N.a}][${N.rk}(${N.frame}, instr.${N.b})] = ${N.rk}(${N.frame}, instr.${N.c})
|
|
2670
|
+
return ${N.dispatch}(${N.frame}, pc + 1)
|
|
2671
|
+
end
|
|
2672
|
+
|
|
2673
|
+
-- NEWTABLE
|
|
2674
|
+
${N.handlers}[${op(10 /* NEWTABLE */)}] = function(${N.frame}, pc, instr)
|
|
2675
|
+
${N.frame}.${N.R}[instr.${N.a}] = {}
|
|
2676
|
+
return ${N.dispatch}(${N.frame}, pc + 1)
|
|
2677
|
+
end
|
|
2678
|
+
|
|
2679
|
+
-- SELF (R[a] = R[b][key]; R[a+1] = R[b])
|
|
2680
|
+
${N.handlers}[${op(11 /* SELF */)}] = function(${N.frame}, pc, instr)
|
|
2681
|
+
local obj = ${N.frame}.${N.R}[instr.${N.b}]
|
|
2682
|
+
${N.frame}.${N.R}[instr.${N.a}] = obj[${N.rk}(${N.frame}, instr.${N.c})]
|
|
2683
|
+
${N.frame}.${N.R}[instr.${N.a} + 1] = obj
|
|
2684
|
+
return ${N.dispatch}(${N.frame}, pc + 1)
|
|
2685
|
+
end
|
|
2686
|
+
|
|
2687
|
+
-- ADD SUB MUL DIV MOD POW
|
|
2688
|
+
${N.handlers}[${op(12 /* ADD */)}] = function(${N.frame}, pc, instr)
|
|
2689
|
+
${N.frame}.${N.R}[instr.${N.a}] = ${N.rk}(${N.frame}, instr.${N.b}) + ${N.rk}(${N.frame}, instr.${N.c})
|
|
2690
|
+
return ${N.dispatch}(${N.frame}, pc + 1)
|
|
2691
|
+
end
|
|
2692
|
+
${N.handlers}[${op(13 /* SUB */)}] = function(${N.frame}, pc, instr)
|
|
2693
|
+
${N.frame}.${N.R}[instr.${N.a}] = ${N.rk}(${N.frame}, instr.${N.b}) - ${N.rk}(${N.frame}, instr.${N.c})
|
|
2694
|
+
return ${N.dispatch}(${N.frame}, pc + 1)
|
|
2695
|
+
end
|
|
2696
|
+
${N.handlers}[${op(14 /* MUL */)}] = function(${N.frame}, pc, instr)
|
|
2697
|
+
${N.frame}.${N.R}[instr.${N.a}] = ${N.rk}(${N.frame}, instr.${N.b}) * ${N.rk}(${N.frame}, instr.${N.c})
|
|
2698
|
+
return ${N.dispatch}(${N.frame}, pc + 1)
|
|
2699
|
+
end
|
|
2700
|
+
${N.handlers}[${op(15 /* DIV */)}] = function(${N.frame}, pc, instr)
|
|
2701
|
+
${N.frame}.${N.R}[instr.${N.a}] = ${N.rk}(${N.frame}, instr.${N.b}) / ${N.rk}(${N.frame}, instr.${N.c})
|
|
2702
|
+
return ${N.dispatch}(${N.frame}, pc + 1)
|
|
2703
|
+
end
|
|
2704
|
+
${N.handlers}[${op(16 /* MOD */)}] = function(${N.frame}, pc, instr)
|
|
2705
|
+
${N.frame}.${N.R}[instr.${N.a}] = ${N.rk}(${N.frame}, instr.${N.b}) % ${N.rk}(${N.frame}, instr.${N.c})
|
|
2706
|
+
return ${N.dispatch}(${N.frame}, pc + 1)
|
|
2707
|
+
end
|
|
2708
|
+
${N.handlers}[${op(17 /* POW */)}] = function(${N.frame}, pc, instr)
|
|
2709
|
+
${N.frame}.${N.R}[instr.${N.a}] = ${N.rk}(${N.frame}, instr.${N.b}) ^ ${N.rk}(${N.frame}, instr.${N.c})
|
|
2710
|
+
return ${N.dispatch}(${N.frame}, pc + 1)
|
|
2711
|
+
end
|
|
2712
|
+
|
|
2713
|
+
-- IDIV (Luau \uBC14\uB2E5 \uB098\uB217\uC148)
|
|
2714
|
+
${N.handlers}[${op(34 /* IDIV */)}] = function(${N.frame}, pc, instr)
|
|
2715
|
+
${N.frame}.${N.R}[instr.${N.a}] = ${N.rk}(${N.frame}, instr.${N.b}) // ${N.rk}(${N.frame}, instr.${N.c})
|
|
2716
|
+
return ${N.dispatch}(${N.frame}, pc + 1)
|
|
2717
|
+
end
|
|
2718
|
+
|
|
2719
|
+
-- CONCAT
|
|
2720
|
+
${N.handlers}[${op(18 /* CONCAT */)}] = function(${N.frame}, pc, instr)
|
|
2721
|
+
${N.frame}.${N.R}[instr.${N.a}] = ${N.rk}(${N.frame}, instr.${N.b}) .. ${N.rk}(${N.frame}, instr.${N.c})
|
|
2722
|
+
return ${N.dispatch}(${N.frame}, pc + 1)
|
|
2723
|
+
end
|
|
2724
|
+
|
|
2725
|
+
-- UNM
|
|
2726
|
+
${N.handlers}[${op(19 /* UNM */)}] = function(${N.frame}, pc, instr)
|
|
2727
|
+
${N.frame}.${N.R}[instr.${N.a}] = -${N.frame}.${N.R}[instr.${N.b}]
|
|
2728
|
+
return ${N.dispatch}(${N.frame}, pc + 1)
|
|
2729
|
+
end
|
|
2730
|
+
|
|
2731
|
+
-- NOT
|
|
2732
|
+
${N.handlers}[${op(20 /* NOT */)}] = function(${N.frame}, pc, instr)
|
|
2733
|
+
${N.frame}.${N.R}[instr.${N.a}] = not ${N.frame}.${N.R}[instr.${N.b}]
|
|
2734
|
+
return ${N.dispatch}(${N.frame}, pc + 1)
|
|
2735
|
+
end
|
|
2736
|
+
|
|
2737
|
+
-- LEN
|
|
2738
|
+
${N.handlers}[${op(21 /* LEN */)}] = function(${N.frame}, pc, instr)
|
|
2739
|
+
${N.frame}.${N.R}[instr.${N.a}] = #${N.frame}.${N.R}[instr.${N.b}]
|
|
2740
|
+
return ${N.dispatch}(${N.frame}, pc + 1)
|
|
2741
|
+
end
|
|
2742
|
+
|
|
2743
|
+
-- JMP (pc += a)
|
|
2744
|
+
${N.handlers}[${op(22 /* JMP */)}] = function(${N.frame}, pc, instr)
|
|
2745
|
+
return ${N.dispatch}(${N.frame}, pc + instr.${N.a})
|
|
2746
|
+
end
|
|
2747
|
+
|
|
2748
|
+
-- EQ LT LE (\uAC12 \uC0DD\uC131\uD615 \uBE44\uAD50)
|
|
2749
|
+
${N.handlers}[${op(23 /* EQ */)}] = function(${N.frame}, pc, instr)
|
|
2750
|
+
${N.frame}.${N.R}[instr.${N.a}] = ${N.rk}(${N.frame}, instr.${N.b}) == ${N.rk}(${N.frame}, instr.${N.c})
|
|
2751
|
+
return ${N.dispatch}(${N.frame}, pc + 1)
|
|
2752
|
+
end
|
|
2753
|
+
${N.handlers}[${op(24 /* LT */)}] = function(${N.frame}, pc, instr)
|
|
2754
|
+
${N.frame}.${N.R}[instr.${N.a}] = ${N.rk}(${N.frame}, instr.${N.b}) < ${N.rk}(${N.frame}, instr.${N.c})
|
|
2755
|
+
return ${N.dispatch}(${N.frame}, pc + 1)
|
|
2756
|
+
end
|
|
2757
|
+
${N.handlers}[${op(25 /* LE */)}] = function(${N.frame}, pc, instr)
|
|
2758
|
+
${N.frame}.${N.R}[instr.${N.a}] = ${N.rk}(${N.frame}, instr.${N.b}) <= ${N.rk}(${N.frame}, instr.${N.c})
|
|
2759
|
+
return ${N.dispatch}(${N.frame}, pc + 1)
|
|
2760
|
+
end
|
|
2761
|
+
|
|
2762
|
+
-- TEST (if (not R[a]) != (c!=0) then pc += 2 else pc += 1 \u2014 \uBCF4\uD1B5 \uB2E4\uC74C \uBA85\uB839\uC740 JMP)
|
|
2763
|
+
${N.handlers}[${op(26 /* TEST */)}] = function(${N.frame}, pc, instr)
|
|
2764
|
+
if (not ${N.frame}.${N.R}[instr.${N.a}]) ~= (instr.${N.c} ~= 0) then
|
|
2765
|
+
return ${N.dispatch}(${N.frame}, pc + 2)
|
|
2766
|
+
end
|
|
2767
|
+
return ${N.dispatch}(${N.frame}, pc + 1)
|
|
2768
|
+
end
|
|
2769
|
+
|
|
2770
|
+
-- CALL
|
|
2771
|
+
${N.handlers}[${op(27 /* CALL */)}] = function(${N.frame}, pc, instr)
|
|
2772
|
+
local a, b, c = instr.${N.a}, instr.${N.b}, instr.${N.c}
|
|
2773
|
+
local fn = ${N.frame}.${N.R}[a]
|
|
2774
|
+
local nargs
|
|
2775
|
+
if b == 0 then
|
|
2776
|
+
nargs = (${N.frame}.${N.multiTop} or (a + 1)) - (a + 1)
|
|
2777
|
+
else
|
|
2778
|
+
nargs = b - 1
|
|
2779
|
+
end
|
|
2780
|
+
local args = table.create(nargs)
|
|
2781
|
+
for i = 1, nargs do args[i] = ${N.frame}.${N.R}[a + i] end
|
|
2782
|
+
local rets = table.pack(fn(table.unpack(args, 1, nargs)))
|
|
2783
|
+
if c == 1 then
|
|
2784
|
+
-- discard
|
|
2785
|
+
elseif c == 0 then
|
|
2786
|
+
for i = 1, rets.n do ${N.frame}.${N.R}[a + i - 1] = rets[i] end
|
|
2787
|
+
${N.frame}.${N.multiTop} = a + rets.n
|
|
2788
|
+
else
|
|
2789
|
+
local want = c - 1
|
|
2790
|
+
for i = 1, want do ${N.frame}.${N.R}[a + i - 1] = rets[i] end
|
|
2791
|
+
end
|
|
2792
|
+
return ${N.dispatch}(${N.frame}, pc + 1)
|
|
2793
|
+
end
|
|
2794
|
+
|
|
2795
|
+
-- RETURN
|
|
2796
|
+
${N.handlers}[${op(28 /* RETURN */)}] = function(${N.frame}, pc, instr)
|
|
2797
|
+
local a, b = instr.${N.a}, instr.${N.b}
|
|
2798
|
+
if b == 0 then
|
|
2799
|
+
return table.unpack(${N.frame}.${N.R}, a, (${N.frame}.${N.multiTop} or (a + 1)) - 1)
|
|
2800
|
+
end
|
|
2801
|
+
return table.unpack(${N.frame}.${N.R}, a, a + b - 2)
|
|
2802
|
+
end
|
|
2803
|
+
|
|
2804
|
+
-- FORPREP
|
|
2805
|
+
${N.handlers}[${op(29 /* FORPREP */)}] = function(${N.frame}, pc, instr)
|
|
2806
|
+
local a = instr.${N.a}
|
|
2807
|
+
${N.frame}.${N.R}[a] = ${N.frame}.${N.R}[a] - ${N.frame}.${N.R}[a + 2]
|
|
2808
|
+
return ${N.dispatch}(${N.frame}, pc + instr.${N.b})
|
|
2809
|
+
end
|
|
2810
|
+
|
|
2811
|
+
-- FORLOOP
|
|
2812
|
+
${N.handlers}[${op(30 /* FORLOOP */)}] = function(${N.frame}, pc, instr)
|
|
2813
|
+
local a = instr.${N.a}
|
|
2814
|
+
local step = ${N.frame}.${N.R}[a + 2]
|
|
2815
|
+
${N.frame}.${N.R}[a] = ${N.frame}.${N.R}[a] + step
|
|
2816
|
+
local ok
|
|
2817
|
+
if step > 0 then
|
|
2818
|
+
ok = ${N.frame}.${N.R}[a] <= ${N.frame}.${N.R}[a + 1]
|
|
2819
|
+
else
|
|
2820
|
+
ok = ${N.frame}.${N.R}[a] >= ${N.frame}.${N.R}[a + 1]
|
|
2821
|
+
end
|
|
2822
|
+
if ok then
|
|
2823
|
+
${N.frame}.${N.R}[a + 3] = ${N.frame}.${N.R}[a]
|
|
2824
|
+
return ${N.dispatch}(${N.frame}, pc + instr.${N.b})
|
|
2825
|
+
end
|
|
2826
|
+
return ${N.dispatch}(${N.frame}, pc + 1)
|
|
2827
|
+
end
|
|
2828
|
+
|
|
2829
|
+
-- CLOSURE
|
|
2830
|
+
${N.handlers}[${op(31 /* CLOSURE */)}] = function(${N.frame}, pc, instr)
|
|
2831
|
+
local childProto = ${N.frame}.${N.protos}[instr.${N.b} + 1]
|
|
2832
|
+
local n = #childProto.${N.upvalDescs}
|
|
2833
|
+
local capturedUpvals = table.create(n)
|
|
2834
|
+
for i = 1, n do
|
|
2835
|
+
local desc = childProto.${N.upvalDescs}[i]
|
|
2836
|
+
local captureInstr = ${N.frame}.${N.code}[pc + i]
|
|
2837
|
+
if desc.${N.kind} == "local" then
|
|
2838
|
+
capturedUpvals[i] = ${N.frame}.${N.R}[captureInstr.${N.b}]
|
|
2839
|
+
else
|
|
2840
|
+
capturedUpvals[i] = ${N.frame}.${N.upvals}[captureInstr.${N.b} + 1]
|
|
2841
|
+
end
|
|
2842
|
+
end
|
|
2843
|
+
${N.frame}.${N.R}[instr.${N.a}] = function(...)
|
|
2844
|
+
return ${N.execute}(childProto, capturedUpvals, ...)
|
|
2845
|
+
end
|
|
2846
|
+
return ${N.dispatch}(${N.frame}, pc + 1 + n)
|
|
2847
|
+
end
|
|
2848
|
+
|
|
2849
|
+
-- VARARG
|
|
2850
|
+
${N.handlers}[${op(32 /* VARARG */)}] = function(${N.frame}, pc, instr)
|
|
2851
|
+
local count = instr.${N.b} == 0 and ${N.frame}.${N.nVarargs} or (instr.${N.b} - 1)
|
|
2852
|
+
for i = 1, count do
|
|
2853
|
+
${N.frame}.${N.R}[instr.${N.a} + i - 1] = ${N.frame}.${N.varargs}[i]
|
|
2854
|
+
end
|
|
2855
|
+
if instr.${N.b} == 0 then
|
|
2856
|
+
${N.frame}.${N.multiTop} = instr.${N.a} + count
|
|
2857
|
+
end
|
|
2858
|
+
return ${N.dispatch}(${N.frame}, pc + 1)
|
|
2859
|
+
end
|
|
2860
|
+
|
|
2861
|
+
-- SETLIST
|
|
2862
|
+
${N.handlers}[${op(33 /* SETLIST */)}] = function(${N.frame}, pc, instr)
|
|
2863
|
+
local tbl = ${N.frame}.${N.R}[instr.${N.a}]
|
|
2864
|
+
local valuesBase = instr.${N.b}
|
|
2865
|
+
local top = ${N.frame}.${N.multiTop} or (valuesBase + 1)
|
|
2866
|
+
local startIdx = instr.${N.c}
|
|
2867
|
+
local n = top - valuesBase
|
|
2868
|
+
for i = 0, n - 1 do
|
|
2869
|
+
tbl[startIdx + i] = ${N.frame}.${N.R}[valuesBase + i]
|
|
2870
|
+
end
|
|
2871
|
+
return ${N.dispatch}(${N.frame}, pc + 1)
|
|
2872
|
+
end
|
|
2873
|
+
|
|
2874
|
+
function ${N.execute}(proto, upvals, ...)
|
|
2875
|
+
local nArgs = select("#", ...)
|
|
2876
|
+
local packedArgs = table.pack(...)
|
|
2877
|
+
local R = table.create(proto.${N.maxRegs} + 8)
|
|
2878
|
+
for i = 1, proto.${N.numParams} do
|
|
2879
|
+
R[i - 1] = packedArgs[i]
|
|
2880
|
+
end
|
|
2881
|
+
local nVarargs = 0
|
|
2882
|
+
local varargs = {}
|
|
2883
|
+
if proto.${N.hasVarargs} and nArgs > proto.${N.numParams} then
|
|
2884
|
+
nVarargs = nArgs - proto.${N.numParams}
|
|
2885
|
+
for i = 1, nVarargs do
|
|
2886
|
+
varargs[i] = packedArgs[proto.${N.numParams} + i]
|
|
2887
|
+
end
|
|
2888
|
+
end
|
|
2889
|
+
|
|
2890
|
+
local ${N.frame} = {
|
|
2891
|
+
${N.R} = R,
|
|
2892
|
+
${N.K} = proto.${N.consts},
|
|
2893
|
+
${N.code} = proto.${N.code},
|
|
2894
|
+
${N.protos} = proto.${N.protos},
|
|
2895
|
+
${N.upvals} = upvals,
|
|
2896
|
+
${N.varargs} = varargs,
|
|
2897
|
+
${N.nVarargs} = nVarargs,
|
|
2898
|
+
}
|
|
2899
|
+
|
|
2900
|
+
return ${N.dispatch}(${N.frame}, 1)
|
|
2901
|
+
end
|
|
2902
|
+
`;
|
|
2903
|
+
}
|
|
2904
|
+
|
|
2905
|
+
// src/passes/vmify/names.ts
|
|
2906
|
+
var ID_CHARS_HEAD = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_";
|
|
2907
|
+
var ID_CHARS_TAIL = ID_CHARS_HEAD + "0123456789";
|
|
2908
|
+
function makeIdGenerator(random) {
|
|
2909
|
+
const used = /* @__PURE__ */ new Set();
|
|
2910
|
+
return () => {
|
|
2911
|
+
let id;
|
|
2912
|
+
do {
|
|
2913
|
+
const len = 5 + Math.floor(random() * 5);
|
|
2914
|
+
let s = ID_CHARS_HEAD[Math.floor(random() * ID_CHARS_HEAD.length)];
|
|
2915
|
+
for (let i = 1; i < len; i++) s += ID_CHARS_TAIL[Math.floor(random() * ID_CHARS_TAIL.length)];
|
|
2916
|
+
id = s;
|
|
2917
|
+
} while (used.has(id));
|
|
2918
|
+
used.add(id);
|
|
2919
|
+
return id;
|
|
2920
|
+
};
|
|
2921
|
+
}
|
|
2922
|
+
function generateVmNames(random = Math.random) {
|
|
2923
|
+
const id = makeIdGenerator(random);
|
|
2924
|
+
return {
|
|
2925
|
+
globals: id(),
|
|
2926
|
+
protoRoot: id(),
|
|
2927
|
+
execute: id(),
|
|
2928
|
+
handlers: id(),
|
|
2929
|
+
dispatch: id(),
|
|
2930
|
+
rk: id(),
|
|
2931
|
+
frame: id(),
|
|
2932
|
+
R: id(),
|
|
2933
|
+
K: id(),
|
|
2934
|
+
code: id(),
|
|
2935
|
+
protos: id(),
|
|
2936
|
+
upvals: id(),
|
|
2937
|
+
varargs: id(),
|
|
2938
|
+
nVarargs: id(),
|
|
2939
|
+
multiTop: id(),
|
|
2940
|
+
op: id(),
|
|
2941
|
+
a: id(),
|
|
2942
|
+
b: id(),
|
|
2943
|
+
c: id(),
|
|
2944
|
+
numParams: id(),
|
|
2945
|
+
hasVarargs: id(),
|
|
2946
|
+
maxRegs: id(),
|
|
2947
|
+
consts: id(),
|
|
2948
|
+
upvalDescs: id(),
|
|
2949
|
+
kind: id(),
|
|
2950
|
+
index: id()
|
|
2951
|
+
};
|
|
2952
|
+
}
|
|
2953
|
+
|
|
2954
|
+
// src/passes/Vmify.ts
|
|
2955
|
+
function runVmify(program, options) {
|
|
2956
|
+
const globalNames = options.builtinGlobals ?? DEFAULT_BUILTIN_GLOBALS;
|
|
2957
|
+
const random = options.random ?? Math.random;
|
|
2958
|
+
const opcodeMap = createOpcodeMap(random);
|
|
2959
|
+
const names = generateVmNames(random);
|
|
2960
|
+
const compiler = new VmCompiler(program, globalNames, opcodeMap);
|
|
2961
|
+
const topProto = compiler.compile();
|
|
2962
|
+
const globalsTable = table(
|
|
2963
|
+
globalNames.map((name) => namedField(name, identifier(name)))
|
|
2964
|
+
);
|
|
2965
|
+
const runtimeSource = buildVmRuntimeSource(names, opcodeMap);
|
|
2966
|
+
const runtimeProgram = luauparser2.parse(runtimeSource);
|
|
2967
|
+
const runtimeStatements = runtimeProgram.body.statements;
|
|
2968
|
+
const protoLiteral = serializeProto(topProto, names);
|
|
2969
|
+
const newBody = [
|
|
2970
|
+
localStatement(names.globals, globalsTable),
|
|
2971
|
+
...runtimeStatements,
|
|
2972
|
+
localStatement(names.protoRoot, protoLiteral),
|
|
2973
|
+
returnStatement([call(identifier(names.execute), [identifier(names.protoRoot), table([]), vararg()])])
|
|
2974
|
+
];
|
|
2975
|
+
program.body.statements = newBody;
|
|
1007
2976
|
}
|
|
1008
2977
|
|
|
1009
2978
|
// src/pipeline.ts
|
|
1010
2979
|
var PASS_ORDER = [
|
|
2980
|
+
"Vmify",
|
|
1011
2981
|
"GlobalMapping",
|
|
1012
2982
|
"StringsToExpressions",
|
|
1013
2983
|
"NumbersToExpressions",
|
|
@@ -1016,7 +2986,6 @@ var PASS_ORDER = [
|
|
|
1016
2986
|
"EncryptStrings",
|
|
1017
2987
|
"EncryptNumbers",
|
|
1018
2988
|
"InsertJunk",
|
|
1019
|
-
"Vmify",
|
|
1020
2989
|
"WrapInFunction",
|
|
1021
2990
|
"Minify"
|
|
1022
2991
|
];
|
|
@@ -1029,7 +2998,8 @@ var PASS_MAP = {
|
|
|
1029
2998
|
EncryptStrings: runEncryptStrings,
|
|
1030
2999
|
EncryptNumbers: runEncryptNumbers,
|
|
1031
3000
|
InsertJunk: runInsertJunk,
|
|
1032
|
-
WrapInFunction: runWrapInFunction
|
|
3001
|
+
WrapInFunction: runWrapInFunction,
|
|
3002
|
+
Vmify: runVmify
|
|
1033
3003
|
};
|
|
1034
3004
|
function runPipeline(program, config) {
|
|
1035
3005
|
runStripTypes(program);
|
|
@@ -1052,11 +3022,11 @@ function minifyPrinted(code) {
|
|
|
1052
3022
|
function obfuscateByAst(program, PConfig) {
|
|
1053
3023
|
const config = mergeConfig(ObfuscateDefault, PConfig ?? {});
|
|
1054
3024
|
runPipeline(program, config);
|
|
1055
|
-
const printed =
|
|
3025
|
+
const printed = luauparser3.print(program);
|
|
1056
3026
|
return config.Minify.active ? minifyPrinted(printed) : printed;
|
|
1057
3027
|
}
|
|
1058
3028
|
function obfuscate(source, PConfig) {
|
|
1059
|
-
const program =
|
|
3029
|
+
const program = luauparser3.parse(source);
|
|
1060
3030
|
return obfuscateByAst(program, PConfig);
|
|
1061
3031
|
}
|
|
1062
3032
|
export {
|