rusteal 0.2.0

CLI tool for rusteal: codegen, project setup, and build orchestration
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
// UHT exporter for Rusteal: exports UE reflection data to JSON for codegen consumption.
//
// This is a UBT plugin exporter that runs during Unreal Header Tool processing.
// It produces three JSON files (classes, structs, enums) consumed by rusteal-codegen.
//

using EpicGames.Core;
using EpicGames.UHT.Tables;
using EpicGames.UHT.Types;
using EpicGames.UHT.Utils;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Nodes;

// Disambiguate from EpicGames.Core.JsonObject
using JsonObject = System.Text.Json.Nodes.JsonObject;
using JsonArray = System.Text.Json.Nodes.JsonArray;

namespace Rusteal;

[UnrealHeaderTool]
public static class RustealExport
{
    #region Filter Constants

    // Property flags that always disqualify from export
    private const EPropertyFlags NoExportPropFlags =
        EPropertyFlags.NativeAccessSpecifierPrivate |
        EPropertyFlags.NativeAccessSpecifierProtected;

    // Function flags that always disqualify from export
    private const EFunctionFlags NoExportFuncFlags =
        EFunctionFlags.NetServer |
        EFunctionFlags.NetRequest |
        EFunctionFlags.NetResponse |
        EFunctionFlags.Protected |
        EFunctionFlags.Private |
        EFunctionFlags.Delegate;

    // Property flags indicating script-exposed fields 
    private const EPropertyFlags ScriptExposedPropFlags =
        EPropertyFlags.BlueprintVisible | EPropertyFlags.BlueprintAssignable;

    // Function flags indicating script-exposed fields 
    private const EFunctionFlags ScriptExposedFuncFlags =
        EFunctionFlags.BlueprintCallable | EFunctionFlags.BlueprintEvent;

    // NoExport structs with TBaseStructure<> registration path
    private static readonly HashSet<string> NeedRegisterStruct = new()
    {
        "Rotator", "Quat", "Transform", "Color", "LinearColor", "Plane",
        "Vector", "Vector2D", "Vector4", "RandomStream", "Guid", "Box2D",
        "FallbackStruct", "FloatRangeBound", "FloatRange", "Int32RangeBound",
        "Int32Range", "FloatInterval", "Int32Interval", "FrameNumber",
        "SoftObjectPath", "SoftClassPath", "PrimaryAssetType", "PrimaryAssetId",
        "DateTime", "PolyglotTextData",
    };

    #endregion

    #region Entry Point

    [UhtExporter(
        Name = "Rusteal",
        Description = "Export UE reflection data to JSON for Rusteal Rust codegen",
        Options = UhtExporterOptions.Default,
        ModuleName = "RustealGenerator")]
    public static void Generate(IUhtExportFactory factory)
    {
        new Exporter(factory).Run();
    }

    #endregion

    #region Exporter

    private sealed class Exporter
    {
        private readonly IUhtExportFactory _factory;
        private readonly UhtSession _session;

        private readonly List<JsonObject> _classes = new();
        private readonly List<JsonObject> _structs = new();
        private readonly List<JsonObject> _enums = new();
        private readonly HashSet<string> _exportedClassNames = new();
        private readonly HashSet<string> _exportedStructNames = new();
        private readonly HashSet<string> _exportedEnumNames = new();

        public Exporter(IUhtExportFactory factory)
        {
            _factory = factory;
            _session = factory.Session;
        }

        public void Run()
        {
            CollectTypes();
            WriteJsonFiles();
        }

        // ── Type Collection ─────────────────────────────────────────────

        private void CollectTypes()
        {
            // Export all modules — package-to-module mapping is done downstream by codegen.
            foreach (UhtModule module in _session.Modules)
            {
                string package = module.ShortName;

                foreach (UhtHeaderFile header in module.Headers)
                {
                    foreach (UhtType type in header.Children)
                    {
                        switch (type)
                        {
                            case UhtClass classObj
                                when classObj.ClassType is UhtClassType.Class or UhtClassType.Interface:
                                TryExportClass(classObj, package, header);
                                break;

                            case UhtScriptStruct structObj:
                                TryExportStruct(structObj, package);
                                break;

                            case UhtEnum enumObj:
                                TryExportEnum(enumObj, package);
                                break;
                        }
                    }
                }
            }
        }

