-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlobject.h
More file actions
2021 lines (1611 loc) · 71.3 KB
/
lobject.h
File metadata and controls
2021 lines (1611 loc) · 71.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
/*
** $Id: lobject.h $
** Type definitions for Lua objects
** See Copyright Notice in lua.h
*/
#ifndef lobject_h
#define lobject_h
#include <cstdarg>
#include <span>
#include "llimits.h"
#include "lua.h"
#include "ltvalue.h" /* TValue class */
/* Forward declarations */
enum class GCAge : lu_byte;
/*
** Extra types for collectable non-values
*/
inline constexpr int LUA_TUPVAL = LUA_NUMTYPES; /* upvalues */
inline constexpr int LUA_TPROTO = (LUA_NUMTYPES+1); /* function prototypes */
inline constexpr int LUA_TDEADKEY = (LUA_NUMTYPES+2); /* removed keys in tables */
/*
** number of all possible types (including LUA_TNONE but excluding DEADKEY)
*/
inline constexpr int LUA_TOTALTYPES = (LUA_TPROTO + 2);
/*
** setobj() moved to after type check functions are defined.
** See below after Collectable Types section.
*/
/*
** Entries in a Lua stack. Field 'tbclist' forms a list of all
** to-be-closed variables active in this stack. Dummy entries are
** used when the distance between two tbc variables does not fit
** in an unsigned short. They are represented by delta==0, and
** their real delta is always the maximum value that fits in
** that field.
*/
typedef union StackValue {
TValue val;
struct {
Value value_;
lu_byte tt_;
unsigned short delta;
} tbclist;
} StackValue;
/* index to stack elements */
typedef StackValue *StkId;
/*
** When reallocating the stack, change all pointers to the stack into
** proper offsets.
*/
typedef union {
StkId p; /* actual pointer */
ptrdiff_t offset; /* used while the stack is being reallocated */
} StkIdRel;
/* convert a 'StackValue' to a 'TValue' */
constexpr TValue* s2v(StackValue* o) noexcept { return &(o)->val; }
constexpr const TValue* s2v(const StackValue* o) noexcept { return &(o)->val; }
/*
** {==================================================================
** Nil
** ===================================================================
*/
/* Standard nil */
inline constexpr int LUA_VNIL = makevariant(LUA_TNIL, 0);
/* Empty slot (which might be different from a slot containing nil) */
inline constexpr int LUA_VEMPTY = makevariant(LUA_TNIL, 1);
/* Value returned for a key not found in a table (absent key) */
inline constexpr int LUA_VABSTKEY = makevariant(LUA_TNIL, 2);
/* Special variant to signal that a fast get is accessing a non-table */
inline constexpr int LUA_VNOTABLE = makevariant(LUA_TNIL, 3);
/* macro to test for (any kind of) nil */
constexpr bool ttisnil(const TValue* v) noexcept { return checktype(v, LUA_TNIL); }
constexpr bool TValue::isNil() const noexcept { return checktype(this, LUA_TNIL); }
/*
** Macro to test the result of a table access. Formally, it should
** distinguish between LUA_VEMPTY/LUA_VABSTKEY/LUA_VNOTABLE and
** other tags. As currently nil is equivalent to LUA_VEMPTY, it is
** simpler to just test whether the value is nil.
*/
constexpr bool tagisempty(int tag) noexcept { return novariant(tag) == LUA_TNIL; }
/* macro to test for a standard nil */
constexpr bool ttisstrictnil(const TValue* o) noexcept { return checktag(o, LUA_VNIL); }
constexpr bool TValue::isStrictNil() const noexcept { return checktag(this, LUA_VNIL); }
inline void setnilvalue(TValue* obj) noexcept { obj->setNil(); }
constexpr bool isabstkey(const TValue* v) noexcept { return checktag(v, LUA_VABSTKEY); }
constexpr bool TValue::isAbstKey() const noexcept { return checktag(this, LUA_VABSTKEY); }
/*
** function to detect non-standard nils (used only in assertions)
*/
constexpr bool isnonstrictnil(const TValue* v) noexcept {
return ttisnil(v) && !ttisstrictnil(v);
}
constexpr bool TValue::isNonStrictNil() const noexcept {
return isNil() && !isStrictNil();
}
/*
** By default, entries with any kind of nil are considered empty.
** (In any definition, values associated with absent keys must also
** be accepted as empty.)
*/
constexpr bool isempty(const TValue* v) noexcept { return ttisnil(v); }
constexpr bool TValue::isEmpty() const noexcept { return isNil(); }
/* macro defining a value corresponding to an absent key */
#define ABSTKEYCONSTANT {nullptr}, LUA_VABSTKEY
/* mark an entry as empty */
inline void setempty(TValue* v) noexcept { settt_(v, LUA_VEMPTY); }
/* }================================================================== */
/*
** {==================================================================
** Booleans
** ===================================================================
*/
inline constexpr int LUA_VFALSE = makevariant(LUA_TBOOLEAN, 0);
inline constexpr int LUA_VTRUE = makevariant(LUA_TBOOLEAN, 1);
constexpr bool ttisboolean(const TValue* o) noexcept { return checktype(o, LUA_TBOOLEAN); }
constexpr bool ttisfalse(const TValue* o) noexcept { return checktag(o, LUA_VFALSE); }
constexpr bool ttistrue(const TValue* o) noexcept { return checktag(o, LUA_VTRUE); }
constexpr bool TValue::isBoolean() const noexcept { return checktype(this, LUA_TBOOLEAN); }
constexpr bool TValue::isFalse() const noexcept { return checktag(this, LUA_VFALSE); }
constexpr bool TValue::isTrue() const noexcept { return checktag(this, LUA_VTRUE); }
constexpr bool l_isfalse(const TValue* o) noexcept { return ttisfalse(o) || ttisnil(o); }
constexpr bool tagisfalse(int t) noexcept { return (t == LUA_VFALSE || novariant(t) == LUA_TNIL); }
constexpr bool TValue::isFalseLike() const noexcept { return isFalse() || isNil(); }
inline void setbfvalue(TValue* obj) noexcept { obj->setFalse(); }
inline void setbtvalue(TValue* obj) noexcept { obj->setTrue(); }
/* }================================================================== */
/*
** {==================================================================
** Threads
** ===================================================================
*/
inline constexpr int LUA_VTHREAD = makevariant(LUA_TTHREAD, 0);
constexpr bool ttisthread(const TValue* o) noexcept { return checktag(o, ctb(LUA_VTHREAD)); }
constexpr bool TValue::isThread() const noexcept { return checktag(this, ctb(LUA_VTHREAD)); }
inline lua_State* thvalue(const TValue* o) noexcept { return o->threadValue(); }
/* setthvalue now defined as inline function below */
/* }================================================================== */
/*
** {==================================================================
** Collectable Objects
** ===================================================================
*/
/*
** CommonHeader macro deprecated - GC objects now inherit from GCBase
*/
/* Common type for all collectable objects */
class GCObject {
protected:
mutable GCObject* next; /* GC list linkage (mutable for GC bookkeeping) */
lu_byte tt; /* Type tag (immutable) */
mutable lu_byte marked; /* GC mark bits (mutable for GC bookkeeping) */
public:
// Inline accessors
GCObject* getNext() const noexcept { return next; }
void setNext(GCObject* n) const noexcept { next = n; } /* const - next is mutable */
// Pointer-to-pointer for efficient GC list manipulation (allows in-place removal)
GCObject** getNextPtr() const noexcept { return &next; } /* const - next is mutable */
lu_byte getType() const noexcept { return tt; }
void setType(lu_byte t) noexcept { tt = t; }
lu_byte getMarked() const noexcept { return marked; }
void setMarked(lu_byte m) const noexcept { marked = m; } /* const - marked is mutable */
bool isMarked() const noexcept { return marked != 0; }
// Marked field bit manipulation methods (const - marked is mutable)
void setMarkedBit(int bit) const noexcept { marked |= cast_byte(1 << bit); }
void clearMarkedBit(int bit) const noexcept { marked &= cast_byte(~(1 << bit)); }
void clearMarkedBits(int mask) const noexcept { marked &= cast_byte(~mask); }
// Marked field bit manipulation helpers (for backward compatibility)
lu_byte& getMarkedRef() const noexcept { return marked; } /* const - marked is mutable */
// GC color and age methods (defined in lgc.h after constants are available)
inline bool isWhite() const noexcept;
inline bool isBlack() const noexcept;
inline bool isGray() const noexcept;
inline GCAge getAge() const noexcept;
inline void setAge(GCAge age) const noexcept; /* const - marked is mutable */
inline bool isOld() const noexcept;
// GC operations (implemented in lgc.cpp)
void fix(lua_State* L) const; /* const - only modifies mutable GC fields */
void checkFinalizer(lua_State* L, Table* mt);
};
/*
** CRTP (Curiously Recurring Template Pattern) Base class for all GC-managed objects
**
** DESIGN PATTERN:
** CRTP is a C++ idiom where a class X derives from a template base class using X itself
** as a template parameter: class X : public Base<X>
**
** Benefits compared to traditional polymorphism (virtual functions):
** 1. Zero runtime overhead - no vtable pointer, no virtual function indirection
** 2. Compile-time polymorphism - compiler can inline all method calls
** 3. Type safety - each derived class gets its own type-specific methods
** 4. Same memory layout as plain C struct - maintains C API compatibility
**
** Usage in Lua's GC system:
** - Table : public GCBase<Table>
** - TString : public GCBase<TString>
** - Proto : public GCBase<Proto>
** - LClosure : public GCBase<LClosure>
** - CClosure : public GCBase<CClosure>
** - UpVal : public GCBase<UpVal>
** - Udata : public GCBase<Udata>
** - lua_State : public GCBase<lua_State> (thread object)
**
** CRITICAL INVARIANT:
** Memory layout MUST match GCObject exactly:
** GCObject *next; lu_byte tt; lu_byte marked
**
** This allows safe casting between GCObject* and Derived* without pointer adjustment.
** The static_assert in each derived class verifies this invariant at compile time.
**
** PERFORMANCE:
** This design eliminated the vtable overhead from the original Lua C implementation
** while gaining C++ type safety and encapsulation. All color-checking methods
** (isWhite, isBlack, isGray) compile to simple bit tests with no function call overhead.
**
** See claude.md for detailed discussion of this architectural decision.
*/
template<typename Derived>
class GCBase: public GCObject {
public:
// Accessor methods (preferred over direct field access)
constexpr GCObject* getNext() const noexcept { return next; }
constexpr void setNext(GCObject* n) const noexcept { next = n; } /* const - next is mutable */
constexpr lu_byte getType() const noexcept { return tt; }
constexpr void setType(lu_byte t) noexcept { tt = t; }
constexpr lu_byte getMarked() const noexcept { return marked; }
constexpr void setMarked(lu_byte m) const noexcept { marked = m; } /* const - marked is mutable */
constexpr bool isMarked() const noexcept { return marked != 0; }
// GC color and age methods (defined in lgc.h after constants)
inline void setAge(GCAge age) const noexcept; /* const - marked is mutable */
inline bool isOld() const noexcept;
// Cast to GCObject* for compatibility
GCObject* toGCObject() noexcept {
return reinterpret_cast<GCObject*>(static_cast<Derived*>(this));
}
const GCObject* toGCObject() const noexcept {
return reinterpret_cast<const GCObject*>(static_cast<const Derived*>(this));
}
};
constexpr bool iscollectable(const TValue* o) noexcept { return (rawtt(o) & BIT_ISCOLLECTABLE) != 0; }
constexpr bool TValue::isCollectable() const noexcept { return (tt_ & BIT_ISCOLLECTABLE) != 0; }
inline GCObject* gcvalue(const TValue* o) noexcept { return o->gcValue(); }
constexpr GCObject* gcvalueraw(const Value& v) noexcept { return v.gc; }
/* setgcovalue now defined as inline function below */
/* collectable object has the same tag as the original value (inline version) */
inline bool righttt(const TValue* obj) noexcept { return ttypetag(obj) == gcvalue(obj)->getType(); }
inline bool TValue::hasRightType() const noexcept { return typeTag() == gcValue()->getType(); }
/* }================================================================== */
/*
** {==================================================================
** TValue assignment functions
** ===================================================================
*/
/*
** TValue assignment now uses the operator= defined in lgc.h.
** Stack assignments use LuaStack::setSlot() and copySlot().
*/
/* }================================================================== */
/*
** {==================================================================
** Numbers
** ===================================================================
*/
/* Variant tags for numbers */
inline constexpr int LUA_VNUMINT = makevariant(LUA_TNUMBER, 0); /* integer numbers */
inline constexpr int LUA_VNUMFLT = makevariant(LUA_TNUMBER, 1); /* float numbers */
constexpr bool ttisnumber(const TValue* o) noexcept { return checktype(o, LUA_TNUMBER); }
constexpr bool ttisfloat(const TValue* o) noexcept { return checktag(o, LUA_VNUMFLT); }
constexpr bool ttisinteger(const TValue* o) noexcept { return checktag(o, LUA_VNUMINT); }
constexpr bool TValue::isNumber() const noexcept { return checktype(this, LUA_TNUMBER); }
constexpr bool TValue::isFloat() const noexcept { return checktag(this, LUA_VNUMFLT); }
constexpr bool TValue::isInteger() const noexcept { return checktag(this, LUA_VNUMINT); }
// TValue::numberValue() implementation (needs LUA_VNUMINT constant)
inline lua_Number TValue::numberValue() const noexcept {
return (tt_ == LUA_VNUMINT) ? static_cast<lua_Number>(value_.i) : value_.n;
}
inline lua_Number nvalue(const TValue* o) noexcept { return o->numberValue(); }
inline lua_Number fltvalue(const TValue* o) noexcept { return o->floatValue(); }
inline lua_Integer ivalue(const TValue* o) noexcept { return o->intValue(); }
constexpr lua_Number fltvalueraw(const Value& v) noexcept { return v.n; }
constexpr lua_Integer ivalueraw(const Value& v) noexcept { return v.i; }
inline void setfltvalue(TValue* obj, lua_Number x) noexcept { obj->setFloat(x); }
inline void chgfltvalue(TValue* obj, lua_Number x) noexcept { obj->changeFloat(x); }
inline void setivalue(TValue* obj, lua_Integer x) noexcept { obj->setInt(x); }
inline void chgivalue(TValue* obj, lua_Integer x) noexcept { obj->changeInt(x); }
/* }================================================================== */
/*
** {==================================================================
** Strings
** ===================================================================
*/
/* Variant tags for strings */
inline constexpr int LUA_VSHRSTR = makevariant(LUA_TSTRING, 0); /* short strings */
inline constexpr int LUA_VLNGSTR = makevariant(LUA_TSTRING, 1); /* long strings */
constexpr bool ttisstring(const TValue* o) noexcept { return checktype(o, LUA_TSTRING); }
constexpr bool ttisshrstring(const TValue* o) noexcept { return checktag(o, ctb(LUA_VSHRSTR)); }
constexpr bool ttislngstring(const TValue* o) noexcept { return checktag(o, ctb(LUA_VLNGSTR)); }
constexpr bool TValue::isString() const noexcept { return checktype(this, LUA_TSTRING); }
constexpr bool TValue::isShortString() const noexcept { return checktag(this, ctb(LUA_VSHRSTR)); }
constexpr bool TValue::isLongString() const noexcept { return checktag(this, ctb(LUA_VLNGSTR)); }
inline TString* tsvalue(const TValue* o) noexcept { return o->stringValue(); }
/* Kinds of long strings (stored in 'shrlen') */
inline constexpr int LSTRREG = -1; /* regular long string */
inline constexpr int LSTRFIX = -2; /* fixed external long string */
inline constexpr int LSTRMEM = -3; /* external long string with deallocation */
/*
** Header for a string value.
*/
// TString inherits from GCBase (CRTP)
class TString : public GCBase<TString> {
private:
lu_byte extra; /* reserved words for short strings; "has hash" for longs */
ls_byte shrlen; /* length for short strings, negative for long strings */
unsigned int hash;
union {
size_t lnglen; /* length for long strings */
TString *hnext; /* linked list for hash table */
} u;
char *contents; /* pointer to content in long strings */
lua_Alloc falloc; /* deallocation function for external strings */
void *ud; /* user data for external strings */
public:
// Phase 50: Constructor - initializes only fields common to both short and long strings
// For short strings: only fields up to 'u' exist (contents/falloc/ud are overlay for string data)
// For long strings: all fields exist
TString() noexcept {
extra = 0;
shrlen = 0;
hash = 0;
u.lnglen = 0; // Zero-initialize union
// Note: contents, falloc, ud are NOT initialized here!
// They will be initialized by the caller only for long strings.
}
// Phase 50: Destructor - trivial (GC handles deallocation)
// MUST be empty (not = default) because for short strings, not all fields exist in memory!
~TString() noexcept {}
// Phase 50: Special placement new for variable-size objects
// This is used when we need exact size control (for short strings)
static void* operator new(size_t /*size*/, void* ptr) noexcept {
return ptr; // Just return the pointer, no allocation
}
// Phase 50: Placement new operator - integrates with Lua's GC (implemented in lgc.h)
// Note: For TString, this may allocate less than sizeof(TString) for short strings!
static void* operator new(size_t size, lua_State* L, lu_byte tt, size_t extra = 0);
// Disable regular new/delete (must use placement new with GC)
static void* operator new(size_t) = delete;
static void operator delete(void*) = delete;
// Type checks
bool isShort() const noexcept { return shrlen >= 0; }
bool isLong() const noexcept { return shrlen < 0; }
bool isExternal() const noexcept { return isLong() && shrlen != LSTRREG; }
// Accessors
size_t length() const noexcept {
return isShort() ? static_cast<size_t>(shrlen) : u.lnglen;
}
ls_byte getShrlen() const noexcept { return shrlen; }
size_t getLnglen() const noexcept { return u.lnglen; }
unsigned int getHash() const noexcept { return hash; }
lu_byte getExtra() const noexcept { return extra; }
const char* c_str() const noexcept {
return isShort() ? getContentsAddr() : contents;
}
char* getContentsPtr() noexcept { return isShort() ? getContentsAddr() : contents; }
char* getContentsField() noexcept { return contents; }
const char* getContentsField() const noexcept { return contents; }
// For short strings: return address where inline string data starts (after 'u' union)
// For long strings: would return same address (where contents pointer is stored)
char* getContentsAddr() noexcept { return cast_charp(this) + contentsOffset(); }
const char* getContentsAddr() const noexcept { return cast_charp(this) + contentsOffset(); }
lua_Alloc getFalloc() const noexcept { return falloc; }
void* getUserData() const noexcept { return ud; }
// Setters
void setExtra(lu_byte e) noexcept { extra = e; }
void setShrlen(ls_byte len) noexcept { shrlen = len; }
void setHash(unsigned int h) noexcept { hash = h; }
void setLnglen(size_t len) noexcept { u.lnglen = len; }
void setContents(char* c) noexcept { contents = c; }
void setFalloc(lua_Alloc f) noexcept { falloc = f; }
void setUserData(void* data) noexcept { ud = data; }
// Hash table operations
TString* getNext() const noexcept { return u.hnext; }
void setNext(TString* next_str) noexcept { u.hnext = next_str; }
// Helper for offset calculations
static constexpr size_t fallocOffset() noexcept {
// Offset of falloc field accounting for alignment
// Must include GCObject base!
struct OffsetHelper {
GCObject base;
lu_byte extra;
ls_byte shrlen;
unsigned int hash;
union { size_t lnglen; TString* hnext; } u;
char* contents;
};
return sizeof(OffsetHelper);
}
static constexpr size_t contentsOffset() noexcept {
// Offset of contents field accounting for GCObject base and alignment
struct OffsetHelper {
GCObject base;
lu_byte extra;
ls_byte shrlen;
unsigned int hash;
union { size_t lnglen; TString* hnext; } u;
};
return sizeof(OffsetHelper);
}
// Method declarations (implemented in lstring.cpp)
unsigned hashLongStr();
bool equals(const TString* other) const;
void remove(lua_State* L); // Phase 25a: from luaS_remove
TString* normalize(lua_State* L); // Phase 25a: from luaS_normstr
// Static factory-like functions (still use luaS_* for now)
// static TString* create(lua_State* L, const char* str, size_t len);
// Comparison operator overloads (defined after l_strcmp declaration)
friend bool operator<(const TString& l, const TString& r) noexcept;
friend bool operator<=(const TString& l, const TString& r) noexcept;
friend bool operator==(const TString& l, const TString& r) noexcept;
friend bool operator!=(const TString& l, const TString& r) noexcept;
};
/* Check if string is short (wrapper for backward compatibility) */
inline bool strisshr(const TString* ts) noexcept { return ts->isShort(); }
/* Check if string is external (fixed or with custom deallocator) */
inline bool isextstr(const TValue* v) noexcept {
return ttislngstring(v) && tsvalue(v)->isExternal();
}
inline bool TValue::isExtString() const noexcept {
return isLongString() && stringValue()->isExternal();
}
/*
** Get the actual string (array of bytes) from a 'TString'. (Generic
** version and specialized versions for long and short strings.)
*/
inline char* rawgetshrstr(TString* ts) noexcept {
return ts->getContentsAddr();
}
inline const char* rawgetshrstr(const TString* ts) noexcept {
return ts->getContentsAddr();
}
/*
** String accessor functions (Phase 46: converted from macros to inline functions)
** These provide type-safe access to string contents with assertions.
*/
/* Get short string contents (asserts string is short) */
inline char* getshrstr(TString* ts) noexcept {
lua_assert(ts->isShort());
return ts->getContentsAddr();
}
inline const char* getshrstr(const TString* ts) noexcept {
lua_assert(ts->isShort());
return ts->getContentsAddr();
}
/* Get long string contents (asserts string is long) */
inline char* getlngstr(TString* ts) noexcept {
lua_assert(ts->isLong());
return ts->getContentsField();
}
inline const char* getlngstr(const TString* ts) noexcept {
lua_assert(ts->isLong());
return ts->getContentsField();
}
/* Get string contents (works for both short and long strings) */
inline char* getstr(TString* ts) noexcept {
return ts->getContentsPtr();
}
inline const char* getstr(const TString* ts) noexcept {
return ts->c_str();
}
/* get string length from 'TString *ts' */
inline size_t tsslen(const TString* ts) noexcept {
return ts->length();
}
/*
** Get string and length */
inline const char* getlstr(const TString* ts, size_t& len) noexcept {
len = ts->length();
return ts->c_str();
}
/* }================================================================== */
/*
** {==================================================================
** Userdata
** ===================================================================
*/
/*
** Light userdata should be a variant of userdata, but for compatibility
** reasons they are also different types.
*/
inline constexpr int LUA_VLIGHTUSERDATA = makevariant(LUA_TLIGHTUSERDATA, 0);
inline constexpr int LUA_VUSERDATA = makevariant(LUA_TUSERDATA, 0);
constexpr bool ttislightuserdata(const TValue* o) noexcept { return checktag(o, LUA_VLIGHTUSERDATA); }
constexpr bool ttisfulluserdata(const TValue* o) noexcept { return checktag(o, ctb(LUA_VUSERDATA)); }
constexpr bool TValue::isLightUserdata() const noexcept { return checktag(this, LUA_VLIGHTUSERDATA); }
constexpr bool TValue::isFullUserdata() const noexcept { return checktag(this, ctb(LUA_VUSERDATA)); }
inline void* pvalue(const TValue* o) noexcept { return o->pointerValue(); }
inline Udata* uvalue(const TValue* o) noexcept { return o->userdataValue(); }
constexpr void* pvalueraw(const Value& v) noexcept { return v.p; }
/* setpvalue and setuvalue now defined as inline functions below */
/* Ensures that addresses after this type are always fully aligned. */
typedef union UValue {
TValue uv;
LUAI_MAXALIGN; /* ensures maximum alignment for udata bytes */
} UValue;
/*
** Header for userdata with user values;
** memory area follows the end of this structure.
*/
// Udata inherits from GCBase (CRTP)
class Udata : public GCBase<Udata> {
private:
unsigned short nuvalue; /* number of user values */
size_t len; /* number of bytes */
Table *metatable;
GCObject *gclist;
UValue uv[1]; /* user values */
public:
// Phase 50: Constructor - initializes all fields to safe defaults
Udata() noexcept {
nuvalue = 0;
len = 0;
metatable = nullptr;
gclist = nullptr;
// Note: uv array will be initialized by caller if needed
}
// Phase 50: Destructor - trivial (GC handles deallocation)
// MUST be empty (not = default) for variable-size objects
~Udata() noexcept {}
// Phase 50: Special placement new for variable-size objects
static void* operator new(size_t /*size*/, void* ptr) noexcept {
return ptr; // Just return the pointer, no allocation
}
// Phase 50: Placement new operator - integrates with Lua's GC (implemented in lgc.h)
static void* operator new(size_t size, lua_State* L, lu_byte tt, size_t extra = 0);
// Disable regular new/delete (must use placement new with GC)
static void* operator new(size_t) = delete;
static void operator delete(void*) = delete;
// Inline accessors
size_t getLen() const noexcept { return len; }
void setLen(size_t l) noexcept { len = l; }
unsigned short getNumUserValues() const noexcept { return nuvalue; }
void setNumUserValues(unsigned short n) noexcept { nuvalue = n; }
Table* getMetatable() const noexcept { return metatable; }
void setMetatable(Table* mt) noexcept { metatable = mt; }
Table** getMetatablePtr() noexcept { return &metatable; }
GCObject* getGclist() noexcept { return gclist; }
void setGclist(GCObject* gc) noexcept { gclist = gc; }
// For GC gray list traversal - allows efficient list manipulation
GCObject** getGclistPtr() noexcept { return &gclist; }
UValue* getUserValue(int idx) noexcept { return &uv[idx]; }
const UValue* getUserValue(int idx) const noexcept { return &uv[idx]; }
// Note: getMemory() uses function udatamemoffset which requires Udata0 to be defined
inline void* getMemory() noexcept;
inline const void* getMemory() const noexcept;
// Static method to compute UV offset (needed for udatamemoffset function)
static constexpr size_t uvOffset() noexcept { return offsetof(Udata, uv); }
};
/*
** Header for userdata with no user values. These userdata do not need
** to be gray during GC, and therefore do not need a 'gclist' field.
** To simplify, the code always use 'Udata' for both kinds of userdata,
** making sure it never accesses 'gclist' on userdata with no user values.
** This structure here is used only to compute the correct size for
** this representation. (The 'bindata' field in its end ensures correct
** alignment for binary data following this header.)
*/
// Udata0 inherits from GCBase (CRTP)
typedef struct Udata0 : public GCBase<Udata0> {
unsigned short nuvalue; /* number of user values */
size_t len; /* number of bytes */
Table *metatable;
union {LUAI_MAXALIGN;} bindata;
} Udata0;
/* compute the offset of the memory area of a userdata */
// Phase 49: Convert macro to constexpr function
// offsetof for non-standard-layout types (classes with GCBase inheritance)
// This triggers -Winvalid-offsetof but is safe because we control the memory layout
constexpr inline size_t udatamemoffset(int nuv) noexcept {
return (nuv == 0) ? offsetof(Udata0, bindata)
: Udata::uvOffset() + (sizeof(UValue) * static_cast<size_t>(nuv));
}
/* get the address of the memory block inside 'Udata' */
// Phase 49: Convert macro to inline function with const overload
inline char* getudatamem(Udata* u) noexcept {
return cast_charp(u) + udatamemoffset(u->getNumUserValues());
}
inline const char* getudatamem(const Udata* u) noexcept {
return cast_charp(u) + udatamemoffset(u->getNumUserValues());
}
/* compute the size of a userdata */
// Phase 49: Convert macro to constexpr function
constexpr inline size_t sizeudata(int nuv, size_t nb) noexcept {
return udatamemoffset(nuv) + nb;
}
// Implementation of Udata::getMemory() now that Udata0 is defined
inline void* Udata::getMemory() noexcept {
return getudatamem(this);
}
inline const void* Udata::getMemory() const noexcept {
return getudatamem(this); // Calls const overload
}
/* }================================================================== */
/*
** {==================================================================
** Prototypes
** ===================================================================
*/
inline constexpr int LUA_VPROTO = makevariant(LUA_TPROTO, 0);
typedef l_uint32 Instruction;
/*
** Description of an upvalue for function prototypes
*/
class Upvaldesc {
private:
TString *name; /* upvalue name (for debug information) */
lu_byte instack; /* whether it is in stack (register) */
lu_byte idx; /* index of upvalue (in stack or in outer function's list) */
lu_byte kind; /* kind of corresponding variable */
public:
// Inline accessors
TString* getName() const noexcept { return name; }
TString** getNamePtr() noexcept { return &name; } // For serialization
bool isInStack() const noexcept { return instack != 0; }
lu_byte getInStackRaw() const noexcept { return instack; }
lu_byte getIndex() const noexcept { return idx; }
lu_byte getKind() const noexcept { return kind; }
// Inline setters
void setName(TString* n) noexcept { name = n; }
void setInStack(lu_byte val) noexcept { instack = val; }
void setIndex(lu_byte i) noexcept { idx = i; }
void setKind(lu_byte k) noexcept { kind = k; }
};
/*
** Description of a local variable for function prototypes
** (used for debug information)
*/
class LocVar {
private:
TString *varname;
int startpc; /* first point where variable is active */
int endpc; /* first point where variable is dead */
public:
// Inline accessors
TString* getVarName() const noexcept { return varname; }
TString** getVarNamePtr() noexcept { return &varname; } // For serialization
int getStartPC() const noexcept { return startpc; }
int getEndPC() const noexcept { return endpc; }
bool isActive(int pc) const noexcept { return startpc <= pc && pc < endpc; }
// Inline setters
void setVarName(TString* name) noexcept { varname = name; }
void setStartPC(int pc) noexcept { startpc = pc; }
void setEndPC(int pc) noexcept { endpc = pc; }
};
/*
** Associates the absolute line source for a given instruction ('pc').
** The array 'lineinfo' gives, for each instruction, the difference in
** lines from the previous instruction. When that difference does not
** fit into a byte, Lua saves the absolute line for that instruction.
** (Lua also saves the absolute line periodically, to speed up the
** computation of a line number: we can use binary search in the
** absolute-line array, but we must traverse the 'lineinfo' array
** linearly to compute a line.)
*/
class AbsLineInfo {
private:
int pc;
int line;
public:
// Inline accessors
int getPC() const noexcept { return pc; }
int getLine() const noexcept { return line; }
// Inline setters
void setPC(int p) noexcept { pc = p; }
void setLine(int l) noexcept { line = l; }
};
/*
** Flags in Prototypes
*/
inline constexpr lu_byte PF_ISVARARG = 1;
inline constexpr lu_byte PF_FIXED = 2; /* prototype has parts in fixed memory */
/*
** Proto Subsystem - Debug information management
** Separates debug data from runtime execution data for better organization
*/
class ProtoDebugInfo {
private:
/* Line information */
ls_byte *lineinfo; /* Map from opcodes to source lines */
int sizelineinfo;
AbsLineInfo *abslineinfo; /* Absolute line info for faster lookup */
int sizeabslineinfo;
/* Local variable information */
LocVar *locvars; /* Local variable descriptors */
int sizelocvars;
/* Source location */
int linedefined; /* First line of function definition */
int lastlinedefined; /* Last line of function definition */
TString *source; /* Source file name */
public:
/* Inline accessors */
inline ls_byte* getLineInfo() const noexcept { return lineinfo; }
inline int getLineInfoSize() const noexcept { return sizelineinfo; }
inline AbsLineInfo* getAbsLineInfo() const noexcept { return abslineinfo; }
inline int getAbsLineInfoSize() const noexcept { return sizeabslineinfo; }
inline LocVar* getLocVars() const noexcept { return locvars; }
inline int getLocVarsSize() const noexcept { return sizelocvars; }
inline int getLineDefined() const noexcept { return linedefined; }
inline int getLastLineDefined() const noexcept { return lastlinedefined; }
inline TString* getSource() const noexcept { return source; }
/* Inline setters */
inline void setLineInfo(ls_byte* li) noexcept { lineinfo = li; }
inline void setLineInfoSize(int s) noexcept { sizelineinfo = s; }
inline void setAbsLineInfo(AbsLineInfo* ali) noexcept { abslineinfo = ali; }
inline void setAbsLineInfoSize(int s) noexcept { sizeabslineinfo = s; }
inline void setLocVars(LocVar* lv) noexcept { locvars = lv; }
inline void setLocVarsSize(int s) noexcept { sizelocvars = s; }
inline void setLineDefined(int l) noexcept { linedefined = l; }
inline void setLastLineDefined(int l) noexcept { lastlinedefined = l; }
inline void setSource(TString* s) noexcept { source = s; }
/* Reference accessors for luaM_growvector */
inline int& getLineInfoSizeRef() noexcept { return sizelineinfo; }
inline int& getAbsLineInfoSizeRef() noexcept { return sizeabslineinfo; }
inline int& getLocVarsSizeRef() noexcept { return sizelocvars; }
inline ls_byte*& getLineInfoRef() noexcept { return lineinfo; }
inline AbsLineInfo*& getAbsLineInfoRef() noexcept { return abslineinfo; }
inline LocVar*& getLocVarsRef() noexcept { return locvars; }
/* Pointer accessors */
inline TString** getSourcePtr() noexcept { return &source; }
/* Phase 112: std::span accessors for debug info arrays */
inline std::span<ls_byte> getLineInfoSpan() noexcept {
return std::span(lineinfo, static_cast<size_t>(sizelineinfo));
}
inline std::span<const ls_byte> getLineInfoSpan() const noexcept {
return std::span(lineinfo, static_cast<size_t>(sizelineinfo));
}
inline std::span<AbsLineInfo> getAbsLineInfoSpan() noexcept {
return std::span(abslineinfo, static_cast<size_t>(sizeabslineinfo));
}
inline std::span<const AbsLineInfo> getAbsLineInfoSpan() const noexcept {
return std::span(abslineinfo, static_cast<size_t>(sizeabslineinfo));
}
inline std::span<LocVar> getLocVarsSpan() noexcept {
return std::span(locvars, static_cast<size_t>(sizelocvars));
}
inline std::span<const LocVar> getLocVarsSpan() const noexcept {
return std::span(locvars, static_cast<size_t>(sizelocvars));
}
};
/*
** Function Prototypes
*/
// Proto inherits from GCBase (CRTP)
class Proto : public GCBase<Proto> {
private:
/* Runtime data (always needed for execution) */
lu_byte numparams; /* number of fixed (named) parameters */
lu_byte flag;
lu_byte maxstacksize; /* number of registers needed by this function */
int sizeupvalues; /* size of 'upvalues' */
int sizek; /* size of 'k' */
int sizecode;
int sizep; /* size of 'p' */
TValue *k; /* constants used by the function */
Instruction *code; /* opcodes */
Proto **p; /* functions defined inside the function */
Upvaldesc *upvalues; /* upvalue information */
GCObject *gclist;
/* Debug subsystem (debug information) */
ProtoDebugInfo debugInfo;
public:
// Phase 50: Constructor - initializes all fields to safe defaults
Proto() noexcept {
numparams = 0;
flag = 0;
maxstacksize = 0;
sizeupvalues = 0;
sizek = 0;
sizecode = 0;
sizep = 0;
k = nullptr;
code = nullptr;
p = nullptr;
upvalues = nullptr;
gclist = nullptr;
// Initialize debug info subsystem
debugInfo.setLineInfoSize(0);
debugInfo.setAbsLineInfoSize(0);
debugInfo.setLocVarsSize(0);