-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathLuaDecompClosure.inc
More file actions
790 lines (710 loc) · 27.4 KB
/
Copy pathLuaDecompClosure.inc
File metadata and controls
790 lines (710 loc) · 27.4 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
function TDecompiler.IsSelfRefClosure(Node: PSSANode): Boolean;
var
SubProto: PProto;
NUps, I, PseudoPC: Integer;
Inst: TInstruction;
Op: TOpCode;
B: Integer;
begin
Result := False;
if (Node = nil) or (Node^.Kind <> SSA_CLOSURE) then Exit;
if (Node^.ConstIdx < 0) or (Node^.ConstIdx >= Length(FProto^.P)) then Exit;
SubProto := FProto^.P[Node^.ConstIdx];
NUps := SubProto^.NUps;
if NUps = 0 then Exit;
if FProto^.LuaVersion >= $52 then begin
{ 5.2+: upvalue descriptors are in SubProto^.UpvalDescs }
for I := 0 to NUps - 1 do begin
if (I < Length(SubProto^.UpvalDescs)) and
SubProto^.UpvalDescs[I].InStack and
(SubProto^.UpvalDescs[I].Idx = Node^.Dest.Reg) then begin
Result := True;
Exit;
end;
end;
end else begin
{ 5.1: scan pseudo-instructions after CLOSURE }
for I := 0 to NUps - 1 do begin
PseudoPC := Node^.PC + 1 + I;
if PseudoPC >= Length(FProto^.Code) then Continue;
Inst := FProto^.Code[PseudoPC];
Op := GET_OPCODE(Inst);
B := GETARG_B(Inst);
{ If a MOVE pseudo-instruction binds to the CLOSURE's own destination register }
if (Op = OP_MOVE) and (B = Node^.Dest.Reg) then begin
Result := True;
Exit;
end;
end;
end;
end;
{ ======================================================================
ResolveUpvalNames - read pseudo-instructions after CLOSURE to map child
upvalues to parent register/upvalue names (for stripped bytecode)
====================================================================== }
function TDecompiler.ResolveUpvalNames(ClosurePC, SubProtoIdx: Integer): TAnsiStringArray;
var
SubProto: PProto;
NUps, I, PseudoPC, B, ScanPC, J: Integer;
Inst, ScanInst: TInstruction;
Op, ScanOp: TOpCode;
NameFromExpr: Boolean;
Name: AnsiString;
InStack: Boolean;
function IsSafeUpvalueName(const S: AnsiString): Boolean;
var
P, StartPos: Integer;
Part: AnsiString;
begin
Result := False;
if S = '' then Exit;
if IsValidLuaIdent(S) then begin
Result := True;
Exit;
end;
{ Accept dotted identifier paths (module.field), but reject literals and
general expressions. Upvalue names are emitted as lvalues/table bases;
using a cached string literal like "pkg.mod" would generate invalid Lua
when later field accesses append ".name". }
StartPos := 1;
P := 1;
while P <= Length(S) + 1 do begin
if (P > Length(S)) or (S[P] = '.') then begin
Part := Copy(S, StartPos, P - StartPos);
if not IsValidLuaIdent(Part) then Exit;
StartPos := P + 1;
end
else if not (S[P] in ['A'..'Z', 'a'..'z', '0'..'9', '_', '.']) then
Exit;
Inc(P);
end;
Result := True;
end;
begin
SetLength(Result, 0);
if (SubProtoIdx < 0) or (SubProtoIdx >= Length(FProto^.P)) then Exit;
SubProto := FProto^.P[SubProtoIdx];
NUps := SubProto^.NUps;
if NUps = 0 then Exit;
{ 5.2+: upvalue descriptors are stored in the proto, no pseudo-instructions }
if FProto^.LuaVersion >= $52 then begin
SetLength(Result, NUps);
for I := 0 to NUps - 1 do begin
if I >= Length(SubProto^.UpvalDescs) then begin
Result[I] := '_upval' + IntToStr(I);
Continue;
end;
InStack := SubProto^.UpvalDescs[I].InStack;
B := SubProto^.UpvalDescs[I].Idx;
if InStack then begin
{ Upvalue captures parent register B }
{ Check for self-reference }
if B = GETARG_A(FProto^.Code[ClosurePC]) then begin
Result[I] := 'func_' + IntToStr(SubProtoIdx);
Continue;
end;
Result[I] := LocalName(B, ClosurePC);
end else begin
{ Upvalue copies parent upvalue B }
Result[I] := UpvalName(B);
end;
end;
Exit;
end;
{ 5.1: scan pseudo-instructions after CLOSURE }
SetLength(Result, NUps);
for I := 0 to NUps - 1 do begin
PseudoPC := ClosurePC + 1 + I;
if PseudoPC >= Length(FProto^.Code) then begin
Result[I] := '_upval' + IntToStr(I);
Continue;
end;
Inst := FProto^.Code[PseudoPC];
Op := GET_OPCODE(Inst);
B := GETARG_B(Inst);
if Op = OP_MOVE then begin
{ Check for self-reference: upvalue binds to the CLOSURE's own dest register }
if B = GETARG_A(FProto^.Code[ClosurePC]) then begin
{ Self-referencing closure - use a generated function name }
Name := 'func_' + IntToStr(SubProtoIdx);
Result[I] := Name;
Continue;
end;
{ Upvalue I binds to parent register B.
First check FExprStr: if the register was a closure that was cached
as func_N or a local name, use that cached name.
IMPORTANT: Only accept short identifier-like names (e.g., "func_N",
"t50", local variable names). Skip full expressions like function
bodies or compound expressions that were cached by NodeExpr. }
Name := '';
{ Find the SSA definition of register B at or before ClosurePC.
Only look at REAL definitions (CLOSURE, NEWTABLE, GETTABLE, etc.),
skip NOP pseudo-instructions (upvalue binding hints) as they create
spurious SSA versions of R(A) that may have stale FExprStr.
Also skip SETTABLE (writes to a table slot, not the register itself). }
for J := 0 to High(FSF^.AllNodes) do begin
if (FSF^.AllNodes[J]^.Kind <> SSA_NOP) and
(FSF^.AllNodes[J]^.Kind <> SSA_SETTABLE) and
(FSF^.AllNodes[J]^.Kind <> SSA_SETGLOBAL) and
(FSF^.AllNodes[J]^.Kind <> SSA_SETUPVAL) and
(FSF^.AllNodes[J]^.Dest.Reg = B) and
(FSF^.AllNodes[J]^.PC <= ClosurePC) then begin
ScanPC := NodeIdx(B, FSF^.AllNodes[J]^.Dest.Version);
if (ScanPC >= 0) and (ScanPC < Length(FExprStr)) and
(FExprStr[ScanPC] <> '') and (FExprStr[ScanPC] <> '__swap_temp__') and
(Pos('function', FExprStr[ScanPC]) = 0) and { skip full closure bodies }
(Pos(#10, FExprStr[ScanPC]) = 0) and { skip multi-line expressions }
(Length(FExprStr[ScanPC]) < 80) and { skip long expressions }
IsSafeUpvalueName(FExprStr[ScanPC]) then
Name := FExprStr[ScanPC];
end;
end;
{ If still unnamed and register B is a CLOSURE, try to find the table key
this closure was assigned to (e.g. SETTABLE easing_tbl "outQuad" R_B).
The key name then serves as the upvalue reference via the table. }
if (Name = '') then begin
for ScanPC := ClosurePC downto 0 do begin
if GET_OPCODE(FProto^.Code[ScanPC]) = OP_CLOSURE then begin
if GETARG_A(FProto^.Code[ScanPC]) = B then begin
{ Found the CLOSURE that defines register B.
Now scan forward for a SETTABLE that uses B as a value. }
for J := ScanPC + 1 to Length(FProto^.Code) - 1 do begin
if GET_OPCODE(FProto^.Code[J]) = OP_SETTABLE then begin
{ SETTABLE A B C: table[RK(B)] = RK(C).
If C = register B (our closure), extract the key name. }
if (not ISK(GETARG_C(FProto^.Code[J]))) and
(GETARG_C(FProto^.Code[J]) = B) then begin
{ Key is RK(B) of SETTABLE }
if ISK(GETARG_B(FProto^.Code[J])) then begin
Name := ConstStr(INDEXRK(GETARG_B(FProto^.Code[J])));
{ Strip quotes from string constants }
if (Length(Name) >= 2) and (Name[1] = '"') then
Name := Copy(Name, 2, Length(Name) - 2);
{ Build table.field reference using the table's name }
Name := TempName(GETARG_A(FProto^.Code[J])) + '.' + Name;
end;
Break;
end;
end;
if GET_OPCODE(FProto^.Code[J]) = OP_RETURN then Break;
end;
Break;
end;
end;
end;
end;
NameFromExpr := (Name <> '');
if Name = '' then
Name := LocalName(B, ClosurePC);
{ If the name is a temp (t<N>) and came from LocalName (not FExprStr),
try to trace back through MOVE chains to find a parameter or meaningful
source. Scan backwards from ClosurePC.
NOTE: Only do this when FExprStr/SETTABLE didn't provide a name,
because those names are authoritative (NEWTABLE/CLOSURE definitions). }
if (not NameFromExpr) and
(Length(Name) >= 2) and (Name[1] = 't') then begin
for ScanPC := ClosurePC - 1 downto 0 do begin
ScanInst := FProto^.Code[ScanPC];
ScanOp := GET_OPCODE(ScanInst);
if (ScanOp = OP_MOVE) and (GETARG_A(ScanInst) = B) then begin
{ Found: MOVE B = ScanB. Check if ScanB has a name }
J := GETARG_B(ScanInst);
Name := LocalName(J, ScanPC);
if (Length(Name) >= 2) and (Name[1] = 't') then
Continue { still a temp, keep tracing }
else
Break; { found a real name }
end else if (ScanOp <> OP_MOVE) and (GETARG_A(ScanInst) = B) then
Break; { B redefined by non-MOVE, stop tracing }
end;
end;
Result[I] := Name;
end
else if Op = OP_GETUPVAL then begin
{ Upvalue I binds to parent's upvalue B - chain through parent's upvalue names }
Result[I] := UpvalName(B);
end
else
Result[I] := '_upval' + IntToStr(I);
end;
end;
{ ======================================================================
BuildSubProtoParams - build parameter list for a sub-proto, avoiding
name collisions with upvalue names by using 'arg<N>' for conflicts
====================================================================== }
function TDecompiler.BuildSubProtoParams(SubProto: PProto;
const UpvalNames: TAnsiStringArray;
SkipSelf: Boolean = False): AnsiString;
var
I, J: Integer;
PName: AnsiString;
Collision: Boolean;
begin
Result := '';
for I := 0 to SubProto^.NumParams - 1 do begin
if SkipSelf and (I = 0) then Continue;
if Result <> '' then Result := Result + ', ';
{ Get the default parameter name }
if I < Length(SubProto^.LocVars) then
PName := SubProto^.LocVars[I].Name
else
PName := 'a' + IntToStr(I);
{ Check for collision with upvalue names }
Collision := False;
for J := 0 to High(UpvalNames) do begin
if UpvalNames[J] = PName then begin
Collision := True;
Break;
end;
end;
if Collision then
PName := 'arg' + IntToStr(I);
Result := Result + PName;
end;
{ Lua 5.1: IsVarArg is a 3-bit field (bit 1 = VARARG_ISVARARG).
Lua 5.2+: IsVarArg is a simple boolean (0 = no, 1 = yes). }
if SubProto^.LuaVersion >= $52 then begin
if SubProto^.IsVarArg <> 0 then begin
if Result <> '' then Result := Result + ', ';
Result := Result + '...';
end;
end else begin
if (SubProto^.IsVarArg and 2) <> 0 then begin
if Result <> '' then Result := Result + ', ';
Result := Result + '...';
end;
end;
end;
{ ======================================================================
DecompileSubProto - decompile a child proto into a function literal string
====================================================================== }
function TDecompiler.DecompileSubProto(SubProtoIdx: Integer; ClosurePC: Integer = -1): AnsiString;
var
SubProto: PProto;
SubOutput: AnsiString;
D: TDecompiler;
Params: AnsiString;
P, LineStart: Integer;
Line: AnsiString;
Body: AnsiString;
UVNames: TAnsiStringArray;
begin
if (SubProtoIdx < 0) or (SubProtoIdx >= Length(FProto^.P)) then begin
Result := '<closure:P' + IntToStr(SubProtoIdx) + '>'; Exit;
end;
SubProto := FProto^.P[SubProtoIdx];
{ Mark this sub-proto as inlined so DecompileProtoRec skips it }
if SubProtoIdx < Length(FInlinedProtos) then
FInlinedProtos[SubProtoIdx] := True;
{ Resolve upvalue names and build parameter list with collision avoidance }
SetLength(UVNames, 0);
if ClosurePC >= 0 then
UVNames := ResolveUpvalNames(ClosurePC, SubProtoIdx);
Params := BuildSubProtoParams(SubProto, UVNames);
{ Decompile the sub-proto body (rmBodyOnly: no function wrapper, indent 0) }
if Length(UVNames) > 0 then
D := TDecompiler.Create(SubProto, FOpts, UVNames)
else
D := TDecompiler.Create(SubProto, FOpts);
try
SubOutput := StripTrailingNewline(D.Run(rmBodyOnly));
finally
D.Free;
end;
{ Single-line heuristic: use LineDefined as formatting hint when available.
For stripped bytecode (LineDefined=LastLineDefined=0), allow single-line.
For non-stripped multi-line (LineDefined<>LastLineDefined), force multi-line. }
Line := Trim(SubOutput);
if (SubProto^.LineDefined = SubProto^.LastLineDefined) and
(Pos(#10, Line) = 0) and (Pos(#13, Line) = 0) and
(Length(Line) + Length(Params) + 18 < 80) and
(Line <> '') then
Result := 'function(' + Params + ') ' + Line + ' end'
else begin
{ Multi-line: iterate body lines, prepend 2 spaces for wrapper indent }
Body := '';
P := 1;
while P <= Length(SubOutput) do begin
LineStart := P;
while (P <= Length(SubOutput)) and (SubOutput[P] <> #10) do Inc(P);
Line := Copy(SubOutput, LineStart, P - LineStart);
{ Remove trailing CR if present }
if (Length(Line) > 0) and (Line[Length(Line)] = #13) then
Line := Copy(Line, 1, Length(Line) - 1);
Inc(P); { skip the LF }
if Body <> '' then Body := Body + LineEnding;
Body := Body + ' ' + Line;
end;
if Body = '' then
Result := 'function(' + Params + ') end'
else
Result := 'function(' + Params + ')' + LineEnding + Body + LineEnding + 'end';
end;
end;
{ ======================================================================
EmitClosureReturn - emit "return function(...) body end" with indentation
====================================================================== }
procedure TDecompiler.EmitClosureReturn(ClosureNode: PSSANode);
var
SubProtoIdx: Integer;
SubProto: PProto;
Params: AnsiString;
SubOutput, Line, Body: AnsiString;
D: TDecompiler;
UVNames: TAnsiStringArray;
P, LineStart: Integer;
begin
SubProtoIdx := ClosureNode^.ConstIdx;
if (SubProtoIdx < 0) or (SubProtoIdx >= Length(FProto^.P)) then begin
EmitLine('return <closure:P' + IntToStr(SubProtoIdx) + '>');
Exit;
end;
SubProto := FProto^.P[SubProtoIdx];
{ Mark as inlined }
if SubProtoIdx < Length(FInlinedProtos) then
FInlinedProtos[SubProtoIdx] := True;
{ Resolve upvalue names and build parameter list with collision avoidance }
UVNames := ResolveUpvalNames(ClosureNode^.PC, SubProtoIdx);
Params := BuildSubProtoParams(SubProto, UVNames);
{ Decompile sub-proto body (rmBodyOnly: no wrapper, indent 0) }
D := TDecompiler.Create(SubProto, FOpts, UVNames);
try
SubOutput := StripTrailingNewline(D.Run(rmBodyOnly));
finally
D.Free;
end;
{ Single-line check: use LineDefined as formatting hint when available }
Body := Trim(SubOutput);
if (SubProto^.LineDefined = SubProto^.LastLineDefined) and
(Pos(#10, Body) = 0) and (Pos(#13, Body) = 0) and
(Length('return function(' + Params + ') ' + Body + ' end') + FIndent * 2 < 80) then begin
if Body <> '' then
EmitLine('return function(' + Params + ') ' + Body + ' end')
else
EmitLine('return function(' + Params + ') end');
Exit;
end;
{ Multi-line: return function(params)\n body\nend }
EmitStmt('return function(' + Params + ')');
Indent;
P := 1;
while P <= Length(SubOutput) do begin
LineStart := P;
while (P <= Length(SubOutput)) and (SubOutput[P] <> #10) do
Inc(P);
Line := Copy(SubOutput, LineStart, P - LineStart);
if (Length(Line) > 0) and (Line[Length(Line)] = #13) then
Line := Copy(Line, 1, Length(Line) - 1);
Inc(P);
EmitEmbed(Line);
end;
Dedent;
EmitStruct('end');
end;
{ ======================================================================
TryEmitInlineFunction - detect SETGLOBAL of CLOSURE and emit inline
====================================================================== }
function TDecompiler.TryEmitInlineFunction(SetNode: PSSANode; const FuncName: AnsiString): Boolean;
var
ClosureNode: PSSANode;
SubProtoIdx: Integer;
SubProto: PProto;
SubOutput: AnsiString;
D: TDecompiler;
Line: AnsiString;
P, LineStart: Integer;
Params: AnsiString;
I: Integer;
UVNames: TAnsiStringArray;
begin
Result := False;
{ Find the CLOSURE node that defines OpA }
ClosureNode := nil;
if SetNode^.OpA.Reg >= 0 then begin
{ Search for defining node of OpA }
for I := 0 to High(FSF^.AllNodes) do begin
if RefEqual(FSF^.AllNodes[I]^.Dest, SetNode^.OpA) then begin
ClosureNode := FSF^.AllNodes[I];
Break;
end;
end;
end;
if (ClosureNode = nil) or (ClosureNode^.Kind <> SSA_CLOSURE) then Exit;
SubProtoIdx := ClosureNode^.ConstIdx;
if (SubProtoIdx < 0) or (SubProtoIdx >= Length(FProto^.P)) then Exit;
SubProto := FProto^.P[SubProtoIdx];
{ Mark this sub-proto as inlined so DecompileProtoRec skips it }
if SubProtoIdx < Length(FInlinedProtos) then
FInlinedProtos[SubProtoIdx] := True;
{ Resolve upvalue names and build parameter list with collision avoidance }
UVNames := ResolveUpvalNames(ClosureNode^.PC, SubProtoIdx);
Params := BuildSubProtoParams(SubProto, UVNames);
{ Decompile sub-proto body (rmBodyOnly: no wrapper, indent 0) }
D := TDecompiler.Create(SubProto, FOpts, UVNames);
try
SubOutput := StripTrailingNewline(D.Run(rmBodyOnly));
finally
D.Free;
end;
{ Choose between "function FuncName(params)" sugar form and
"FuncName = function(params)" assignment form.
Heuristic: if the SETGLOBAL's line < CLOSURE's line, the source used
the sugar form (SETGLOBAL points to `function` keyword, CLOSURE to `end`).
If SETGLOBAL's line >= CLOSURE's line, the assignment form was used. }
if (SetNode^.PC >= 0) and (SetNode^.PC < Length(FProto^.LineInfo)) and
(ClosureNode^.PC >= 0) and (ClosureNode^.PC < Length(FProto^.LineInfo)) and
(FProto^.LineInfo[SetNode^.PC] >= FProto^.LineInfo[ClosureNode^.PC]) then
EmitStmt(FuncName + ' = function(' + Params + ')')
else
EmitStmt('function ' + FuncName + '(' + Params + ')');
Indent;
{ Emit body lines (rmBodyOnly output at indent 0, no stripping needed) }
P := 1;
while P <= Length(SubOutput) do begin
LineStart := P;
while (P <= Length(SubOutput)) and (SubOutput[P] <> #10) do
Inc(P);
Line := Copy(SubOutput, LineStart, P - LineStart);
if (Length(Line) > 0) and (Line[Length(Line)] = #13) then
Line := Copy(Line, 1, Length(Line) - 1);
Inc(P);
EmitEmbed(Line);
end;
Dedent;
EmitStruct('end');
Result := True;
end;
{ ======================================================================
TryEmitLocalFunction - emit CLOSURE as "local function name()" form
====================================================================== }
function TDecompiler.TryEmitLocalFunction(ClosureNode: PSSANode;
const FuncName: AnsiString; IsLocal: Boolean): Boolean;
var
SubProtoIdx: Integer;
SubProto: PProto;
SubOutput: AnsiString;
D: TDecompiler;
Line: AnsiString;
P, LineStart: Integer;
Params: AnsiString;
Prefix: AnsiString;
UVNames: TAnsiStringArray;
Body: AnsiString;
begin
Result := False;
if (ClosureNode = nil) or (ClosureNode^.Kind <> SSA_CLOSURE) then Exit;
SubProtoIdx := ClosureNode^.ConstIdx;
if (SubProtoIdx < 0) or (SubProtoIdx >= Length(FProto^.P)) then Exit;
SubProto := FProto^.P[SubProtoIdx];
{ Mark this sub-proto as inlined so DecompileProtoRec skips it }
if SubProtoIdx < Length(FInlinedProtos) then
FInlinedProtos[SubProtoIdx] := True;
{ Resolve upvalue names and build parameter list with collision avoidance }
UVNames := ResolveUpvalNames(ClosureNode^.PC, SubProtoIdx);
Params := BuildSubProtoParams(SubProto, UVNames);
{ Decompile sub-proto body (rmBodyOnly: no wrapper, indent 0) }
D := TDecompiler.Create(SubProto, FOpts, UVNames);
try
SubOutput := StripTrailingNewline(D.Run(rmBodyOnly));
finally
D.Free;
end;
{ Single-line check: use LineDefined as formatting hint when available.
For stripped (LineDefined=LastLineDefined=0), allow single-line.
For non-stripped multi-line, force multi-line. }
Body := Trim(SubOutput);
if (SubProto^.LineDefined = SubProto^.LastLineDefined) and
(Pos(#10, Body) = 0) and (Pos(#13, Body) = 0) then begin
{ Build prefix }
if IsLocal then begin
if IsSelfRefClosure(ClosureNode) then
Prefix := 'local function ' + FuncName + '(' + Params + ')'
else
Prefix := 'local ' + FuncName + ' = function(' + Params + ')';
end else
Prefix := FuncName + ' = function(' + Params + ')';
{ Build single-line }
if Body <> '' then
Line := Prefix + ' ' + Body + ' end'
else
Line := Prefix + ' end';
if Length(Line) < 80 then begin
EmitLine(Line);
Result := True;
Exit;
end;
end;
{ Multi-line emit }
if IsLocal then begin
if IsSelfRefClosure(ClosureNode) then
EmitStmt('local function ' + FuncName + '(' + Params + ')')
else
EmitStmt('local ' + FuncName + ' = function(' + Params + ')');
end else
EmitStmt(FuncName + ' = function(' + Params + ')');
Indent;
{ Emit body lines (rmBodyOnly output at indent 0, no stripping needed) }
P := 1;
while P <= Length(SubOutput) do begin
LineStart := P;
while (P <= Length(SubOutput)) and (SubOutput[P] <> #10) do
Inc(P);
Line := Copy(SubOutput, LineStart, P - LineStart);
if (Length(Line) > 0) and (Line[Length(Line)] = #13) then
Line := Copy(Line, 1, Length(Line) - 1);
Inc(P);
EmitEmbed(Line);
end;
Dedent;
EmitStruct('end');
Result := True;
end;
{ ======================================================================
TryEmitSettableFunction - detect SETTABLE of CLOSURE and emit inline
====================================================================== }
function TDecompiler.TryEmitSettableFunction(Node: PSSANode): Boolean;
var
ClosureNode: PSSANode;
SubProtoIdx: Integer;
SubProto: PProto;
TableExpr, KeyStr, FuncName, Params: AnsiString;
I: Integer;
IsColon: Boolean;
SubOutput, Line: AnsiString;
D: TDecompiler;
P, LineStart: Integer;
UVNames: TAnsiStringArray;
function FirstParamLooksLikeReceiver(AProto: PProto): Boolean;
var
PC, A, B, C: Integer;
Inst: TInstruction;
Sem: TSemanticOp;
begin
Result := False;
if (AProto = nil) or (AProto^.NumParams < 1) then Exit;
for PC := 0 to High(AProto^.Code) do begin
Inst := AProto^.Code[PC];
if FOpts.OT <> nil then begin
Sem := DecodeOp(FOpts.OT^, Inst);
A := DecodeA(FOpts.OT^, Inst);
B := DecodeB(FOpts.OT^, Inst);
C := DecodeC(FOpts.OT^, Inst);
if IsIvABCFormat(FOpts.OT^, Inst) then begin
B := DecodeVB(FOpts.OT^, Inst);
C := DecodeVC(FOpts.OT^, Inst);
end;
case Sem of
semGETTABLE, semGETI, semGETFIELD, semSELF:
if B = 0 then begin Result := True; Exit; end;
semSETTABLE, semSETI, semSETFIELD:
if A = 0 then begin Result := True; Exit; end;
end;
end else begin
A := GETARG_A(Inst);
B := GETARG_B(Inst);
C := GETARG_C(Inst);
case GET_OPCODE(Inst) of
OP_GETTABLE, OP_SELF:
if B = 0 then begin Result := True; Exit; end;
OP_SETTABLE:
if A = 0 then begin Result := True; Exit; end;
end;
end;
end;
end;
begin
Result := False;
{ OpC is the value being assigned; find the CLOSURE node for it }
ClosureNode := nil;
if (Node^.OpC.Reg >= 0) and (Node^.OpC.Reg <> SSA_CONST_REG) then begin
for I := 0 to High(FSF^.AllNodes) do
if RefEqual(FSF^.AllNodes[I]^.Dest, Node^.OpC) then begin
ClosureNode := FSF^.AllNodes[I]; Break;
end;
end;
if (ClosureNode = nil) or (ClosureNode^.Kind <> SSA_CLOSURE) then Exit;
SubProtoIdx := ClosureNode^.ConstIdx;
if (SubProtoIdx < 0) or (SubProtoIdx >= Length(FProto^.P)) then Exit;
SubProto := FProto^.P[SubProtoIdx];
{ If this sub-proto was already emitted elsewhere (e.g. as a local function),
don't inline it again - let normal SETTABLE emit the variable reference }
if (SubProtoIdx < Length(FInlinedProtos)) and FInlinedProtos[SubProtoIdx] then
Exit;
{ Mark as inlined }
if SubProtoIdx < Length(FInlinedProtos) then
FInlinedProtos[SubProtoIdx] := True;
{ Build table.key or table:method name }
{ When OpA is SSA_NO_REF but UpvalIdx is set, this is an upvalue table
write (SETTABUP with non-_ENV upvalue). Use the upvalue name. }
if (Node^.OpA.Reg < 0) and (Node^.UpvalIdx >= 0) then
TableExpr := UpvalName(Node^.UpvalIdx)
else
TableExpr := ExprOf(Node^.OpA, Node^.PC);
KeyStr := ExprOf(Node^.OpB, Node^.PC);
{ String key --> dot/colon notation. Only valid for constant string keys.
For non-string keys (variables, expressions), we cannot use
"function name()" syntax - must use "table[key] = function() ... end" }
if (Length(KeyStr) >= 2) and (KeyStr[1] = '"') then begin
{ _ENV table --> emit as plain global function (e.g. function print() instead of function _ENV.print()) }
if TableExpr = '_ENV' then
FuncName := Copy(KeyStr, 2, Length(KeyStr) - 2)
else
FuncName := TableExpr + '.' + Copy(KeyStr, 2, Length(KeyStr) - 2);
end else begin
{ Non-string key --> cannot use "function t[k]()" syntax, bail out }
Exit;
end;
{ Detect colon syntax: first LocVar is "self".
Stripped chunks have no LocVars, so recover the common method form when a
dotted table-field closure uses parameter register 0 as a receiver. }
IsColon := (SubProto^.NumParams >= 1) and
(Length(SubProto^.LocVars) > 0) and
(SubProto^.LocVars[0].Name = 'self');
if (not IsColon) and (SubProto^.NumParams >= 1) and
(Length(SubProto^.LocVars) = 0) and (Pos('.', FuncName) > 0) then
IsColon := FirstParamLooksLikeReceiver(SubProto);
if IsColon then begin
{ Replace the final dot with colon. For nested method fields,
"self.converters.name" should become "self.converters:name",
not "self:converters.name". }
I := Length(FuncName);
while (I > 0) and (FuncName[I] <> '.') do
Dec(I);
if I > 0 then
FuncName[I] := ':';
end;
{ Resolve upvalue names and build parameter list with collision avoidance }
UVNames := ResolveUpvalNames(ClosureNode^.PC, SubProtoIdx);
Params := BuildSubProtoParams(SubProto, UVNames, IsColon);
{ Decompile sub-proto body only (no function wrapper, indent 0) }
D := TDecompiler.Create(SubProto, FOpts, UVNames);
try
if IsColon and (Length(SubProto^.LocVars) = 0) and
(SubProto^.NumParams >= 1) then begin
if Length(D.FParamOverrides) < SubProto^.NumParams then
SetLength(D.FParamOverrides, SubProto^.NumParams);
D.FParamOverrides[0] := 'self';
end;
SubOutput := StripTrailingNewline(D.Run(rmBodyOnly));
finally
D.Free;
end;
{ Emit: function table:method(params) body end }
EmitStmt('function ' + FuncName + '(' + Params + ')');
Indent;
{ Emit body lines (rmBodyOnly output at indent 0, no stripping needed) }
P := 1;
while P <= Length(SubOutput) do begin
LineStart := P;
while (P <= Length(SubOutput)) and (SubOutput[P] <> #10) do
Inc(P);
Line := Copy(SubOutput, LineStart, P - LineStart);
if (Length(Line) > 0) and (Line[Length(Line)] = #13) then
Line := Copy(Line, 1, Length(Line) - 1);
Inc(P);
EmitEmbed(Line);
end;
Dedent;
EmitStruct('end');
Result := True;
end;