        // ── Class Export ────────────────────────────────────────────────

        private void TryExportClass(UhtClass classObj, string package, UhtHeaderFile header)
        {
            string name = StripPrefix(classObj.SourceName);
            if (!_exportedClassNames.Add(name))
                return;

            if (!ShouldExportClass(classObj))
            {
                _exportedClassNames.Remove(name);
                return;
            }

            var props = new JsonArray();
            foreach (UhtProperty prop in classObj.Properties)
            {
                if (ShouldExportProperty(prop))
                    props.Add(ExportProperty(prop));
            }

            var funcs = new JsonArray();
            foreach (UhtFunction func in classObj.Functions)
            {
                if (ShouldExportFunction(func))
                    funcs.Add(ExportFunction(func));
            }

            var interfaces = new JsonArray();
            foreach (UhtStruct baseStruct in classObj.Bases)
            {
                if (baseStruct is UhtClass iface)
                    interfaces.Add(StripPrefix(iface.SourceName));
            }

            string? superName = classObj.SuperClass != null
                ? StripPrefix(classObj.SuperClass.SourceName)
                : null;

            _classes.Add(new JsonObject
            {
                ["name"]        = name,
                ["cpp_name"]    = classObj.SourceName,
                ["package"]     = package,
                ["header"]      = header.IncludeFilePath ?? header.ModuleRelativeFilePath ?? "",
                ["class_flags"] = (long)unchecked((uint)classObj.ClassFlags),
                ["super"]       = superName,
                ["interfaces"]  = interfaces,
                ["props"]       = props,
                ["funcs"]       = funcs,
            });
        }

        private static bool ShouldExportClass(UhtClass classObj)
        {
            // Skip deprecated classes 
            if (classObj.ClassFlags.HasAnyFlags(EClassFlags.Deprecated))
                return false;

            // Must be an API class
            if (!IsApiClass(classObj))
                return false;

            // Must be script-exposed or have script-exposed fields
            return IsScriptExposed(classObj) || HasScriptExposedFields(classObj);
        }

        private static bool IsApiClass(UhtClass classObj)
        {
            return classObj.ClassFlags.HasAnyFlags(EClassFlags.MinimalAPI)
                || classObj.ClassFlags.HasAnyFlags(EClassFlags.RequiredAPI);
        }

        // ── Struct Export ───────────────────────────────────────────────

        private void TryExportStruct(UhtScriptStruct structObj, string package)
        {
            string name = StripPrefix(structObj.SourceName);
            if (!_exportedStructNames.Add(name))
                return;

            if (!ShouldExportStruct(structObj))
            {
                _exportedStructNames.Remove(name);
                return;
            }

            var props = new JsonArray();
            foreach (UhtProperty prop in structObj.Properties)
            {
                if (ShouldExportProperty(prop))
                    props.Add(ExportProperty(prop));
            }

            string? superName = structObj.Super is UhtScriptStruct superStruct
                ? StripPrefix(superStruct.SourceName)
                : null;

            bool hasStaticStruct = !structObj.ScriptStructFlags.HasAnyFlags(EStructFlags.NoExport)
                                || NeedRegisterStruct.Contains(name);

            _structs.Add(new JsonObject
            {
                ["name"]              = name,
                ["cpp_name"]          = structObj.SourceName,
                ["package"]           = package,
                ["struct_flags"]      = (long)unchecked((uint)structObj.ScriptStructFlags),
                ["super"]             = superName,
                ["has_static_struct"] = hasStaticStruct,
                ["props"]             = props,
            });
        }

        private static bool ShouldExportStruct(UhtScriptStruct structObj)
        {
            return IsScriptExposed(structObj) || HasScriptExposedFields(structObj);
        }

        // ── Enum Export ─────────────────────────────────────────────────

