-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathLuaDecomp.pas
More file actions
2073 lines (1917 loc) · 82.3 KB
/
Copy pathLuaDecomp.pas
File metadata and controls
2073 lines (1917 loc) · 82.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
unit LuaDecomp;
{
LuaDecomp.pas - Structured control flow recovery and Lua source emitter.
Takes a TSSAFunction (from LuaSSA) and reconstructs high-level Lua 5.x
pseudo-source code.
Algorithm overview
------------------
1. ConstantFold – evaluate compile-time constant SSA_BINOP / SSA_UNOP nodes.
2. CopyPropagate – replace trivial SSA_MOVE / single-operand SSA_PHI uses.
3. DeadEliminate – mark nodes whose dest has no uses; skip them at emit.
4. ExprBuild – recursively convert each SSA value to an expression string.
5. CFGStructure – identify loops (back-edges), if/then/else, for-loops etc.
6. EmitRegion – walk the structured CFG and emit Lua code.
The emitter works on the raw SSA CFG (blocks + nodes) with a recursive
region-detection approach:
• A "loop region" is identified by a block whose dominator chain contains
the block itself (back-edge target = loop header).
• An "if region" is identified by a branch node whose two successors share
a common post-dominator (the merge block).
• Remaining blocks are emitted linearly.
Variable naming
---------------
Debug info (LocVars) is used when available. Temporaries fall back to
"t<n>" names. Globals and upvalues use their string keys directly.
}
{$mode objfpc}{$H+}
interface
uses
SysUtils, Math, LuaChunk, LuaSSA, LuaOpcodes, LuaUtils, LuaExprUtils, LuaDis;
type
{ Options controlling the emitter }
TDecompOptions = record
Annotate : Boolean; { emit disassembly comments above each statement }
Debug : Boolean; { emit debug trace to stderr }
Indent : AnsiString; { indentation string, default ' ' }
FileName : AnsiString;
OT : POpcodeTable; { nil = Lua 5.1 legacy path }
end;
{ Decompile a single proto (non-recursive) to a string }
function DecompileProto(Proto: PProto; const Opts: TDecompOptions): AnsiString;
{ Decompile full chunk (recurses into sub-protos) and print to stdout }
procedure DecompileChunk(const Chunk: TLuaChunk; const Opts: TDecompOptions);
implementation
{ ======================================================================
Internal types
====================================================================== }
type
TAnsiStringArray = array of AnsiString;
{ Use-def tracking for dead-code elimination and copy propagation }
TUseCount = array of Integer; { indexed by (Reg * MaxVer + Ver) }
TExprMap = array of AnsiString; { cached expression strings per SSA value index }
{ Multi-assign detector result }
TMultiAssignResult = (maNotMatched, maEmitted);
{ Structured region classification }
TRegionKind = (rgLinear, rgIfThen, rgIfThenElse, rgWhile, rgRepeat,
rgNumericFor, rgGenericFor, rgReturn);
TRegion = record
Kind : TRegionKind;
Header : Integer; { block index }
TrueBlk : Integer;
FalseBlk : Integer;
MergeBlk : Integer;
LoopBack : Integer;
BodyBlk : Integer;
ExitBlk : Integer;
end;
{ ======================================================================
TStringList (lightweight)
====================================================================== }
type
TStringList = class
private
FLines: array of AnsiString;
FCount: Integer;
public
procedure Add(const S: AnsiString);
function Text: AnsiString;
function Count: Integer;
function GetLine(Idx: Integer): AnsiString;
procedure SetLine(Idx: Integer; const S: AnsiString);
procedure Insert(Idx: Integer; const S: AnsiString);
procedure DeleteLast;
end;
{ ======================================================================
TRunMode - controls output format of Run()
====================================================================== }
type
TRunMode = (
rmChunk, { top-level entry: emit body directly, no function wrapper }
rmFunction, { full function(...)...end wrapper (standalone proto dump) }
rmBodyOnly { body only, no wrapper. For embedding into parent closures }
);
{ ======================================================================
TDecompiler (private class per proto)
====================================================================== }
type
TDecompiler = class
private
FProto : PProto;
FSF : PSSAFunction;
FOpts : TDecompOptions;
FOutput : TStringList;
FIndent : Integer;
{ max version seen per register (for indexing) }
FMaxVer : Integer;
{ use counts: (reg * FMaxVer + ver) -> count }
FUseCnt : array of Integer;
{ expression strings for each SSA value (same indexing) }
FExprStr : array of AnsiString;
{ set of nodes already inlined into expressions (don't emit again) }
FInlined : array of Boolean;
{ visited set for cycle detection in ExprOf }
FVisited : array of Boolean;
{ recursion depth counter for ExprOf }
FExprDepth : Integer;
{ block visit tracking for CFG walk }
FEmitted : array of Boolean;
{ set to True whenever EmitStmt/EmitStruct emits 'break' or 'return', cleared on other emits }
FLastBreak : Boolean;
{ count of real emitted constructs (for SSA emission invariant) }
FStmtCount : Integer;
{ track which sub-protos were inlined (skip in DecompileProtoRec) }
FInlinedProtos : array of Boolean;
{ track which LocVars have been declared (for 'local' keyword emission) }
FDeclared : array of Boolean;
{ track which temp registers (t<N>) have been declared local in stripped mode }
FTempDeclared : array of Boolean;
{ stack of loop exit block indices for break detection }
FLoopExitStack : array of Integer;
FLoopExitTop : Integer;
{ upvalue names resolved from parent context (for stripped bytecode) }
FUpvalNames : array of AnsiString;
{ parameter name overrides (for collision avoidance with upvalue names) }
FParamOverrides : array of AnsiString;
{ Global do..end scope tracking (computed once, used during emission) }
FPendingScopes : array of record
StartPC: Integer; { PC at which to emit "do" (LocVar.StartPC - 1) }
EndPC: Integer; { PC at which to emit "end" (LocVar.EndPC) }
end;
FPendingScopeCount : Integer;
FActiveScopeStack : array of Integer; { indices into FPendingScopes }
FActiveScopeTop : Integer;
FNextPendingScope : Integer;
{ SSA definition lookup map: [Reg][Version] --> defining node }
FDefNodeMap : array of array of PSSANode;
{ Annotation support: PC of the current node being emitted (-1 = none) }
FAnnotatePC : Integer;
{ Set of PCs already annotated (avoid duplicate annotations) }
FAnnotatedPCs : array of Boolean;
procedure PushLoopExit(ExitBlk: Integer);
procedure PopLoopExit;
function CurrentLoopExit: Integer;
function IsBreakTarget(Blk: Integer): Boolean;
procedure Indent;
procedure Dedent;
procedure Emit(const S: AnsiString);
procedure EmitAny(const S: AnsiString; CountAsStmt: Boolean);
procedure EmitStmt(const S: AnsiString);
procedure EmitStruct(const S: AnsiString);
procedure EmitEmbed(const S: AnsiString);
procedure EmitLine(const S: AnsiString); { backward-compat alias for EmitStmt }
procedure EmitAnnotation(PC: Integer);
function NodeIdx(Reg, Ver: Integer): Integer;
function CountPhiUses(Reg, Ver: Integer): Integer;
function ConstStr(Idx: Integer): AnsiString;
function LocVarInScope(VarIdx, PC: Integer): Boolean;
function LocalName(Reg, PC: Integer): AnsiString;
function UpvalName(Idx: Integer): AnsiString;
function RegRef(const R: TSSARef; PC: Integer): AnsiString;
{ Expression building }
function ExprOf(const R: TSSARef; PC: Integer): AnsiString;
function NodeExpr(Node: PSSANode): AnsiString;
function BinOpStr(Op: TBinOp): AnsiString;
function BinOpPrec(Op: TBinOp): Integer;
function UnOpStr(Op: TUnOp): AnsiString;
function RelOpStr(Op: TRelOp; Invert: Boolean): AnsiString;
function FlippedRelOpStr(Op: TRelOp; Invert: Boolean): AnsiString;
function BuildCompare(const OpA, OpB: TSSARef;
Op: TRelOp; Invert: Boolean;
PC: Integer): AnsiString;
{ Constant folding }
procedure FoldConstants;
{ Count uses of each SSA value across all nodes }
procedure CountUses;
{ SSA-level LocVar binding }
procedure BindLocVarsToSSA;
{ Global do..end scope computation }
function FindLocVarDefPC(VarIdx: Integer): Integer;
procedure ComputeDoEndScopes;
{ Node-based naming (LocVarIdx-based, no PC heuristics) }
function NodeIsLocal(Node: PSSANode): Boolean;
function NodeNeedsDecl(Node: PSSANode): Boolean;
function NodeLocalName(Node: PSSANode): AnsiString;
procedure NodeMarkDeclared(Node: PSSANode);
function NodeIsEmittableLocal(Node: PSSANode): Boolean;
{ SSA DefNodeMap: (Reg, Version) --> defining node }
procedure BuildDefNodeMap;
function DefNodeFor(const Op: TSSARef): PSSANode;
{ SSA definition lookup }
function FindDefNode(BIdx, Reg: Integer): PSSANode;
function FindDefNodeAll(Reg: Integer): PSSANode;
function RegExpr(Reg, PC: Integer): AnsiString;
function CallFuncExpr(Reg, BeforePC: Integer): AnsiString;
function IsUserLocal(Reg, PC: Integer): Boolean;
function IsUserLocalStrict(Reg, PC: Integer): Boolean;
function ShouldEmitAsLocal(Reg, PC: Integer): Boolean;
function LocalNameForEmit(Reg, PC: Integer): AnsiString;
function NeedsLocalDecl(Reg, PC: Integer): Boolean;
function IsBareLocalDecl(Reg, PC: Integer): Boolean;
function IsOnlyPhiUsed(Reg, Version: Integer): Boolean;
function IsOnlyTrivialPhiUsed(Reg, Version: Integer): Boolean;
function IsUpvalCaptured(Reg, DefPC: Integer): Boolean;
function ShouldEmitTemp(Reg, Version, PC: Integer): Boolean;
function NeedsTempLocal(Reg: Integer): Boolean;
function TempName(Reg: Integer): AnsiString;
{ Structured emission }
function FindMerge(BranchBlk, TrueBlk, FalseBlk: Integer): Integer;
function IsLoopHeader(BIdx: Integer): Boolean;
function FindLoopExit(HeaderIdx: Integer): Integer;
function IsRepeatUntilLoop(HeaderIdx: Integer): Boolean;
function FindRepeatUntilExit(HeaderIdx: Integer): Integer;
function EmitForNumericLoop(BIdx: Integer): Integer;
function EmitForGenericLoop(BIdx: Integer): Integer;
procedure EmitBlock(BIdx: Integer);
procedure EmitRegion(BIdx: Integer; StopAt: Integer = -1);
procedure EmitIfRegion(BranchBlk, TrueBlk, FalseBlk, MergeBlk: Integer);
procedure EmitIfRegionCompound(BranchBlk, TrueBlk, FalseBlk, MergeBlk: Integer;
const CompoundCond: AnsiString);
procedure EmitWhileRegion(HeaderBlk: Integer);
procedure EmitRepeatRegion(HeaderBlk: Integer);
procedure EmitNode(Node: PSSANode; BIdx: Integer);
procedure EmitReturnOnly(BlkIdx: Integer);
function TryEmitBreakIf(BranchBlk, TrueBlk, FalseBlk: Integer;
out NextBlk: Integer): Boolean;
function TryEmitOrAnd(BranchBlk, TrueBlk, FalseBlk: Integer): Boolean;
function TryCacheBranchValueSelect(BranchBlk, TrueBlk, FalseBlk: Integer): Boolean;
function TryBuildCompoundCond(BranchBlk: Integer;
out CondExpr: AnsiString;
out TrueTarget, FalseTarget: Integer): Boolean;
function TryBuildComparisonExpr(PhiNode: PSSANode): AnsiString;
function TryBuildOrAndExpr(PhiNode: PSSANode): AnsiString;
function TryBuildNegatedCompoundExpr(PhiNode: PSSANode): AnsiString;
function TryBuildChainedPhiExpr(PhiNode: PSSANode): AnsiString;
function TryEmitMultiLocal(BIdx, StartIdx: Integer; out ConsumedCount: Integer): Boolean;
function TryEmitMultiAssign(BIdx, StartIdx: Integer; out ConsumedCount: Integer): TMultiAssignResult;
function TryEmitMultiReturnAssign(BIdx, StartIdx: Integer; out ConsumedCount: Integer): TMultiAssignResult;
function TryEmitReverseMultiAssign(BIdx, StartIdx: Integer; out ConsumedCount: Integer): TMultiAssignResult;
function TryEmitSwap(BIdx, StartIdx: Integer; out ConsumedCount: Integer): TMultiAssignResult;
function TryEmitTableSwap(BIdx, StartIdx: Integer; out ConsumedCount: Integer): Boolean;
function TryEmitTableConstructor(BIdx, StartIdx: Integer; out ConsumedCount: Integer): Boolean;
procedure EmitTempLoweredMultiAssign(
const LHSNames: array of AnsiString;
const RHSExprs: array of AnsiString;
const LHSNeedsLocalDecl: array of Boolean;
const LHSIsTableAccess: array of Boolean);
function MultiAssignNeedsTemps(Blk: PBasicBlock;
ComputeStart, ComputeEnd: Integer;
WriteBackStart, WriteBackEnd: Integer): Boolean;
function TryBuildInnerTableCtor(BIdx, StartIdx: Integer;
out ConsumedCount: Integer;
out CtorStr: AnsiString): Boolean;
function IsSelfRefClosure(Node: PSSANode): Boolean;
function ResolveUpvalNames(ClosurePC, SubProtoIdx: Integer): TAnsiStringArray;
function BuildSubProtoParams(SubProto: PProto;
const UpvalNames: TAnsiStringArray;
SkipSelf: Boolean = False): AnsiString;
function DecompileSubProto(SubProtoIdx: Integer; ClosurePC: Integer = -1): AnsiString;
procedure EmitClosureReturn(ClosureNode: PSSANode);
function TryEmitInlineFunction(SetNode: PSSANode; const FuncName: AnsiString): Boolean;
function TryEmitLocalFunction(ClosureNode: PSSANode; const FuncName: AnsiString; IsLocal: Boolean): Boolean;
function TryEmitSettableFunction(Node: PSSANode): Boolean;
function FuncHeader: AnsiString;
{ Post-emission single-line collapse helpers }
function TryCollapseSingleLineBlock(OpenIdx: Integer; StartPC, EndPC: Integer): Boolean;
function TryCollapseIfElseBlock(OpenIdx: Integer; StartPC, EndPC: Integer): Boolean;
{ Constant propagation / inline helpers }
function IsInlineable(const R: TSSARef): Boolean;
public
constructor Create(Proto: PProto; const Opts: TDecompOptions);
constructor Create(Proto: PProto; const Opts: TDecompOptions;
const UpvalNames: TAnsiStringArray);
destructor Destroy; override;
function Run(Mode: TRunMode = rmChunk): AnsiString;
end;
procedure TStringList.Add(const S: AnsiString);
begin
if FCount >= Length(FLines) then
SetLength(FLines, FCount * 2 + 8);
FLines[FCount] := S;
Inc(FCount);
end;
function TStringList.Text: AnsiString;
var
I: Integer;
begin
Result := '';
for I := 0 to FCount - 1 do
Result := Result + FLines[I] + LineEnding;
end;
function TStringList.Count: Integer;
begin
Result := FCount;
end;
function TStringList.GetLine(Idx: Integer): AnsiString;
begin
if (Idx >= 0) and (Idx < FCount) then
Result := FLines[Idx]
else
Result := '';
end;
procedure TStringList.SetLine(Idx: Integer; const S: AnsiString);
begin
if (Idx >= 0) and (Idx < FCount) then
FLines[Idx] := S;
end;
procedure TStringList.Insert(Idx: Integer; const S: AnsiString);
var
I: Integer;
begin
if Idx < 0 then Idx := 0;
if Idx > FCount then Idx := FCount;
if FCount >= Length(FLines) then
SetLength(FLines, FCount * 2 + 8);
for I := FCount downto Idx + 1 do
FLines[I] := FLines[I - 1];
FLines[Idx] := S;
Inc(FCount);
end;
procedure TStringList.DeleteLast;
begin
if FCount > 0 then
Dec(FCount);
end;
{ String manipulation utilities (StripOuterParens, InvertAtom, ApplyDeMorgan,
ParenthesizeMixedNotCompare, GroupMixedAndOr) moved to LuaExprUtils.pas }
{ ======================================================================
TDecompiler implementation
====================================================================== }
constructor TDecompiler.Create(Proto: PProto; const Opts: TDecompOptions);
var
I: Integer;
begin
inherited Create;
FProto := Proto;
FOpts := Opts;
FOutput := TStringList.Create;
FIndent := 0;
FExprDepth := 0;
FLoopExitTop := -1;
FAnnotatePC := -1;
FSF := BuildSSAFunction(Proto, FOpts.OT);
{ Compute FMaxVer from the actual maximum SSA version seen across all nodes }
FMaxVer := 1;
for I := 0 to High(FSF^.AllNodes) do begin
if FSF^.AllNodes[I]^.Dest.Version >= FMaxVer then
FMaxVer := FSF^.AllNodes[I]^.Dest.Version + 1;
end;
if FMaxVer < Proto^.MaxStack * 4 + 16 then
FMaxVer := Proto^.MaxStack * 4 + 16; { minimum safety margin }
SetLength(FInlinedProtos, Length(Proto^.P));
if FOpts.Annotate then
SetLength(FAnnotatedPCs, Length(Proto^.Code));
end;
constructor TDecompiler.Create(Proto: PProto; const Opts: TDecompOptions;
const UpvalNames: TAnsiStringArray);
var
I, J: Integer;
ParamName: AnsiString;
Collision: Boolean;
begin
Create(Proto, Opts);
SetLength(FUpvalNames, Length(UpvalNames));
for I := 0 to High(UpvalNames) do
FUpvalNames[I] := UpvalNames[I];
{ Detect collisions between upvalue names and parameter names.
When a parameter name would collide with an upvalue name,
override the parameter to use 'arg<N>' instead. }
SetLength(FParamOverrides, Proto^.NumParams);
for I := 0 to Proto^.NumParams - 1 do begin
if I < Length(Proto^.LocVars) then
ParamName := Proto^.LocVars[I].Name
else
ParamName := 'a' + IntToStr(I);
Collision := False;
for J := 0 to High(FUpvalNames) do begin
if FUpvalNames[J] = ParamName then begin
Collision := True;
Break;
end;
end;
if Collision then
FParamOverrides[I] := 'arg' + IntToStr(I)
else
FParamOverrides[I] := ''; { no override needed }
end;
end;
destructor TDecompiler.Destroy;
begin
FOutput.Free;
FreeSSAFunction(FSF);
inherited;
end;
{ Loop exit stack helpers for break detection }
procedure TDecompiler.PushLoopExit(ExitBlk: Integer);
begin
Inc(FLoopExitTop);
if FLoopExitTop >= Length(FLoopExitStack) then
SetLength(FLoopExitStack, FLoopExitTop + 8);
FLoopExitStack[FLoopExitTop] := ExitBlk;
end;
procedure TDecompiler.PopLoopExit;
begin
if FLoopExitTop >= 0 then Dec(FLoopExitTop);
end;
function TDecompiler.CurrentLoopExit: Integer;
begin
if FLoopExitTop >= 0 then
Result := FLoopExitStack[FLoopExitTop]
else
Result := -1;
end;
function TDecompiler.IsBreakTarget(Blk: Integer): Boolean;
{ Check if Blk is (or leads to) the current loop exit block.
A break target is either the exit block itself, or a JMP-only
trampoline block whose sole successor is the exit block. }
var
ExitB, J: Integer;
IsJmp: Boolean;
begin
Result := False;
ExitB := CurrentLoopExit;
if ExitB < 0 then Exit;
if Blk = ExitB then begin Result := True; Exit; end;
{ Check if Blk is a JMP-only block leading to ExitB }
if (Blk >= 0) and (Blk < Length(FSF^.Blocks)) then begin
if Length(FSF^.Blocks[Blk].Succs) = 1 then begin
IsJmp := True;
for J := 0 to High(FSF^.Blocks[Blk].Nodes) do
if not (FSF^.Blocks[Blk].Nodes[J]^.Kind in [SSA_JUMP, SSA_PHI, SSA_NOP]) then begin
IsJmp := False; Break;
end;
if IsJmp and (FSF^.Blocks[Blk].Succs[0] = ExitB) then
Result := True;
end;
end;
end;
procedure TDecompiler.Indent;
begin
Inc(FIndent);
end;
procedure TDecompiler.Dedent;
begin
if FIndent > 0 then Dec(FIndent);
end;
procedure TDecompiler.Emit(const S: AnsiString);
var
Pad: AnsiString;
P, LineStart: Integer;
Line: AnsiString;
begin
Pad := StringOfChar(' ', FIndent * 2);
{ If S contains embedded newlines (multi-line expressions like closures),
indent each line individually so the output is properly formatted. }
if Pos(#10, S) > 0 then begin
P := 1;
while P <= Length(S) do begin
LineStart := P;
while (P <= Length(S)) and (S[P] <> #10) do
Inc(P);
Line := Copy(S, LineStart, P - LineStart);
if (Length(Line) > 0) and (Line[Length(Line)] = #13) then
Line := Copy(Line, 1, Length(Line) - 1);
FOutput.Add(Pad + Line);
Inc(P); { skip LF }
end;
end else
FOutput.Add(Pad + S);
end;
procedure TDecompiler.EmitAny(const S: AnsiString; CountAsStmt: Boolean);
var
LastIdx: Integer;
LastLine, TrimmedLast: AnsiString;
begin
if (FAnnotatePC >= 0) and FOpts.Annotate then
EmitAnnotation(FAnnotatePC);
if CountAsStmt and FLastBreak and
(S <> 'end') and (S <> 'else') and
(Copy(S, 1, 7) <> 'elseif ') then begin
LastIdx := FOutput.Count - 1;
if LastIdx >= 0 then begin
LastLine := FOutput.GetLine(LastIdx);
TrimmedLast := Trim(LastLine);
if ((TrimmedLast = 'break') or (Copy(TrimmedLast, 1, 6) = 'return')) and
(Copy(TrimmedLast, 1, 3) <> 'do ') then
FOutput.SetLine(LastIdx, StringOfChar(' ', FIndent * 2) +
'do ' + TrimmedLast + ' end');
end;
end;
FLastBreak := (S = 'break') or (Copy(S, 1, 6) = 'return');
if CountAsStmt then Inc(FStmtCount);
Emit(S);
end;
procedure TDecompiler.EmitStmt(const S: AnsiString);
begin EmitAny(S, True); end;
procedure TDecompiler.EmitStruct(const S: AnsiString);
begin EmitAny(S, False); end;
procedure TDecompiler.EmitEmbed(const S: AnsiString);
begin Emit(S); end; { raw re-emit: no annotation, no FLastBreak, no counting }
procedure TDecompiler.EmitLine(const S: AnsiString);
begin EmitStmt(S); end; { backward-compat alias }
procedure TDecompiler.EmitAnnotation(PC: Integer);
var
DisStr: AnsiString;
begin
if not FOpts.Annotate then Exit;
if (PC < 0) or (PC > High(FProto^.Code)) then Exit;
{ Skip if already annotated this PC }
if (PC < Length(FAnnotatedPCs)) and FAnnotatedPCs[PC] then Exit;
if PC < Length(FAnnotatedPCs) then
FAnnotatedPCs[PC] := True;
{ Format the instruction }
if FOpts.OT <> nil then
DisStr := FormatInstructionV(FProto^, PC, FOpts.OT^)
else
DisStr := FormatInstruction(FProto^, PC);
Emit('-- ' + DisStr);
end;
function TDecompiler.TryCollapseSingleLineBlock(OpenIdx: Integer; StartPC, EndPC: Integer): Boolean;
{ Try to collapse a block like:
if cond then (OpenIdx)
body (OpenIdx+1)
end (OpenIdx+2)
into: if cond then body end
Also handles: for...do...end, while...do...end, repeat...until
OpenIdx: FOutput index of the opening line
StartPC: PC of the opening instruction (BRANCH/FORPREP/TEST etc.)
EndPC: PC of the closing instruction (JMP after body / FORLOOP / BRANCH at tail).
All LineInfo entries from StartPC to EndPC must map to the same source line.
Pass StartPC=-1 to skip LineInfo check.
Returns True if collapsed. }
var
CurCount: Integer;
OpenLine, BodyLine, CloseLine: AnsiString;
Collapsed: AnsiString;
SrcLine, I: Integer;
begin
Result := False;
CurCount := FOutput.Count;
{ Need exactly 3 lines: open, body, close }
if CurCount <> OpenIdx + 3 then Exit;
OpenLine := Trim(FOutput.GetLine(OpenIdx));
BodyLine := Trim(FOutput.GetLine(OpenIdx + 1));
CloseLine := Trim(FOutput.GetLine(OpenIdx + 2));
{ Opening line must end with 'then', 'do', or be 'repeat' }
if not ((Length(OpenLine) >= 4) and (Copy(OpenLine, Length(OpenLine) - 3, 4) = 'then')) and
not ((Length(OpenLine) >= 2) and (Copy(OpenLine, Length(OpenLine) - 1, 2) = 'do')) and
not (OpenLine = 'repeat') then
Exit;
{ Closing line must be 'end' or start with 'until ' }
if (CloseLine <> 'end') and (Copy(CloseLine, 1, 6) <> 'until ') then
Exit;
{ Body must not itself be a block opener }
if (Copy(BodyLine, 1, 3) = 'if ') or
(Copy(BodyLine, 1, 4) = 'for ') or
(Copy(BodyLine, 1, 6) = 'while ') or
(Copy(BodyLine, 1, 7) = 'repeat ') or
(Copy(BodyLine, 1, 3) = 'do ') then
Exit;
{ LineInfo check: all PCs from StartPC to EndPC must be on the same source line }
if (StartPC >= 0) and (StartPC < Length(FProto^.LineInfo)) and
(EndPC >= StartPC) and (EndPC < Length(FProto^.LineInfo)) then begin
SrcLine := FProto^.LineInfo[StartPC];
if SrcLine <= 0 then Exit;
for I := StartPC + 1 to EndPC do begin
if FProto^.LineInfo[I] <> SrcLine then
Exit; { Multi-line block - don't collapse }
end;
end else if StartPC >= 0 then
Exit; { Invalid PC range - don't collapse }
{ Build collapsed line }
if CloseLine = 'end' then
Collapsed := OpenLine + ' ' + BodyLine + ' end'
else
Collapsed := OpenLine + ' ' + BodyLine + ' ' + CloseLine;
{ Check length (with indentation) }
if FIndent * 2 + Length(Collapsed) >= 80 then Exit;
{ Perform collapse: replace open with collapsed, remove body+close }
FOutput.SetLine(OpenIdx, StringOfChar(' ', FIndent * 2) + Collapsed);
FOutput.DeleteLast; { remove close line }
FOutput.DeleteLast; { remove body line }
Result := True;
end;
function TDecompiler.TryCollapseIfElseBlock(OpenIdx: Integer; StartPC, EndPC: Integer): Boolean;
{ Try to collapse an if-then-else block:
if cond then (OpenIdx)
body1 (OpenIdx+1)
else (OpenIdx+2)
body2 (OpenIdx+3)
end (OpenIdx+4)
into: if cond then body1 else body2 end
StartPC/EndPC: LineInfo range to verify single-line origin.
Returns True if collapsed. }
var
CurCount: Integer;
IfLine, Body1, ElseLine, Body2, EndLine: AnsiString;
Collapsed: AnsiString;
SrcLine, I: Integer;
begin
Result := False;
CurCount := FOutput.Count;
{ Need exactly 5 lines: if, body1, else, body2, end }
if CurCount <> OpenIdx + 5 then Exit;
IfLine := Trim(FOutput.GetLine(OpenIdx));
Body1 := Trim(FOutput.GetLine(OpenIdx + 1));
ElseLine := Trim(FOutput.GetLine(OpenIdx + 2));
Body2 := Trim(FOutput.GetLine(OpenIdx + 3));
EndLine := Trim(FOutput.GetLine(OpenIdx + 4));
{ Validate structure }
if not ((Length(IfLine) >= 4) and (Copy(IfLine, Length(IfLine) - 3, 4) = 'then')) then Exit;
if ElseLine <> 'else' then Exit;
if EndLine <> 'end' then Exit;
{ Bodies must not be block openers }
if (Copy(Body1, 1, 3) = 'if ') or (Copy(Body1, 1, 4) = 'for ') or
(Copy(Body1, 1, 6) = 'while ') or (Copy(Body1, 1, 7) = 'repeat') or
(Copy(Body1, 1, 3) = 'do ') then Exit;
if (Copy(Body2, 1, 3) = 'if ') or (Copy(Body2, 1, 4) = 'for ') or
(Copy(Body2, 1, 6) = 'while ') or (Copy(Body2, 1, 7) = 'repeat') or
(Copy(Body2, 1, 3) = 'do ') then Exit;
{ LineInfo check }
if (StartPC >= 0) and (StartPC < Length(FProto^.LineInfo)) and
(EndPC >= StartPC) and (EndPC < Length(FProto^.LineInfo)) then begin
SrcLine := FProto^.LineInfo[StartPC];
if SrcLine <= 0 then Exit;
for I := StartPC + 1 to EndPC do begin
if FProto^.LineInfo[I] <> SrcLine then
Exit;
end;
end else if StartPC >= 0 then
Exit;
Collapsed := IfLine + ' ' + Body1 + ' else ' + Body2 + ' end';
if FIndent * 2 + Length(Collapsed) >= 80 then Exit;
FOutput.SetLine(OpenIdx, StringOfChar(' ', FIndent * 2) + Collapsed);
FOutput.DeleteLast; { end }
FOutput.DeleteLast; { body2 }
FOutput.DeleteLast; { else }
FOutput.DeleteLast; { body1 }
Result := True;
end;
{ ======================================================================
Utility: valid Lua identifier check (used by dot-notation logic)
====================================================================== }
function IsValidLuaIdent(const S: AnsiString): Boolean;
var
I: Integer;
begin
Result := False;
if Length(S) = 0 then Exit;
if (S = 'and') or (S = 'break') or (S = 'do') or (S = 'else') or
(S = 'elseif') or (S = 'end') or (S = 'false') or (S = 'for') or
(S = 'function') or (S = 'if') or (S = 'in') or (S = 'local') or
(S = 'nil') or (S = 'not') or (S = 'or') or (S = 'repeat') or
(S = 'return') or (S = 'then') or (S = 'true') or (S = 'until') or
(S = 'while') then Exit;
if not (S[1] in ['A'..'Z','a'..'z','_']) then Exit;
for I := 2 to Length(S) do
if not (S[I] in ['A'..'Z','a'..'z','0'..'9','_']) then Exit;
Result := True;
end;
{ ======================================================================
BuildDefNodeMap: populate FDefNodeMap[Reg][Version] --> defining node.
Called once in Run(), after FoldConstants (which mutates Node^.Kind),
before BindLocVarsToSSA.
====================================================================== }
procedure TDecompiler.BuildDefNodeMap;
var
I, R, V, MaxReg: Integer;
Node: PSSANode;
MaxVer: array of Integer;
begin
{ Pass 1: find max register }
MaxReg := -1;
for I := 0 to High(FSF^.AllNodes) do begin
Node := FSF^.AllNodes[I];
R := Node^.Dest.Reg;
if R > MaxReg then MaxReg := R;
end;
{ Include implicit defs (TFORLOOP loop vars, CALL extra returns, SELF R(A+1)) }
for I := 0 to High(FSF^.ImplicitDefs) do
if FSF^.ImplicitDefs[I].Reg > MaxReg then
MaxReg := FSF^.ImplicitDefs[I].Reg;
if MaxReg < 0 then Exit;
{ Find max version per register }
SetLength(MaxVer, MaxReg + 1);
for I := 0 to MaxReg do MaxVer[I] := -1;
for I := 0 to High(FSF^.AllNodes) do begin
Node := FSF^.AllNodes[I];
R := Node^.Dest.Reg;
if (R >= 0) and (Node^.Dest.Version > MaxVer[R]) then
MaxVer[R] := Node^.Dest.Version;
end;
for I := 0 to High(FSF^.ImplicitDefs) do begin
R := FSF^.ImplicitDefs[I].Reg;
if (R >= 0) and (R <= MaxReg) and
(FSF^.ImplicitDefs[I].Version > MaxVer[R]) then
MaxVer[R] := FSF^.ImplicitDefs[I].Version;
end;
{ Allocate }
SetLength(FDefNodeMap, MaxReg + 1);
for R := 0 to MaxReg do begin
if MaxVer[R] >= 0 then begin
SetLength(FDefNodeMap[R], MaxVer[R] + 1);
for V := 0 to MaxVer[R] do
FDefNodeMap[R][V] := nil;
end;
end;
{ Pass 2: populate with uniqueness assertion }
for I := 0 to High(FSF^.AllNodes) do begin
Node := FSF^.AllNodes[I];
R := Node^.Dest.Reg;
V := Node^.Dest.Version;
if (R >= 0) and (V >= 0) and (R < Length(FDefNodeMap)) and
(V < Length(FDefNodeMap[R])) then begin
if FDefNodeMap[R][V] <> nil then begin
if FOpts.Debug then
WriteLn(StdErr, 'WARNING: duplicate def for R', R, '_', V,
' at PC ', Node^.PC, ' (existing at PC ',
FDefNodeMap[R][V]^.PC, ')');
end else
FDefNodeMap[R][V] := Node;
end;
end;
{ Pass 3: populate implicit defs (TFORLOOP loop vars, CALL multi-return,
SELF implicit copy). Maps (Reg,Version) --> parent node.
Never overwrite: if an AllNodes entry already claimed this slot, keep it. }
for I := 0 to High(FSF^.ImplicitDefs) do begin
R := FSF^.ImplicitDefs[I].Reg;
V := FSF^.ImplicitDefs[I].Version;
if (R >= 0) and (V >= 0) and (R < Length(FDefNodeMap)) and
(V < Length(FDefNodeMap[R])) then begin
if FDefNodeMap[R][V] = nil then
FDefNodeMap[R][V] := FSF^.ImplicitDefs[I].ParentNode;
end;
end;
end;
{ DefNodeFor: resolve (Reg, Version) --> defining PSSANode.
Returns nil for constants (Reg=-2), no-ref (Reg=-1), or out-of-range. }
function TDecompiler.DefNodeFor(const Op: TSSARef): PSSANode;
begin
if (Op.Reg < 0) or (Op.Reg >= Length(FDefNodeMap)) then Exit(nil);
if (Op.Version < 0) or (Op.Version >= Length(FDefNodeMap[Op.Reg])) then Exit(nil);
Result := FDefNodeMap[Op.Reg][Op.Version];
end;
{ NodeIsEmittableLocal: True only for user-visible locals (not internal
for-loop vars, not implicit 'arg' in 5.1 vararg). No PC scanning. }
function TDecompiler.NodeIsEmittableLocal(Node: PSSANode): Boolean;
var
Name: AnsiString;
begin
Result := False;
if (Node = nil) or (Node^.LocVarIdx < 0) or
(Node^.LocVarIdx > High(FProto^.LocVars)) then Exit;
Name := FProto^.LocVars[Node^.LocVarIdx].Name;
if Length(Name) = 0 then Exit;
{ Exclude internal for-loop locals: (for index), (for limit), etc. }
if Name[1] = '(' then Exit;
{ Exclude implicit 'arg' local in Lua 5.1 vararg functions }
if (FSF^.LuaVersion <= $51) and (Name = 'arg') and
((FProto^.IsVarArg and 1) <> 0) and
(Node^.Dest.Reg = FProto^.NumParams) then Exit;
{ First char must be letter or underscore }
if not (Name[1] in ['a'..'z', 'A'..'Z', '_']) then Exit;
Result := True;
end;
procedure TDecompiler.EmitReturnOnly(BlkIdx: Integer);
{ Emit only SSA_RETURN and SSA_TAILCALL nodes from a block using EmitNode.
No scope management, no successor traversal, no FEmitted mutation.
Handles all RETURN variants (bare, single/multi-value, closure return,
tailcall, vararg) via existing EmitNode dispatch. }
var
I: Integer;
Node: PSSANode;
begin
if (BlkIdx < 0) or (BlkIdx >= Length(FSF^.Blocks)) then Exit;
for I := 0 to High(FSF^.Blocks[BlkIdx].Nodes) do begin
Node := FSF^.Blocks[BlkIdx].Nodes[I];
if Node^.Kind in [SSA_RETURN, SSA_TAILCALL] then
EmitNode(Node, BlkIdx);
end;
end;
{ ======================================================================
Include files: method implementations split for maintainability
====================================================================== }
{$I LuaDecompNaming.inc}
{$I LuaDecompExpr.inc}
{ Strip only terminal CR/LF characters from a string (not other whitespace) }
function StripTrailingNewline(const S: AnsiString): AnsiString;
var
L: Integer;
begin
L := Length(S);
while (L > 0) and (S[L] in [#10, #13]) do Dec(L);
Result := Copy(S, 1, L);
end;
{$I LuaDecompCF.inc}
{$I LuaDecompEmitNode.inc}
{$I LuaDecompBoolean.inc}
{$I LuaDecompMulti.inc}
{$I LuaDecompClosure.inc}
procedure TDecompiler.EmitBlock(BIdx: Integer);
var
I, J: Integer;
Node: PSSANode;
SwapCount: Integer;
begin
I := 0;
while I <= High(FSF^.Blocks[BIdx].Nodes) do begin
Node := FSF^.Blocks[BIdx].Nodes[I];
{ Skip pseudo-definition nodes (IsMetaOnly) - they exist solely for
LocVar binding in SSA and must not be emitted or processed by
multi-assign detectors. }
if Node^.IsMetaOnly then begin Inc(I); Continue; end;
{ Close expired do..end scopes (inner-first = top of stack first) }
while FActiveScopeTop > 0 do begin
if Node^.PC < FPendingScopes[FActiveScopeStack[FActiveScopeTop - 1]].EndPC then
Break;
Dec(FActiveScopeTop);
Dedent;
EmitStruct('end');
end;
{ Open pending do..end scopes (outer-first = ascending order) }
while FNextPendingScope < FPendingScopeCount do begin
if Node^.PC < FPendingScopes[FNextPendingScope].StartPC then Break;
EmitStruct('do');
Indent;
FActiveScopeStack[FActiveScopeTop] := FNextPendingScope;
Inc(FActiveScopeTop);
Inc(FNextPendingScope);
end;
{ Try to detect multiple assignment (local a, b, c = 1, 2, 3) }
if (Node^.Kind in [SSA_LOADK, SSA_LOADBOOL, SSA_LOADNIL,
SSA_GETGLOBAL, SSA_GETTABLE, SSA_GETUPVAL,
SSA_MOVE, SSA_BINOP, SSA_UNOP, SSA_CONCAT]) then
case TryEmitMultiAssign(BIdx, I, SwapCount) of
maEmitted: begin Inc(I, SwapCount); Continue; end;
maNotMatched: ;
end;
{ Try to detect multi-return CALL/VARARG + MOVEs (p, a, s = func(...) or a, b = ...) }
if (Node^.Kind in [SSA_CALL, SSA_VARARG]) then
case TryEmitMultiReturnAssign(BIdx, I, SwapCount) of
maEmitted: begin Inc(I, SwapCount); Continue; end;
maNotMatched: ;
end;
{ Try to detect reverse multi-assign: value-compute + reverse MOVEs
Handles: a, b = ... | a, b, c = 1, ... | a, b, c = 1, f(multi)
Also: a, b, c = f(single-ret), 1, 2 (CALL with ImmC=2 + LOADKs + MOVEs)
Also: t, b, c, d = clock, initial[k], v - initial[k], duration
(eval into temps + reverse MOVEs to user locals, with optional direct writes) }
if (Node^.Kind in [SSA_LOADK, SSA_LOADBOOL, SSA_LOADNIL,
SSA_GETGLOBAL, SSA_GETTABLE, SSA_GETUPVAL,
SSA_MOVE, SSA_BINOP, SSA_UNOP, SSA_CONCAT,
SSA_VARARG, SSA_CALL, SSA_NEWTABLE]) then
case TryEmitReverseMultiAssign(BIdx, I, SwapCount) of
maEmitted: begin Inc(I, SwapCount); Continue; end;
maNotMatched: ;
end;
{ Try to detect variable swap pattern (3 consecutive MOVEs) }
if (Node^.Kind = SSA_MOVE) then
case TryEmitSwap(BIdx, I, SwapCount) of
maEmitted: begin Inc(I, SwapCount); Continue; end;
maNotMatched: ;
end;
{ Try to detect table element swap: t[a],t[b] = t[b],t[a] }
if (Node^.Kind = SSA_GETTABLE) and TryEmitTableSwap(BIdx, I, SwapCount) then begin
Inc(I, SwapCount);
Continue;
end;
{ Try to detect inline table constructor (NEWTABLE + LOADKs + SETTABLEs + SETLIST) }
if (Node^.Kind = SSA_NEWTABLE) and TryEmitTableConstructor(BIdx, I, SwapCount) then begin
Inc(I, SwapCount);
Continue;
end;
{ Try to detect multi-local declaration with trailing nil stripping:
local v, w = 0 (instead of "local v = 0; local w") }
if (Node^.Kind in [SSA_LOADK, SSA_LOADBOOL, SSA_MOVE, SSA_GETGLOBAL,
SSA_GETTABLE, SSA_GETUPVAL, SSA_BINOP, SSA_UNOP,
SSA_CONCAT, SSA_CALL]) and