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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
//! Load precompiled Lua chunks.
//!
//! Direct port of `reference/lua-5.4.7/src/lundump.c` (335 lines, 20 items).
//! Declarations from `lundump.h` are merged here per PORTING.md §1.
//!
//! The public entry point is [`undump`], which reads a binary Lua chunk from
//! a [`ZIO`] stream and returns a Lua closure ready to call.
// TODO(port): resolve import paths once the crate module graph is settled
// in Phase B. These are best-guess paths based on other translated files.
use crateLuaState;
use crate*;
use crateZIO;
use LuaError;
use LuaValue;
// PORT NOTE: GcRef<T>, LuaProto, LuaClosure, LuaString, UpvalDesc, LocalVar,
// AbsLineInfo, and Instruction are expected to live in lua_types or lua_vm
// crates. All paths below are provisional for Phase A.
// TODO(port): confirm concrete module paths for all GC types in Phase B.
use ;
use ;
use UpVal;
use LuaString;
use GcRef;
use Instruction;
// ── Constants (from lundump.h) ─────────────────────────────────────────────
// C: #define LUAC_DATA "\x19\x93\r\n\x1a\n"
/// Six-byte data marker in the chunk header used to catch conversion errors.
const LUAC_DATA: & = b"\x19\x93\r\n\x1a\n";
// C: #define LUAC_INT 0x5678
/// Reference integer written in the header to detect integer endianness/size
/// mismatches.
const LUAC_INT: i64 = 0x5678;
// C: #define LUAC_NUM cast_num(370.5)
// macros.tsv: cast_num → x as f64
/// Reference float written in the header to detect float format mismatches.
const LUAC_NUM: f64 = 370.5;
// C: #define LUAC_VERSION (((LUA_VERSION_NUM / 100) * 16) + LUA_VERSION_NUM % 100)
// LUA_VERSION_NUM = 504 → ((5 * 16) + 4) = 0x54 = 84
/// One-byte version tag: upper nibble = major, lower nibble = minor.
const LUAC_VERSION: u8 = 0x54;
// C: #define LUAC_FORMAT 0 /* this is the official format */
const LUAC_FORMAT: u8 = 0;
// C: #define LUA_SIGNATURE "\x1bLua" (from lua.h, macros.tsv)
const LUA_SIGNATURE: & = b"\x1bLua";
// C: #define LUAI_MAXSHORTLEN (from llimits.h)
// macros.tsv: LUAI_MAXSHORTLEN → const MAX_SHORT_LEN: usize = 40
const MAX_SHORT_LEN: usize = 40;
// ── Constant-pool type tags (from lobject.h makevariant) ───────────────────
//
// These are the byte values written by ldump.c into the constants array.
// makevariant(t, v) = t | (v << 4).
//
// PORT NOTE: types.tsv maps LUA_VNIL → LuaValue::Nil etc. but the *byte
// values* used in the binary format are the raw tag integers from lobject.h.
// We define them here as u8 constants so the match in load_constants is
// self-documenting.
// C: LUA_VNIL = makevariant(LUA_TNIL, 0) = 0 | (0 << 4) = 0x00
const TAG_NIL: u8 = 0x00;
// C: LUA_VFALSE = makevariant(LUA_TBOOLEAN, 0) = 1 | (0 << 4) = 0x01
const TAG_FALSE: u8 = 0x01;
// C: LUA_VTRUE = makevariant(LUA_TBOOLEAN, 1) = 1 | (1 << 4) = 0x11
const TAG_TRUE: u8 = 0x11;
// C: LUA_VNUMINT = makevariant(LUA_TNUMBER, 0) = 3 | (0 << 4) = 0x03
const TAG_INT: u8 = 0x03;
// C: LUA_VNUMFLT = makevariant(LUA_TNUMBER, 1) = 3 | (1 << 4) = 0x13
const TAG_FLOAT: u8 = 0x13;
// C: LUA_VSHRSTR = makevariant(LUA_TSTRING, 0) = 4 | (0 << 4) = 0x04
const TAG_SHORT_STR: u8 = 0x04;
// C: LUA_VLNGSTR = makevariant(LUA_TSTRING, 1) = 4 | (1 << 4) = 0x14
const TAG_LONG_STR: u8 = 0x14;
// ── LoadState ──────────────────────────────────────────────────────────────
/// Loader state bundled for convenience: Lua state, input stream, and the
/// chunk name used in error messages.
///
/// # C mapping
/// ```c
/// // C: typedef struct { lua_State *L; ZIO *Z; const char *name; } LoadState;
/// ```
///
/// PORT NOTE: In C, `LoadState` holds raw pointers to `lua_State` and `ZIO`.
/// In Rust these become references with a shared lifetime `'a`. The struct is
/// always stack-allocated inside [`undump`] and never escapes the call.
// ── Error helper ───────────────────────────────────────────────────────────
/// Build a syntax error for a malformed binary chunk.
///
/// # C source
/// ```c
/// // C: static l_noret error(LoadState *S, const char *why) {
/// // luaO_pushfstring(S->L, "%s: bad binary format (%s)", S->name, why);
/// // luaD_throw(S->L, LUA_ERRSYNTAX);
/// // }
/// ```
///
/// PORT NOTE: `l_noret` in C (diverges via `longjmp`). In Rust we return
/// `LuaError` and the caller does `return Err(load_error(...))`. The C
/// pattern `luaO_pushfstring + luaD_throw(LUA_ERRSYNTAX)` collapses to a
/// single `LuaError::syntax` per error_sites.tsv.
///
/// TODO(port): `s.name` is `Vec<u8>`; `LuaError::syntax` takes `format_args!`
/// which requires an `std::fmt::Display` implementor. `Vec<u8>` does not
/// implement `Display`. Phase B should add a byte-string formatting path to
/// `LuaError::syntax_bytes` or similar, so the chunk name is included verbatim
/// in the message.
// ── Low-level I/O ──────────────────────────────────────────────────────────
/// Read exactly `buf.len()` bytes from the stream into `buf`.
///
/// # C source
/// ```c
/// // C: static void loadBlock(LoadState *S, void *b, size_t size) {
/// // if (luaZ_read(S->Z, b, size) != 0)
/// // error(S, "truncated chunk");
/// // }
/// ```
///
/// PORT NOTE: C takes `void *b` + explicit `size`. In Rust we use `&mut [u8]`
/// whose length encodes the byte count. `luaZ_read` returns the number of
/// bytes NOT read (0 = success), matching `ZIO::read`'s contract.
/// Read a single byte from the stream.
///
/// # C source
/// ```c
/// // C: static lu_byte loadByte(LoadState *S) {
/// // int b = zgetc(S->Z);
/// // if (b == EOZ)
/// // error(S, "truncated chunk");
/// // return cast_byte(b);
/// // }
/// ```
///
/// PORT NOTE: `cast_byte` → `as u8` per macros.tsv; `zgetc` → `z.getc()`.
/// Read a variable-length unsigned integer (7 bits per byte, big-endian,
/// MSB-first continuation flag).
///
/// # C source
/// ```c
/// // C: static size_t loadUnsigned(LoadState *S, size_t limit) {
/// // size_t x = 0;
/// // int b;
/// // limit >>= 7;
/// // do {
/// // b = loadByte(S);
/// // if (x >= limit)
/// // error(S, "integer overflow");
/// // x = (x << 7) | (b & 0x7f);
/// // } while ((b & 0x80) == 0);
/// // return x;
/// // }
/// ```
///
/// PORT NOTE: The encoding terminates when a byte with the high bit set is
/// seen (the *last* byte has bit 7 = 1). That is the opposite of the more
/// common LEB128 where the continuation bit means "more follows".
/// Read a `size_t`-sized unsigned value.
///
/// # C source
/// ```c
/// // C: static size_t loadSize(LoadState *S) {
/// // return loadUnsigned(S, MAX_SIZET);
/// // }
/// ```
///
/// PORT NOTE: `MAX_SIZET` → `usize::MAX` per macros.tsv.
/// Read a signed `int`-sized value.
///
/// # C source
/// ```c
/// // C: static int loadInt(LoadState *S) {
/// // return cast_int(loadUnsigned(S, INT_MAX));
/// // }
/// ```
///
/// PORT NOTE: `cast_int` → `x as i32` per macros.tsv. `INT_MAX` → `i32::MAX
/// as usize`.
/// Read a `lua_Number` (f64) as eight raw native-endian bytes.
///
/// # C source
/// ```c
/// // C: static lua_Number loadNumber(LoadState *S) {
/// // lua_Number x;
/// // loadVar(S, x); /* expands to loadBlock(S, &x, sizeof(x)) */
/// // return x;
/// // }
/// ```
///
/// PORT NOTE: `loadVar` reads `sizeof(lua_Number) = 8` raw bytes directly
/// into the value. In Rust we use `f64::from_ne_bytes` (native endian) to
/// reconstruct the value from the eight bytes. The binary format is host-
/// endian for these fields; the header check verifies endianness compatibility
/// via `LUAC_INT` and `LUAC_NUM` sentinels.
/// Read a `lua_Integer` (i64) as eight raw native-endian bytes.
///
/// # C source
/// ```c
/// // C: static lua_Integer loadInteger(LoadState *S) {
/// // lua_Integer x;
/// // loadVar(S, x); /* expands to loadBlock(S, &x, sizeof(x)) */
/// // return x;
/// // }
/// ```
///
/// PORT NOTE: Same reasoning as [`load_number`] — uses `i64::from_ne_bytes`.
// ── String loading ─────────────────────────────────────────────────────────
/// Load a nullable string. Returns `None` if the stored size is zero.
///
/// # C source
/// ```c
/// // C: static TString *loadStringN(LoadState *S, Proto *p) {
/// // lua_State *L = S->L;
/// // TString *ts;
/// // size_t size = loadSize(S);
/// // if (size == 0) return NULL;
/// // else if (--size <= LUAI_MAXSHORTLEN) { /* short string? */
/// // char buff[LUAI_MAXSHORTLEN];
/// // loadVector(S, buff, size);
/// // ts = luaS_newlstr(L, buff, size);
/// // } else { /* long string */
/// // ts = luaS_createlngstrobj(L, size);
/// // setsvalue2s(L, L->top.p, ts); /* anchor it (loadVector can GC) */
/// // luaD_inctop(L);
/// // loadVector(S, getlngstr(ts), size);
/// // L->top.p--;
/// // }
/// // luaC_objbarrier(L, p, ts);
/// // return ts;
/// // }
/// ```
///
/// PORT NOTE: The Lua binary format stores `actual_length + 1` so that size=0
/// is the null-string sentinel. After reading `raw_size`, the actual byte
/// count is `raw_size - 1`.
///
/// PORT NOTE: In C, long strings are created first (to anchor them from GC)
/// and then filled in-place via `getlngstr`. In Rust, GC anchoring is not
/// needed in Phase A–C (Rc keeps objects alive); we read into a buffer and
/// then create the string.
///
/// TODO(port): `luaS_newlstr` interns the string (short strings only);
/// `luaS_createlngstrobj` does NOT intern. Phase A uses `state.intern_str()`
/// for both. Phase B should add a `state.create_long_str()` path that skips
/// the intern table, matching C semantics.
///
/// PORT NOTE: The `_proto` parameter corresponds to C's `Proto *p` used only
/// for `luaC_objbarrier(L, p, ts)`. The barrier is a no-op in Phase A–C
/// (macros.tsv: `luaC_objbarrier → state.gc().obj_barrier(p, o)` no-op).
/// Load a non-nullable string; error if the stream encodes a null string.
///
/// # C source
/// ```c
/// // C: static TString *loadString(LoadState *S, Proto *p) {
/// // TString *st = loadStringN(S, p);
/// // if (st == NULL)
/// // error(S, "bad format for constant string");
/// // return st;
/// // }
/// ```
// ── Proto-field loaders ────────────────────────────────────────────────────
/// Load the bytecode instruction array into a prototype.
///
/// # C source
/// ```c
/// // C: static void loadCode(LoadState *S, Proto *f) {
/// // int n = loadInt(S);
/// // f->code = luaM_newvectorchecked(S->L, n, Instruction);
/// // f->sizecode = n;
/// // loadVector(S, f->code, n);
/// // }
/// ```
///
/// PORT NOTE: `loadVector(S, f->code, n)` expands to
/// `loadBlock(S, f->code, n * sizeof(Instruction))` — `n` raw 4-byte words.
/// We read each `u32` in native-endian order, consistent with how
/// [`load_number`] and [`load_integer`] work.
///
/// PORT NOTE: `f->sizecode` is removed in Rust — `Vec::len()` covers it
/// (types.tsv: `Proto.sizecode → removed`).
/// Load the constant pool into a prototype.
///
/// # C source
/// ```c
/// // C: static void loadConstants(LoadState *S, Proto *f) {
/// // int i; int n = loadInt(S);
/// // f->k = luaM_newvectorchecked(S->L, n, TValue);
/// // f->sizek = n;
/// // for (i = 0; i < n; i++) setnilvalue(&f->k[i]);
/// // for (i = 0; i < n; i++) {
/// // TValue *o = &f->k[i];
/// // int t = loadByte(S);
/// // switch (t) {
/// // case LUA_VNIL: setnilvalue(o); break;
/// // case LUA_VFALSE: setbfvalue(o); break;
/// // case LUA_VTRUE: setbtvalue(o); break;
/// // case LUA_VNUMFLT: setfltvalue(o, loadNumber(S)); break;
/// // case LUA_VNUMINT: setivalue(o, loadInteger(S)); break;
/// // case LUA_VSHRSTR:
/// // case LUA_VLNGSTR: setsvalue2n(S->L, o, loadString(S, f)); break;
/// // default: lua_assert(0);
/// // }
/// // }
/// // }
/// ```
///
/// PORT NOTE: The initial `setnilvalue` loop initialises the vector for GC
/// safety in C. In Rust, `Vec` is always in a valid state; we skip it.
/// Load nested function prototypes into a prototype.
///
/// # C source
/// ```c
/// // C: static void loadProtos(LoadState *S, Proto *f) {
/// // int i; int n = loadInt(S);
/// // f->p = luaM_newvectorchecked(S->L, n, Proto *);
/// // f->sizep = n;
/// // for (i = 0; i < n; i++) f->p[i] = NULL;
/// // for (i = 0; i < n; i++) {
/// // f->p[i] = luaF_newproto(S->L);
/// // luaC_objbarrier(S->L, f, f->p[i]);
/// // loadFunction(S, f->p[i], f->source);
/// // }
/// // }
/// ```
///
/// PORT NOTE: C creates the proto first (for GC anchor) then fills it. In
/// Rust we create a default `LuaProto`, fill it, then wrap in `GcRef`.
/// `f->sizep` is removed per types.tsv (`Proto.sizep → removed`).
/// Load upvalue descriptors into a prototype.
///
/// # C source
/// ```c
/// // C: static void loadUpvalues(LoadState *S, Proto *f) {
/// // int i, n;
/// // n = loadInt(S);
/// // f->upvalues = luaM_newvectorchecked(S->L, n, Upvaldesc);
/// // f->sizeupvalues = n;
/// // for (i = 0; i < n; i++)
/// // f->upvalues[i].name = NULL; /* make array valid for GC */
/// // for (i = 0; i < n; i++) {
/// // f->upvalues[i].instack = loadByte(S);
/// // f->upvalues[i].idx = loadByte(S);
/// // f->upvalues[i].kind = loadByte(S);
/// // }
/// // }
/// ```
///
/// PORT NOTE: The C comment says names must be filled first for GC safety.
/// In Rust we build `UpvalDesc` values with `name: None` and fill names later
/// in [`load_debug`]. This requires `UpvalDesc.name` to be
/// `Option<GcRef<LuaString>>` rather than `GcRef<LuaString>` as listed in
/// types.tsv. Phase B should reconcile the types.tsv entry.
///
/// PORT NOTE: `f->sizeupvalues` is removed per types.tsv.
/// Load debug information into a prototype.
///
/// # C source
/// ```c
/// // C: static void loadDebug(LoadState *S, Proto *f) {
/// // int i, n;
/// // n = loadInt(S);
/// // f->lineinfo = luaM_newvectorchecked(S->L, n, ls_byte);
/// // f->sizelineinfo = n;
/// // loadVector(S, f->lineinfo, n);
/// // n = loadInt(S);
/// // f->abslineinfo = luaM_newvectorchecked(S->L, n, AbsLineInfo);
/// // f->sizeabslineinfo = n;
/// // for (i = 0; i < n; i++) {
/// // f->abslineinfo[i].pc = loadInt(S);
/// // f->abslineinfo[i].line = loadInt(S);
/// // }
/// // n = loadInt(S);
/// // f->locvars = luaM_newvectorchecked(S->L, n, LocVar);
/// // f->sizelocvars = n;
/// // for (i = 0; i < n; i++) f->locvars[i].varname = NULL;
/// // for (i = 0; i < n; i++) {
/// // f->locvars[i].varname = loadStringN(S, f);
/// // f->locvars[i].startpc = loadInt(S);
/// // f->locvars[i].endpc = loadInt(S);
/// // }
/// // n = loadInt(S);
/// // if (n != 0) /* does it have debug information? */
/// // n = f->sizeupvalues; /* must be this many */
/// // for (i = 0; i < n; i++)
/// // f->upvalues[i].name = loadStringN(S, f);
/// // }
/// ```
///
/// PORT NOTE: `ls_byte` (signed byte) maps to `i8` per types.tsv.
/// `loadVector(S, f->lineinfo, n)` reads `n * sizeof(ls_byte) = n` bytes.
/// We read them as `u8` then reinterpret as `i8` via cast.
///
/// PORT NOTE: Size companion fields (`sizelineinfo`, `sizeabslineinfo`,
/// `sizelocvars`) are all removed per types.tsv — `Vec::len()` covers them.
///
/// PORT NOTE: `LocalVar.varname` and `UpvalDesc.name` are both
/// `Option<GcRef<LuaString>>` here because `loadStringN` can return `None`.
/// See also the note on [`load_upvalues`].
// ── Function loader ────────────────────────────────────────────────────────
/// Load a complete function prototype from the stream.
///
/// # C source
/// ```c
/// // C: static void loadFunction(LoadState *S, Proto *f, TString *psource) {
/// // f->source = loadStringN(S, f);
/// // if (f->source == NULL) f->source = psource;
/// // f->linedefined = loadInt(S);
/// // f->lastlinedefined = loadInt(S);
/// // f->numparams = loadByte(S);
/// // f->is_vararg = loadByte(S);
/// // f->maxstacksize = loadByte(S);
/// // loadCode(S, f);
/// // loadConstants(S, f);
/// // loadUpvalues(S, f);
/// // loadProtos(S, f);
/// // loadDebug(S, f);
/// // }
/// ```
///
/// PORT NOTE: `TString *psource` becomes `Option<GcRef<LuaString>>` because
/// the top-level call passes `NULL` (mapped to `None`). `f->source` in `LuaProto`
/// is typed `GcRef<LuaString>` in types.tsv, but the undump path needs
/// `Option<GcRef<LuaString>>` to express "inherited from parent". Phase B
/// should align types.tsv or add a dedicated `Option` wrapper there.
///
/// PORT NOTE: `f->is_vararg` is stored as `lu_byte` in C but `bool` in
/// types.tsv. We read the raw byte and convert to `bool` via `!= 0`.
// ── Header validation ──────────────────────────────────────────────────────
/// Verify that the next `expected.len()` bytes in the stream match `expected`.
///
/// # C source
/// ```c
/// // C: static void checkliteral(LoadState *S, const char *s, const char *msg) {
/// // char buff[sizeof(LUA_SIGNATURE) + sizeof(LUAC_DATA)];
/// // size_t len = strlen(s);
/// // loadVector(S, buff, len);
/// // if (memcmp(s, buff, len) != 0)
/// // error(S, msg);
/// // }
/// ```
///
/// PORT NOTE: `strlen` on a `const char *` becomes `.len()` on a `&[u8]`.
/// `memcmp` becomes slice equality.
/// Verify that the next byte in the stream equals `expected_size`.
///
/// # C source
/// ```c
/// // C: static void fchecksize(LoadState *S, size_t size, const char *tname) {
/// // if (loadByte(S) != size)
/// // error(S, luaO_pushfstring(S->L, "%s size mismatch", tname));
/// // }
/// ```
///
/// PORT NOTE: `luaO_pushfstring` is used here as a message formatter, not as
/// a throw site. We inline the message directly. `tname` is always a Rust
/// type-name string literal (ASCII) from the call sites; using `&'static str`
/// is appropriate here (not Lua data).
/// Validate the binary chunk header.
///
/// # C source
/// ```c
/// // C: static void checkHeader(LoadState *S) {
/// // checkliteral(S, &LUA_SIGNATURE[1], "not a binary chunk");
/// // if (loadByte(S) != LUAC_VERSION) error(S, "version mismatch");
/// // if (loadByte(S) != LUAC_FORMAT) error(S, "format mismatch");
/// // checkliteral(S, LUAC_DATA, "corrupted chunk");
/// // checksize(S, Instruction);
/// // checksize(S, lua_Integer);
/// // checksize(S, lua_Number);
/// // if (loadInteger(S) != LUAC_INT) error(S, "integer format mismatch");
/// // if (loadNumber(S) != LUAC_NUM) error(S, "float format mismatch");
/// // }
/// ```
///
/// PORT NOTE: `checksize(S, T)` expands to `fchecksize(S, sizeof(T), #T)`.
/// We emit the three concrete sizes inline.
/// - `sizeof(Instruction)` = 4 (u32)
/// - `sizeof(lua_Integer)` = 8 (i64)
/// - `sizeof(lua_Number)` = 8 (f64)
///
/// PORT NOTE: The first byte of `LUA_SIGNATURE` (`\x1b`) is already consumed
/// by the caller before `checkHeader` is invoked, so we check only bytes 1..
/// of the signature (`"Lua"`).
// ── Public entry point ─────────────────────────────────────────────────────
/// Load a precompiled Lua chunk and return the top-level Lua closure.
///
/// This is the Rust equivalent of `luaU_undump` — the single public function
/// exported by `lundump.c`.
///
/// # C source
/// ```c
/// // C: LClosure *luaU_undump(lua_State *L, ZIO *Z, const char *name) {
/// // LoadState S;
/// // LClosure *cl;
/// // if (*name == '@' || *name == '=')
/// // S.name = name + 1;
/// // else if (*name == LUA_SIGNATURE[0])
/// // S.name = "binary string";
/// // else
/// // S.name = name;
/// // S.L = L; S.Z = Z;
/// // checkHeader(&S);
/// // cl = luaF_newLclosure(L, loadByte(&S));
/// // setclLvalue2s(L, L->top.p, cl);
/// // luaD_inctop(L);
/// // cl->p = luaF_newproto(L);
/// // luaC_objbarrier(L, cl, cl->p);
/// // loadFunction(&S, cl->p, NULL);
/// // lua_assert(cl->nupvalues == cl->p->sizeupvalues);
/// // luai_verifycode(L, cl->p);
/// // return cl;
/// // }
/// ```
///
/// # Parameters
/// - `state` — the Lua thread state.
/// - `z` — input stream positioned at the start of the binary chunk
/// (the first byte `\x1b` of `LUA_SIGNATURE` must still be present).
/// - `name` — chunk name for error messages. Stripped per Lua convention:
/// - `@…` → filename (strip `@`)
/// - `=…` → literal name (strip `=`)
/// - starts with `\x1b` → `"binary string"`
/// - otherwise used as-is.
///
/// PORT NOTE: The C function returns `LClosure *`. In Rust we return
/// `GcRef<LuaLClosure>` (the Lua-closure variant of `LuaClosure`). The
/// closure is also pushed onto the stack for GC anchoring, matching the C
/// behaviour (`setclLvalue2s + luaD_inctop`). The caller is responsible for
/// popping it when done (consistent with C).
///
/// PORT NOTE: `luai_verifycode` is a no-op in the default build
/// (`#define luai_verifycode(L,f) /* empty */`); dropped here.
///
/// PORT NOTE: `cl->nupvalues == cl->p->sizeupvalues` — in Rust the nupvalues
/// count is implicit in `cl.upvals.len()` and `f.upvalues.len()`; the
/// assertion becomes `debug_assert_eq!`.
pub
// ──────────────────────────────────────────────────────────────────────────
// PORT STATUS
// source: src/lundump.c (335 lines, 20 functions/items)
// src/lundump.h (35 lines, merged)
// target_crate: lua-vm
// confidence: medium
// todos: 15
// port_notes: 39
// unsafe_blocks: 0 (must be 0 outside explicit unsafe-budget crates)
// notes: Logic is faithful to the C. The main open items for Phase B
// are: (1) import paths for GcRef/LuaProto/LuaClosure/etc.;
// (2) LuaError::syntax byte-string formatting for the chunk
// name in load_error; (3) long-string vs short-string intern
// distinction in load_string_n; (4) the stack placeholder in
// undump must be replaced with the real GcRef<LuaLClosure>
// value once LuaValue conversion is defined; (5) UpvalDesc.name
// and LocalVar.varname need Option<GcRef<LuaString>> in the
// proto type to match the two-pass load order here.
// ──────────────────────────────────────────────────────────────────────────