        private void TryExportEnum(UhtEnum enumObj, string package)
        {
            string name = enumObj.SourceName;
            if (!_exportedEnumNames.Add(name))
                return;

            if (!ShouldExportEnum(enumObj))
            {
                _exportedEnumNames.Remove(name);
                return;
            }

            var pairs = new JsonArray();
            foreach (UhtEnumValue val in enumObj.EnumValues)
            {
                // Strip "EnumName::" prefix from enum class values
                string valName = val.Name;
                int colonIdx = valName.LastIndexOf("::", StringComparison.Ordinal);
                if (colonIdx >= 0)
                    valName = valName[(colonIdx + 2)..];

                var pair = new JsonArray();
                pair.Add(valName);
                pair.Add(val.Value);
                pairs.Add(pair);
            }

            string underlyingType = enumObj.UnderlyingType switch
            {
                UhtEnumUnderlyingType.Uint8  => "uint8",
                UhtEnumUnderlyingType.Int8   => "int8",
                UhtEnumUnderlyingType.Int16  => "int16",
                UhtEnumUnderlyingType.Uint16 => "uint16",
                UhtEnumUnderlyingType.Int32  => "int32",
                UhtEnumUnderlyingType.Uint32 => "uint32",
                UhtEnumUnderlyingType.Int64  => "int64",
                UhtEnumUnderlyingType.Uint64 => "uint64",
                _                            => "uint8",
            };

            int cppForm = enumObj.CppForm switch
            {
                UhtEnumCppForm.Regular    => 0,
                UhtEnumCppForm.Namespaced => 1,
                UhtEnumCppForm.EnumClass  => 2,
                _                         => 0,
            };

            _enums.Add(new JsonObject
            {
                ["name"]            = name,
                ["cpp_name"]        = name,
                ["package"]         = package,
                ["underlying_type"] = underlyingType,
                ["cpp_form"]        = cppForm,
                ["pairs"]           = pairs,
            });
        }

        private static bool ShouldExportEnum(UhtEnum enumObj)
        {
            return !enumObj.MetaData.ContainsKey("NotBlueprintType");
        }

        // ── Filtering Helpers ───────────────────────────────────────────

        /// <summary>
        /// Walk the inheritance chain checking BlueprintType / NotBlueprintType metadata .
        /// </summary>
        private static bool IsScriptExposed(UhtType type)
        {
            UhtType? current = type;
            while (current != null)
            {
                if (current.MetaData.ContainsKey("BlueprintType")
                    || current.MetaData.ContainsKey("BlueprintSpawnableComponent"))
                    return true;

                if (current.MetaData.ContainsKey("NotBlueprintType"))
                    return false;

                current = current switch
                {
                    UhtClass c        => c.SuperClass,
                    UhtScriptStruct s => s.SuperScriptStruct,
                    _                 => null,
                };
            }
            return false;
        }

        /// <summary>
        /// Check if any property or function in the hierarchy is script-exposed .
        /// </summary>
        private static bool HasScriptExposedFields(UhtStruct structObj)
        {
            UhtStruct? current = structObj;
            while (current != null)
            {
                foreach (UhtType child in current.Children)
                {
                    if (child is UhtProperty prop
                        && prop.PropertyFlags.HasAnyFlags(ScriptExposedPropFlags))
                        return true;

                    if (child is UhtFunction func
                        && func.FunctionFlags.HasAnyFlags(ScriptExposedFuncFlags))
                        return true;
                }

                current = current switch
                {
                    UhtClass c        => c.SuperClass,
                    UhtScriptStruct s => s.SuperScriptStruct,
                    _                 => null,
                };
            }
            return false;
        }

        // ── Property Export ─────────────────────────────────────────────

        private static bool ShouldExportProperty(UhtProperty prop)
        {
            // Skip private/protected
            if (prop.PropertyFlags.HasAnyFlags(NoExportPropFlags))
                return false;

            // Skip deprecated
            if (prop.PropertyFlags.HasAnyFlags(EPropertyFlags.Deprecated))
                return false;

            // Skip editor-only (default: not exporting editor props)
            if (prop.PropertyFlags.HasAnyFlags(EPropertyFlags.EditorOnly))
                return false;

            return true;
        }

        /// <summary>Export a class/struct member property.</summary>
        private static JsonObject ExportProperty(UhtProperty prop)
        {
            var info = new JsonObject
            {
                ["name"]       = prop.SourceName,
                ["type"]       = GetPropertyTypeName(prop),
                ["prop_flags"] = unchecked((long)(ulong)prop.PropertyFlags),
                ["array_dim"]  = GetArrayDim(prop),
            };

            PopulateSubTypeFields(prop, info);

            info["getter"]  = GetMetaOrNull(prop, "BlueprintGetter");
            info["setter"]  = GetMetaOrNull(prop, "BlueprintSetter");
            info["default"] = (JsonNode?)null;

            return info;
        }

        /// <summary>Export a function parameter.</summary>
        private static JsonObject ExportParam(UhtProperty prop, UhtFunction ownerFunc)
        {
            var info = new JsonObject
            {
                ["name"]       = prop.SourceName,
                ["type"]       = GetPropertyTypeName(prop),
                ["prop_flags"] = unchecked((long)(ulong)prop.PropertyFlags),
            };

            PopulateSubTypeFields(prop, info);

            // Default value from function metadata: CPP_Default_{ParamName}
            string defaultKey = $"CPP_Default_{prop.SourceName}";
            if (ownerFunc.MetaData.TryGetValue(defaultKey, out string? defaultVal))
                info["default"] = defaultVal;
            else
                info["default"] = (JsonNode?)null;

            return info;
        }

        /// <summary>Export a container inner property (recursive, minimal).</summary>
        private static JsonObject ExportInnerProperty(UhtProperty prop)
        {
            var info = new JsonObject
            {
                ["name"]       = prop.SourceName,
                ["type"]       = GetPropertyTypeName(prop),
                ["prop_flags"] = unchecked((long)(ulong)prop.PropertyFlags),
            };
            PopulateSubTypeFields(prop, info);
            return info;
        }

        /// <summary>
        /// Populate sub-type fields based on property type.
        /// Uses separate if-blocks (not else-if) because types may set multiple fields.
        /// </summary>
        private static void PopulateSubTypeFields(UhtProperty prop, JsonObject info)
        {
            // Initialize all sub-type fields to null
            info["enum_name"]            = (JsonNode?)null;
            info["enum_cpp_name"]        = (JsonNode?)null;
            info["enum_cpp_form"]        = (JsonNode?)null;
            info["enum_underlying_type"] = (JsonNode?)null;
            info["class_name"]           = (JsonNode?)null;
            info["meta_class_name"]      = (JsonNode?)null;
            info["struct_name"]          = (JsonNode?)null;
            info["interface_name"]       = (JsonNode?)null;
            info["func_info"]            = (JsonNode?)null;
            info["inner_prop"]           = (JsonNode?)null;
            info["key_prop"]             = (JsonNode?)null;
            info["value_prop"]           = (JsonNode?)null;

            // ByteProperty with enum
            if (prop is UhtByteProperty { Enum: not null } byteProp)
            {
                info["enum_name"]     = byteProp.Enum.SourceName;
                info["enum_cpp_name"] = byteProp.Enum.SourceName;
                info["enum_cpp_form"] = (int)byteProp.Enum.CppForm;
            }

            // EnumProperty
            if (prop is UhtEnumProperty enumProp)
            {
                info["enum_name"]     = enumProp.Enum.SourceName;
                info["enum_cpp_name"] = enumProp.Enum.SourceName;
                info["enum_cpp_form"] = (int)enumProp.Enum.CppForm;
                info["enum_underlying_type"] = enumProp.UnderlyingProperty != null
                    ? GetUnderlyingTypeName(enumProp.UnderlyingProperty)
                    : "uint8";
            }

            // ObjectPropertyBase → class_name (covers Object, ObjectPtr, Weak, Soft, Class subtypes)
            if (prop is UhtObjectPropertyBase objPropBase)
            {
                info["class_name"] = StripPrefix(objPropBase.Class.SourceName);
            }

            // ClassProperty → meta_class_name (TSubclassOf<T>)
            if (prop is UhtClassProperty classProp)
            {
                info["meta_class_name"] = StripPrefix(classProp.MetaClass.SourceName);
            }

            // SoftClassProperty → meta_class_name (TSoftClassPtr<T>)
            if (prop is UhtSoftClassProperty softClassProp)
            {
                info["meta_class_name"] = StripPrefix(softClassProp.MetaClass.SourceName);
            }

            // InterfaceProperty → interface_name
            if (prop is UhtInterfaceProperty ifaceProp)
            {
                info["interface_name"] = StripPrefix(ifaceProp.InterfaceClass.SourceName);
            }

            // StructProperty → struct_name
            if (prop is UhtStructProperty structProp)
            {
                info["struct_name"] = StripPrefix(structProp.ScriptStruct.SourceName);
            }

            // DelegateProperty → func_info
            if (prop is UhtDelegateProperty delProp)
            {
                info["func_info"] = ExportDelegateSignature(delProp.Function);
            }

            // MulticastDelegateProperty → func_info (covers Inline and Sparse subtypes)
            if (prop is UhtMulticastDelegateProperty mdelProp)
            {
                info["func_info"] = ExportDelegateSignature(mdelProp.Function);
            }

            // ArrayProperty → inner_prop (recursive)
            if (prop is UhtArrayProperty arrProp)
            {
                info["inner_prop"] = ExportInnerProperty(arrProp.ValueProperty);
            }

            // SetProperty → element_prop (recursive)
            if (prop is UhtSetProperty setProp)
            {
                info["element_prop"] = ExportInnerProperty(setProp.ValueProperty);
            }

            // MapProperty → key_prop + value_prop (recursive)
            if (prop is UhtMapProperty mapProp)
            {
                info["key_prop"]   = ExportInnerProperty(mapProp.KeyProperty);
                info["value_prop"] = ExportInnerProperty(mapProp.ValueProperty);
            }
        }

        // ── Function Export ─────────────────────────────────────────────

        private static bool ShouldExportFunction(UhtFunction func)
        {
            // Only export regular functions (not delegates)
            if (func.FunctionType != UhtFunctionType.Function)
                return false;

            // Skip functions with excluded flags
            if (func.FunctionFlags.HasAnyFlags(NoExportFuncFlags))
                return false;

            // Skip editor-only functions
            if (func.FunctionFlags.HasAnyFlags(EFunctionFlags.EditorOnly))
                return false;

            // Skip deprecated functions (UE marks these via metadata, not flags)
            if (func.MetaData.ContainsKey("DeprecatedFunction"))
                return false;

            // Must be Native, unless it's a BlueprintEvent override
            if (!func.FunctionFlags.HasAnyFlags(EFunctionFlags.Native)
                && !func.FunctionFlags.HasAnyFlags(EFunctionFlags.BlueprintEvent))
                return false;

            return true;
        }

        private static JsonObject ExportFunction(UhtFunction func)
        {
            var funcParams = new JsonArray();

            // Parameters (excluding return)
            foreach (UhtType childType in func.ParameterProperties.Span)
            {
                if (childType is UhtProperty param)
                    funcParams.Add(ExportParam(param, func));
            }

            // Return value (at end of params array, with CPF_ReturnParm flag)
            if (func.ReturnProperty != null)
                funcParams.Add(ExportParam(func.ReturnProperty, func));

            return new JsonObject
            {
                ["name"]       = func.SourceName,
                ["func_flags"] = (long)unchecked((uint)func.FunctionFlags),
                ["is_static"]  = func.FunctionFlags.HasAnyFlags(EFunctionFlags.Static),
                ["params"]     = funcParams,
            };
        }

        private static JsonObject ExportDelegateSignature(UhtFunction func)
        {
            var funcParams = new JsonArray();

            foreach (UhtType childType in func.ParameterProperties.Span)
            {
                if (childType is UhtProperty param)
                    funcParams.Add(ExportParam(param, func));
            }

            if (func.ReturnProperty != null)
                funcParams.Add(ExportParam(func.ReturnProperty, func));

            return new JsonObject
            {
                ["name"]       = func.StrippedFunctionName ?? func.SourceName,
                ["func_flags"] = (long)unchecked((uint)func.FunctionFlags),
                ["is_static"]  = false,
                ["params"]     = funcParams,
            };
        }

        // ── JSON Output ─────────────────────────────────────────────────

        private void WriteJsonFiles()
        {
            var writerOptions = new JsonWriterOptions
            {
                Indented = true,
                Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
            };

            WriteFile("rusteal_classes", new JsonObject
            {
                ["classes"] = ToJsonArray(_classes),
            }, writerOptions);

            WriteFile("rusteal_structs", new JsonObject
            {
                ["structs"] = ToJsonArray(_structs),
            }, writerOptions);

            WriteFile("rusteal_enums", new JsonObject
            {
                ["enums"] = ToJsonArray(_enums),
            }, writerOptions);
        }

        private void WriteFile(string name, JsonObject content, JsonWriterOptions writerOptions)
        {
            string path = _factory.MakePath(name, ".json");
            using var stream = new MemoryStream();
            using (var writer = new Utf8JsonWriter(stream, writerOptions))
            {
                content.WriteTo(writer);
            }
            string json = Encoding.UTF8.GetString(stream.ToArray());
            _factory.CommitOutput(path, new StringBuilder(json));
        }

        private static JsonArray ToJsonArray(List<JsonObject> items)
        {
            var arr = new JsonArray();
            foreach (var item in items)
                arr.Add(item);
            return arr;
        }

        // ── Utilities ───────────────────────────────────────────────────

        /// <summary>
        /// Strip common UE type prefixes: A (actors), U (objects), F (structs).
        /// Does NOT strip E (enums) — enum names are used as-is.
        /// </summary>
        private static string StripPrefix(string name)
        {
            if (name.Length <= 1) return name;
            if (name[0] is 'A' or 'U' or 'F' && char.IsUpper(name[1]))
                return name[1..];
            return name;
        }

        /// <summary>
        /// Map a UhtProperty subclass to its JSON type name string.
        /// Normalizes ObjectPtrProperty → ObjectProperty, ClassPtrProperty → ClassProperty.
        /// Order matters: more specific types must come before their base classes.
        /// </summary>
        private static string GetPropertyTypeName(UhtProperty prop) => prop switch
        {
            // Numeric types (no inheritance issues)
            UhtBoolProperty   => "BoolProperty",
            UhtByteProperty   => "ByteProperty",
            UhtInt8Property   => "Int8Property",
            UhtInt16Property  => "Int16Property",
            UhtIntProperty    => "IntProperty",
            UhtInt64Property  => "Int64Property",
            UhtUInt16Property => "UInt16Property",
            UhtUInt32Property => "UInt32Property",
            UhtUInt64Property => "UInt64Property",
            UhtFloatProperty  => "FloatProperty",
            UhtDoubleProperty => "DoubleProperty",
            UhtLargeWorldCoordinatesRealProperty => "DoubleProperty",

            // String types
            UhtStrProperty  => "StrProperty",
            UhtNameProperty => "NameProperty",
            UhtTextProperty => "TextProperty",

            // Enum / Struct
            UhtEnumProperty   => "EnumProperty",
            UhtStructProperty => "StructProperty",

            // Object hierarchy: most specific first
            UhtClassProperty         => "ClassProperty",
            UhtSoftClassProperty     => "SoftClassProperty",
            UhtSoftObjectProperty    => "SoftObjectProperty",
            UhtWeakObjectPtrProperty => "WeakObjectProperty",
            UhtLazyObjectPtrProperty => "LazyObjectProperty",
            UhtObjectProperty        => "ObjectProperty",

            // Interface
            UhtInterfaceProperty => "InterfaceProperty",

            // Delegates: most specific first
            UhtDelegateProperty                   => "DelegateProperty",
            UhtMulticastInlineDelegateProperty     => "MulticastInlineDelegateProperty",
            UhtMulticastSparseDelegateProperty     => "MulticastSparseDelegateProperty",
            UhtMulticastDelegateProperty           => "MulticastDelegateProperty",

            // Containers
            UhtArrayProperty     => "ArrayProperty",
            UhtSetProperty       => "SetProperty",
            UhtMapProperty       => "MapProperty",

            // Other
            UhtFieldPathProperty => "FieldPathProperty",

            _ => prop.EngineClassName,
        };

        private static int GetArrayDim(UhtProperty prop)
        {
            if (string.IsNullOrEmpty(prop.ArrayDimensions))
                return 1;
            return int.TryParse(prop.ArrayDimensions, out int dim) ? dim : 2;
        }

        private static string GetUnderlyingTypeName(UhtProperty prop) => prop switch
        {
            UhtByteProperty   => "uint8",
            UhtInt8Property   => "int8",
            UhtInt16Property  => "int16",
            UhtUInt16Property => "uint16",
            UhtIntProperty    => "int32",
            UhtUInt32Property => "uint32",
            UhtInt64Property  => "int64",
            UhtUInt64Property => "uint64",
            _                 => "uint8",
        };

        private static string? GetMetaOrNull(UhtType type, string key)
        {
            return type.MetaData.TryGetValue(key, out string? value) ? value : null;
        }
    }

    #endregion
}