submilli-engine 0.3.0

Compiles Submilli programs, a TypeScript subset, to WebAssembly and runs them under capability policy
Documentation
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
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
//! Maps [`MangledName`] to Wasm indices for types, functions, and globals —
//! both imported symbols and consumer-local declarations.

use std::collections::{BTreeMap, BTreeSet, HashMap};

use wasm_encoder::{HeapType, RefType, ValType};

use crate::codegen::closures::ClosureSig;
use crate::codegen::internal_failure;
use crate::codegen::intrinsics::{IntrinsicTypeIndices, intrinsic_supertypes};
use crate::compiler_error::CompilerFailure;
use crate::{Dispatch, ExprId, MangledName, Type};

/// One step of a constructor's field-setup sequence, run after `super(...)`
/// (or at the top of a base class's init fn): own-field initializers and
/// parameter-property copies, in execution order.
#[derive(Clone, Debug)]
pub enum FieldSetup {
    /// `this.field = <initializer expr>`.
    Init { field: String, value: ExprId },
    /// Read the current parameter storage after defaults, including captured cells.
    ParamCopy {
        field: String,
        param: Box<crate::TypedParam>,
    },
    /// `this.field = undefined` for an optional field that redeclares an inherited
    /// one with no initializer of its own. The slot is the parent's, so without
    /// this it would keep the parent's initialized value.
    Reset { field: String },
}

#[derive(Default, Clone, Copy, Debug)]
pub struct ClassGuardLayout {
    pub inheritance_depth: u32,
    pub named_payload_len: u32,
    pub has_instance_guards: bool,
}

#[derive(Default, Clone, Debug)]
pub struct SymbolTable {
    pub(crate) field_lookup_function: Option<u32>,
    pub(crate) resultless_functions: BTreeSet<u32>,
    /// Declared defaults of a host function's Wasm parameters, by position.
    host_parameter_defaults: BTreeMap<u32, Vec<Option<crate::DefaultValue>>>,
    pub class_type_parameters: BTreeMap<MangledName, Vec<String>>,
    pub runtime_generic_functions: BTreeSet<MangledName>,
    pub field_guard_targets: BTreeMap<u32, Type>,
    pub type_descriptor_functions: BTreeMap<Type, u32>,
    pub type_descriptor_globals: BTreeMap<Type, u32>,
    types: BTreeMap<MangledName, u32>,
    funcs: BTreeMap<MangledName, u32>,
    globals: BTreeMap<MangledName, u32>,
    global_types: BTreeMap<MangledName, Type>,
    init_guards: BTreeMap<MangledName, crate::codegen::init_guard::InitFlag>,
    /// The flags of guarded classes, by the index of the top-level statement
    /// their declaration precedes.
    class_declaration_flags: BTreeMap<usize, Vec<u32>>,
    intrinsic_type_indices: Option<IntrinsicTypeIndices>,
    pub(crate) this_environment_type: Option<u32>,
    pub(crate) call_metadata_type: Option<u32>,
    pub(crate) function_argument_metadata: BTreeMap<MangledName, String>,
    // Per-class WasmGC artifacts, keyed by the class's mangled name. Classes are
    // nominal (one struct type each), unlike arity-shared object subtypes.
    class_struct_type_idx: BTreeMap<MangledName, u32>,
    class_vtable_type_idx: BTreeMap<MangledName, u32>,
    class_vtable_global_idx: BTreeMap<MangledName, u32>,
    class_getter_global_idx: BTreeMap<MangledName, u32>,
    class_setter_global_idx: BTreeMap<MangledName, u32>,
    class_method_func_idx: BTreeMap<(MangledName, String), u32>,
    /// Wasm fn index of a class's constructor *init* function — the body that
    /// initializes fields on an already-allocated instance (self-first ABI), as
    /// distinct from the allocating entry constructor. `super(...)` calls it.
    class_ctor_init_func_idx: BTreeMap<MangledName, u32>,
    /// Wasm fn index of a class method's closure-ABI adapter, for the per-instance
    /// method closures placed in the object-fields payload (interface-typed dispatch).
    class_method_adapter_func_idx: BTreeMap<(MangledName, String), u32>,
    /// Vtable slot index (4 + declaration position) of a class method, for static
    /// `call_ref` dispatch; keyed for every class in the method's inheritance chain.
    class_method_slot: BTreeMap<(MangledName, String), u32>,
    /// Methods whose current callable value lives in the mutable instance payload.
    class_payload_methods: BTreeSet<(MangledName, String)>,
    /// Member names this module may write through a structural alias.
    rewritable_members: crate::codegen::classes::RewritableMembers,
    /// Wasm fn-type index of a class method's signature, for the `call_ref`.
    class_method_sig: BTreeMap<(MangledName, String), u32>,
    /// Physical Wasm signature of a class method's vtable slot, keyed for every
    /// class in the chain like `class_method_sig`.
    class_method_abi: BTreeMap<(MangledName, String), MethodSlotAbi>,
    /// Wasm parameter types of a class's constructor (implicit subclass ctors
    /// inherit the parent's).
    class_ctor_abi: BTreeMap<MangledName, Vec<ValType>>,
    /// Struct slot index (4 + declaration position) of a class field, for
    /// `struct.get`/`struct.set` on a class-typed receiver.
    class_field_slot: BTreeMap<(MangledName, String), u32>,
    /// Read guards, keyed by `(class, field)`. See [`crate::FieldNarrowingCheck`].
    class_field_narrowing_check: BTreeMap<(MangledName, String), crate::FieldNarrowingCheck>,
    /// Constructor field-setup steps (parameter-property copies then own-field
    /// initializers) emitted at the post-`super()` field-setup point.
    class_field_setup: BTreeMap<MangledName, Vec<FieldSetup>>,
    vtable_global_idx: BTreeMap<Type, u32>,
    field_names_global_idx: BTreeMap<Vec<super::field_names::FieldName>, u32>,
    optional_field_name_type: Option<u32>,
    field_name_string_global_idx: BTreeMap<String, u32>,
    // Keyed by ValType so language types sharing a Wasm representation share one box.
    box_type_idx: HashMap<ValType, u32>,
    /// Declared Wasm supertype of each struct type the module emits, child →
    /// parent, for [`ref_fits_slot`](Self::ref_fits_slot).
    struct_supertype: BTreeMap<u32, u32>,
    closure_func_type_idx: BTreeMap<ClosureSig, u32>,
    closure_struct_type_idx: BTreeMap<ClosureSig, u32>,
    closure_coercions: BTreeMap<ClosureSig, u32>,
    closure_coercion_vtable_type: Option<u32>,
    env_type_idx: BTreeMap<ExprId, u32>,
    closure_func_idx: BTreeMap<ExprId, u32>,
    closure_vtable_global_idx: Option<u32>,
    /// The sole exception tag's index, recorded at import emission.
    error_tag_idx: Option<u32>,
    adapter_func_idx: BTreeMap<MangledName, u32>,
    adapter_closure_global_idx: BTreeMap<MangledName, u32>,
    /// The closure caches typed `anyref` because the function's package exports
    /// them, so its consumers share one closure; see `function_adapters`.
    shared_closure_globals: BTreeSet<MangledName>,
    /// Runtime validator helpers keyed by recursive alias or interface back-edges.
    runtime_validator_idx: BTreeMap<Type, u32>,
    generic_runtime_validators: BTreeMap<MangledName, (Vec<String>, u32)>,
    instance_field_guards: BTreeMap<(Type, MangledName, String), u32>,
    class_guard_layout: BTreeMap<MangledName, ClassGuardLayout>,
    // Closures, adapters, and direct-dispatch wrappers are NOT in this map.
    top_level_fns: BTreeMap<MangledName, TopLevelFn>,
    iface_dispatch: BTreeMap<MangledName, Dispatch>,
    /// The JavaScript string form of each static-dispatch interface's binding,
    /// which names the object the binding reads as when used as a value.
    static_value_tags: BTreeMap<MangledName, String>,
    /// Physical signature of each Direct/Static-dispatch interface wrapper,
    /// keyed by its `iface#method` dispatch key.
    iface_method_abi: BTreeMap<MangledName, MethodSlotAbi>,
    // Members declared `intrinsic` — codegen emits them inline; nothing imports.
    intrinsic_members: BTreeSet<MangledName>,
}

#[derive(Clone, Debug)]
pub struct TopLevelFn {
    pub wasm_idx: u32,
    pub params: Vec<Type>,
    pub ret: Type,
    /// `true` for host modules whose Wasm ABI uses raw `(ref $rawString)` instead of
    /// `(ref $string)`; drives per-arg extract and post-call rewrap in `emit_direct_call`.
    pub is_host: bool,
}

/// The physical Wasm signature of a dispatched method — a class-method vtable
/// slot, or a Direct/Static-dispatch interface wrapper — captured where the
/// signature is built rather than re-derived at each call site.
///
/// A class slot's signature belongs to the ancestor that introduced it, and
/// erases class types and type variables (see
/// [`slot_value_type`](SymbolTable::slot_value_type)), so it can differ from
/// what an overriding method declares; an interface wrapper's signature erases
/// the interface's type parameters the same way. Call sites coerce arguments
/// into [`params`](Self::params) and cast [`ret`](Self::ret) back to the
/// call-site type; an overriding body binds `params` and returns `ret`
/// whatever its own annotations say.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct MethodSlotAbi {
    /// User parameters; the leading `self` is excluded.
    pub params: Vec<ValType>,
    /// `None` for a void slot.
    pub ret: Option<ValType>,
}

/// Whether a type occupies the erased (boxed) object slot rather than its own
/// concrete lowering. Class types are included: an erased slot must lower the
/// same way regardless of whether the class's struct type has been recorded yet
/// — imported classes are reconstructed before local slot signatures are built,
/// local classes after, and box cells are collected before either — and
/// regardless of which package is compiling it. A union erases whole if any
/// member does; a fully concrete union already lowers identically everywhere.
pub fn is_erased(ty: &Type) -> bool {
    match ty.peel() {
        Type::TypeVar(_) | Type::GenericParam { .. } | Type::ClassRef { .. } => true,
        Type::Union(members) => members.iter().any(is_erased),
        _ => false,
    }
}

/// The *lowering* question — whether a Wasm slot of this type can hold null.
/// See [`may_hold_null`] for the language-level one.
pub(crate) fn is_nullable_ref(val: ValType) -> bool {
    matches!(val, ValType::Ref(RefType { nullable: true, .. }))
}

/// True iff `ty`'s value space contains `null`.
///
/// The *semantic* question, deliberately not `is_nullable_ref(value_type(ty))`:
/// an `InterfaceRef` and an unrecorded `ClassRef` lower to a nullable
/// `(ref null $Object)` without admitting `null` at the language level, and the
/// `ClassRef` lowering is phase-dependent besides. Codegen reads this wherever
/// it has to decide "can this value be null at runtime" — the null-aware `===`
/// dispatch, `JSON.stringify`, and the object-shape `toJson` emitter.
pub(crate) fn may_hold_null(ty: &Type) -> bool {
    match ty.peel() {
        // A recursion back-edge is a name codegen has no body for, and the alias
        // it names often does list `null` (`type J = number | null | Wrap[]`).
        Type::Null
        | Type::Void
        | Type::Unknown
        | Type::TypeVar(_)
        | Type::GenericParam { .. }
        | Type::AliasRef { .. } => true,
        Type::Union(members) => members.iter().any(may_hold_null),
        _ => false,
    }
}

impl SymbolTable {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn type_idx(&self, mangled: &MangledName) -> Option<u32> {
        self.types.get(mangled).copied()
    }

    pub fn func_idx(&self, mangled: &MangledName) -> Option<u32> {
        self.funcs.get(mangled).copied()
    }

    pub fn global_idx(&self, mangled: &MangledName) -> Option<u32> {
        self.globals.get(mangled).copied()
    }

    pub fn global_type(&self, mangled: &MangledName) -> Option<&Type> {
        self.global_types.get(mangled)
    }

    pub fn init_guard(
        &self,
        global: &MangledName,
    ) -> Option<&crate::codegen::init_guard::InitFlag> {
        self.init_guards.get(global)
    }

    pub fn class_declaration_flags(&self, index: usize) -> &[u32] {
        self.class_declaration_flags
            .get(&index)
            .map_or(&[], Vec::as_slice)
    }

    pub fn prelude_func_idx(&self, symbol: &str) -> Option<u32> {
        self.func_idx(&crate::mangle::prelude(symbol))
    }

    pub fn prelude_global_idx(&self, symbol: &str) -> Option<u32> {
        self.global_idx(&crate::mangle::prelude(symbol))
    }

    pub fn string_type_idx(&self) -> Option<u32> {
        self.intrinsic_type_indices.map(|i| i.string)
    }

    pub fn raw_string_type_idx(&self) -> Option<u32> {
        self.intrinsic_type_indices.map(|i| i.raw_string)
    }

    pub fn bigint_type_idx(&self) -> Option<u32> {
        self.intrinsic_type_indices.map(|i| i.bigint)
    }

    pub fn raw_bigint_type_idx(&self) -> Option<u32> {
        self.intrinsic_type_indices.map(|i| i.raw_bigint)
    }

    pub fn regex_type_idx(&self) -> Option<u32> {
        self.intrinsic_type_indices.map(|i| i.regex)
    }

    pub fn regex_match_type_idx(&self) -> Option<u32> {
        self.intrinsic_type_indices.map(|i| i.regex_match)
    }

    pub fn regex_capture_array_type_idx(&self) -> Option<u32> {
        self.intrinsic_type_indices.map(|i| i.regex_capture_array)
    }

    pub fn regex_match_box_type_idx(&self) -> Option<u32> {
        self.intrinsic_type_indices.map(|i| i.regex_match_box)
    }

    pub fn boxed_number_type_idx(&self) -> Option<u32> {
        self.intrinsic_type_indices.map(|i| i.boxed_number)
    }

    pub fn boxed_boolean_type_idx(&self) -> Option<u32> {
        self.intrinsic_type_indices.map(|i| i.boxed_boolean)
    }

    pub fn raw_array_type_idx(&self) -> Option<u32> {
        self.intrinsic_type_indices.map(|i| i.raw_array)
    }

    pub fn field_names_type_idx(&self) -> Option<u32> {
        self.intrinsic_type_indices.map(|i| i.field_names)
    }

    pub fn object_shape_type_idx(&self) -> Option<u32> {
        self.intrinsic_type_indices.map(|i| i.object_shape)
    }

    pub fn array_type_idx(&self) -> Option<u32> {
        self.intrinsic_type_indices.map(|i| i.array)
    }

    pub fn raw_uint8_array_type_idx(&self) -> Option<u32> {
        self.intrinsic_type_indices.map(|i| i.raw_uint8_array)
    }

    pub fn uint8_array_type_idx(&self) -> Option<u32> {
        self.intrinsic_type_indices.map(|i| i.uint8_array)
    }

    pub fn closure_type_idx(&self) -> Option<u32> {
        self.intrinsic_type_indices.map(|i| i.closure)
    }

    pub fn intrinsic_type_indices(&self) -> Option<IntrinsicTypeIndices> {
        self.intrinsic_type_indices
    }

    pub fn object_subtype_idx(&self, ty: &Type) -> Option<u32> {
        match ty {
            Type::Object { .. } => self.object_shape_type_idx(),
            _ => None,
        }
    }

    pub fn class_struct_type_idx(&self, mangled: &MangledName) -> Option<u32> {
        self.class_struct_type_idx.get(mangled).copied()
    }

    pub fn class_vtable_type_idx(&self, mangled: &MangledName) -> Option<u32> {
        self.class_vtable_type_idx.get(mangled).copied()
    }

    pub fn class_vtable_global_idx(&self, mangled: &MangledName) -> Option<u32> {
        self.class_vtable_global_idx.get(mangled).copied()
    }

    pub fn class_getter_global_idx(&self, mangled: &MangledName) -> Option<u32> {
        self.class_getter_global_idx.get(mangled).copied()
    }

    pub fn class_setter_global_idx(&self, mangled: &MangledName) -> Option<u32> {
        self.class_setter_global_idx.get(mangled).copied()
    }

    pub fn class_method_func_idx(&self, class: &MangledName, method: &str) -> Option<u32> {
        self.class_method_func_idx
            .get(&(class.clone(), method.to_string()))
            .copied()
    }

    pub fn class_ctor_init_func_idx(&self, class: &MangledName) -> Option<u32> {
        self.class_ctor_init_func_idx.get(class).copied()
    }

    pub fn class_method_adapter_func_idx(&self, class: &MangledName, method: &str) -> Option<u32> {
        self.class_method_adapter_func_idx
            .get(&(class.clone(), method.to_string()))
            .copied()
    }

    pub fn class_method_slot(&self, class: &MangledName, method: &str) -> Option<u32> {
        self.class_method_slot
            .get(&(class.clone(), method.to_string()))
            .copied()
    }

    pub fn is_class_payload_method(&self, class: &MangledName, method: &str) -> bool {
        self.class_payload_methods
            .contains(&(class.clone(), method.to_string()))
    }

    pub fn class_method_sig(&self, class: &MangledName, method: &str) -> Option<u32> {
        self.class_method_sig
            .get(&(class.clone(), method.to_string()))
            .copied()
    }

    pub fn class_method_abi(&self, class: &MangledName, method: &str) -> Option<&MethodSlotAbi> {
        self.class_method_abi
            .get(&(class.clone(), method.to_string()))
    }

    pub fn class_ctor_abi(&self, class: &MangledName) -> Option<&[ValType]> {
        self.class_ctor_abi.get(class).map(Vec::as_slice)
    }

    pub fn class_field_slot(&self, class: &MangledName, field: &str) -> Option<u32> {
        self.class_field_slot
            .get(&(class.clone(), field.to_string()))
            .copied()
    }

    /// `None` for every ordinary field. See [`crate::FieldNarrowingCheck`].
    pub fn class_field_narrowing_check(
        &self,
        class: &MangledName,
        field: &str,
    ) -> Option<&crate::FieldNarrowingCheck> {
        self.class_field_narrowing_check
            .get(&(class.clone(), field.to_string()))
    }

    pub fn class_field_narrowing_checks<'a>(
        &'a self,
        field: &'a str,
    ) -> impl Iterator<Item = (&'a MangledName, &'a crate::FieldNarrowingCheck)> + 'a {
        self.class_field_narrowing_check
            .iter()
            .filter(move |((_, name), _)| name == field)
            .map(|((class, _), check)| (class, check))
    }

    pub fn class_field_setup(&self, class: &MangledName) -> Option<&[FieldSetup]> {
        self.class_field_setup.get(class).map(Vec::as_slice)
    }

    pub fn vtable_global_idx(&self, ty: &Type) -> Option<u32> {
        self.vtable_global_idx.get(ty).copied()
    }

    pub fn record_optional_field_name_type(&mut self, index: u32) {
        self.optional_field_name_type = Some(index);
    }

    pub fn optional_field_name_type(&self) -> Result<u32, CompilerFailure> {
        self.optional_field_name_type
            .ok_or_else(|| internal_failure("optional field-name type was not declared"))
    }

    pub fn field_names_global_idx(
        &self,
        field_names: &[super::field_names::FieldName],
    ) -> Option<u32> {
        self.field_names_global_idx.get(field_names).copied()
    }

    pub fn field_name_string_global_idx(&self, name: &str) -> Option<u32> {
        self.field_name_string_global_idx.get(name).copied()
    }

    /// Box cells are keyed on [`slot_value_type`](Self::slot_value_type) so the
    /// key a binding registers during collection still resolves once class
    /// struct types are recorded. A cell for an erased type therefore holds
    /// `(ref null $Object)`; reads out of it need `emit_unerase`.
    pub fn box_type_idx(
        &self,
        ty: &Type,
    ) -> Result<Option<u32>, crate::compiler_error::CompilerFailure> {
        Ok(self.box_type_idx.get(&self.slot_value_type(ty)?).copied())
    }

    /// A box struct is the `(ref $box_T)` wrapper a captured-and-mutated binding
    /// is stored behind. Returns the payload type of `idx`, or `None` if `idx`
    /// is not one — so codegen can recognise a slot that holds a box rather than
    /// the value, and know what a `struct.get` off it leaves on the stack.
    ///
    /// The reverse scan is unambiguous because `box_types::collect` dedups by
    /// payload before recording, so one index is registered per payload type.
    pub fn box_payload_type(&self, idx: u32) -> Option<ValType> {
        self.box_type_idx
            .iter()
            .find(|&(_, &v)| v == idx)
            .map(|(payload, _)| *payload)
    }

    pub fn closure_func_type_idx(&self, sig: ClosureSig) -> Option<u32> {
        self.closure_func_type_idx.get(&sig).copied()
    }

    pub fn record_closure_coercion_vtable_type(&mut self, index: u32) {
        self.closure_coercion_vtable_type = Some(index);
    }

    pub fn closure_coercion_vtable_type(
        &self,
    ) -> Result<u32, crate::compiler_error::CompilerFailure> {
        self.closure_coercion_vtable_type.ok_or_else(|| {
            crate::codegen::internal_failure("closure coercion vtable is not registered")
        })
    }

    pub fn closure_signatures(&self) -> impl Iterator<Item = ClosureSig> + '_ {
        self.closure_struct_type_idx.keys().copied()
    }

    pub fn record_closure_coercion(&mut self, target: ClosureSig, index: u32) {
        self.closure_coercions.insert(target, index);
    }

    pub fn closure_coercion(&self, target: ClosureSig) -> Option<u32> {
        self.closure_coercions.get(&target).copied()
    }

    pub fn closure_struct_type_idx(&self, sig: ClosureSig) -> Option<u32> {
        self.closure_struct_type_idx.get(&sig).copied()
    }

    pub fn env_type_idx(&self, expr_id: ExprId) -> Option<u32> {
        self.env_type_idx.get(&expr_id).copied()
    }

    pub fn closure_func_idx(&self, expr_id: ExprId) -> Option<u32> {
        self.closure_func_idx.get(&expr_id).copied()
    }

    pub fn closure_vtable_global_idx(&self) -> Option<u32> {
        self.closure_vtable_global_idx
    }

    pub fn adapter_func_idx(&self, mangled: &MangledName) -> Option<u32> {
        self.adapter_func_idx.get(mangled).copied()
    }

    pub fn adapter_closure_global_idx(&self, mangled: &MangledName) -> Option<u32> {
        self.adapter_closure_global_idx.get(mangled).copied()
    }

    pub fn is_shared_closure_global(&self, mangled: &MangledName) -> bool {
        self.shared_closure_globals.contains(mangled)
    }

    /// Whether a `value`-typed ref already satisfies a `slot` by WasmGC
    /// subtyping, so a coercion needs no instruction.
    ///
    /// Answers `false` whenever the relation isn't known — an unrecorded
    /// supertype edge, an abstract heap type — leaving the caller to emit a
    /// `ref.cast`, which is valid for any two types sharing a hierarchy. Wrong
    /// in that direction costs an always-succeeding cast; wrong in the other
    /// direction is a module the validator rejects.
    pub fn ref_fits_slot(&self, value: RefType, slot: RefType) -> bool {
        if value.nullable && !slot.nullable {
            return false;
        }
        let (HeapType::Concrete(value_idx), HeapType::Concrete(slot_idx)) =
            (value.heap_type, slot.heap_type)
        else {
            return value.heap_type == slot.heap_type;
        };
        let mut current = value_idx;
        while current != slot_idx {
            // Wasm requires a supertype to be declared before its subtypes, so
            // the walk strictly descends and terminates whatever the map holds.
            match self.struct_supertype.get(&current) {
                Some(&parent) if parent < current => current = parent,
                _ => return false,
            }
        }
        true
    }

    pub fn record_type(&mut self, mangled: MangledName, idx: u32) {
        self.types.insert(mangled, idx);
    }

    /// Also seeds the intrinsic hierarchy: those edges are fixed by the indices,
    /// so they can neither be known before this call nor go stale after it.
    pub fn set_intrinsic_type_indices(&mut self, indices: IntrinsicTypeIndices) {
        self.intrinsic_type_indices = Some(indices);
        for (child, parent) in intrinsic_supertypes(indices) {
            self.record_struct_supertype(child, parent);
        }
    }

    pub fn record_struct_supertype(&mut self, child: u32, parent: u32) {
        self.struct_supertype.insert(child, parent);
    }

    pub fn record_class_struct_type(&mut self, mangled: MangledName, idx: u32) {
        self.class_struct_type_idx.insert(mangled, idx);
    }

    pub fn record_class_vtable_type(&mut self, mangled: MangledName, idx: u32) {
        self.class_vtable_type_idx.insert(mangled, idx);
    }

    pub fn record_class_vtable_global(&mut self, mangled: MangledName, idx: u32) {
        self.class_vtable_global_idx.insert(mangled, idx);
    }

    pub fn record_class_getter_global(&mut self, mangled: MangledName, idx: u32) {
        self.class_getter_global_idx.insert(mangled, idx);
    }

    pub fn record_class_setter_global(&mut self, mangled: MangledName, idx: u32) {
        self.class_setter_global_idx.insert(mangled, idx);
    }

    pub fn record_class_method_func(&mut self, class: MangledName, method: String, idx: u32) {
        self.class_method_func_idx.insert((class, method), idx);
    }

    pub fn record_class_ctor_init_func(&mut self, class: MangledName, idx: u32) {
        self.class_ctor_init_func_idx.insert(class, idx);
    }

    pub fn record_class_method_adapter_func(
        &mut self,
        class: MangledName,
        method: String,
        idx: u32,
    ) {
        self.class_method_adapter_func_idx
            .insert((class, method), idx);
    }

    pub fn record_class_method_slot(&mut self, class: MangledName, method: String, slot: u32) {
        self.class_method_slot.insert((class, method), slot);
    }

    pub(crate) fn record_host_parameter_defaults(
        &mut self,
        func_idx: u32,
        defaults: Vec<Option<crate::DefaultValue>>,
    ) {
        self.host_parameter_defaults.insert(func_idx, defaults);
    }

    /// The declared defaults for a call to host function `func_idx`, aligned
    /// to its `arg_count` arguments: entry `i` belongs to argument `i`.
    ///
    /// The arguments fill the trailing parameters, so any leading parameter
    /// without an argument (a method's receiver, already on the stack) is
    /// skipped. A function without recorded defaults has none.
    pub(crate) fn host_call_defaults(
        &self,
        func_idx: u32,
        arg_count: usize,
    ) -> &[Option<crate::DefaultValue>] {
        let defaults = self
            .host_parameter_defaults
            .get(&func_idx)
            .map_or(&[][..], Vec::as_slice);
        let receivers = defaults.len().saturating_sub(arg_count);
        defaults.get(receivers..).unwrap_or_default()
    }

    pub fn record_class_payload_method(&mut self, class: MangledName, method: String) {
        self.class_payload_methods.insert((class, method));
    }

    pub(crate) fn record_rewritable_members(
        &mut self,
        members: crate::codegen::classes::RewritableMembers,
    ) {
        self.rewritable_members = members;
    }

    /// A payload method, local or imported, that this module may overwrite
    /// through a structural alias, so a direct call must read the payload rather
    /// than the class vtable. Every other call keeps the cheaper vtable dispatch.
    pub fn is_rewritable_class_method(&self, class: &MangledName, method: &str) -> bool {
        self.rewritable_members.includes(method) && self.is_class_payload_method(class, method)
    }

    pub fn record_class_method_sig(&mut self, class: MangledName, method: String, sig: u32) {
        self.class_method_sig.insert((class, method), sig);
    }

    pub fn record_class_method_abi(
        &mut self,
        class: MangledName,
        method: String,
        abi: MethodSlotAbi,
    ) {
        self.class_method_abi.insert((class, method), abi);
    }

    pub fn record_class_ctor_abi(&mut self, class: MangledName, params: Vec<ValType>) {
        self.class_ctor_abi.insert(class, params);
    }

    pub fn record_class_field_narrowing_check(
        &mut self,
        class: MangledName,
        field: String,
        check: crate::FieldNarrowingCheck,
    ) {
        self.class_field_narrowing_check
            .insert((class, field), check);
    }

    pub fn record_class_field_slot(&mut self, class: MangledName, field: String, slot: u32) {
        self.class_field_slot.insert((class, field), slot);
    }

    pub fn record_class_field_setup(&mut self, class: MangledName, setup: Vec<FieldSetup>) {
        self.class_field_setup.insert(class, setup);
    }

    pub fn record_vtable_global(&mut self, ty: Type, idx: u32) {
        self.vtable_global_idx.insert(ty, idx);
    }

    pub fn record_field_names_global(
        &mut self,
        field_names: Vec<super::field_names::FieldName>,
        idx: u32,
    ) {
        self.field_names_global_idx.insert(field_names, idx);
    }

    pub fn record_field_name_string_global(&mut self, name: String, idx: u32) {
        self.field_name_string_global_idx.insert(name, idx);
    }

    pub fn record_box_type(&mut self, value_type: ValType, idx: u32) {
        self.box_type_idx.insert(value_type, idx);
    }

    pub fn record_closure_func_type(&mut self, sig: ClosureSig, idx: u32) {
        self.closure_func_type_idx.insert(sig, idx);
    }

    pub fn record_closure_struct_type(&mut self, sig: ClosureSig, idx: u32) {
        self.closure_struct_type_idx.insert(sig, idx);
    }

    pub fn record_env_type(&mut self, expr_id: ExprId, idx: u32) {
        self.env_type_idx.insert(expr_id, idx);
    }

    pub fn record_closure_func_idx(&mut self, expr_id: ExprId, idx: u32) {
        self.closure_func_idx.insert(expr_id, idx);
    }

    pub fn set_closure_vtable_global(&mut self, idx: u32) {
        self.closure_vtable_global_idx = Some(idx);
    }

    // Kept as Option so call sites pattern-match consistently with other optional resources.
    pub fn error_tag_idx(&self) -> Option<u32> {
        self.error_tag_idx
    }

    pub fn set_error_tag_idx(&mut self, idx: u32) {
        self.error_tag_idx = Some(idx);
    }

    pub fn record_adapter_func_idx(&mut self, mangled: MangledName, idx: u32) {
        self.adapter_func_idx.insert(mangled, idx);
    }

    pub fn record_adapter_closure_global_idx(&mut self, mangled: MangledName, idx: u32) {
        self.adapter_closure_global_idx.insert(mangled, idx);
    }

    pub fn record_shared_closure_global_idx(&mut self, mangled: MangledName, idx: u32) {
        self.shared_closure_globals.insert(mangled.clone());
        self.adapter_closure_global_idx.insert(mangled, idx);
    }

    pub fn record_class_guard_layout(
        &mut self,
        class: MangledName,
        parent: Option<&MangledName>,
        named_len: u32,
        guarded: bool,
    ) -> Result<(), CompilerFailure> {
        let depth = match parent {
            Some(parent) => self
                .recorded_class_guard_layout(parent)?
                .inheritance_depth
                .checked_add(1)
                .ok_or_else(|| internal_failure("class inheritance depth overflowed"))?,
            None => 0,
        };
        self.class_guard_layout.insert(
            class,
            ClassGuardLayout {
                inheritance_depth: depth,
                named_payload_len: named_len,
                has_instance_guards: guarded,
            },
        );
        Ok(())
    }

    /// Defaults an unrecorded class to no guards. Only the field-guard emitters
    /// still rely on this until SUB-633 item 17; everything else uses
    /// [`Self::recorded_class_guard_layout`].
    pub fn class_guard_layout(&self, class: &MangledName) -> ClassGuardLayout {
        self.class_guard_layout
            .get(class)
            .copied()
            .unwrap_or_default()
    }

    /// Guard layout of a class this module lays out or reconstructs, which is
    /// recorded before any use.
    pub fn recorded_class_guard_layout(
        &self,
        class: &MangledName,
    ) -> Result<ClassGuardLayout, CompilerFailure> {
        self.class_guard_layout.get(class).copied().ok_or_else(|| {
            internal_failure(format!(
                "class `{}` has no recorded guard layout",
                class.as_str()
            ))
        })
    }

    pub fn record_instance_field_guard(
        &mut self,
        class: Type,
        declaration: MangledName,
        field: String,
        function: u32,
    ) {
        self.instance_field_guards
            .insert((class, declaration, field), function);
    }

    pub fn instance_field_guards<'a>(
        &'a self,
        class: &'a Type,
    ) -> impl Iterator<Item = (&'a MangledName, &'a str, u32)> + 'a {
        self.instance_field_guards
            .iter()
            .filter(move |((ty, _, _), _)| ty == class)
            .map(|((_, declaration, field), function)| (declaration, field.as_str(), *function))
    }

    pub fn record_runtime_validator(&mut self, key: Type, idx: u32) {
        if let Type::AliasRef { mangled, args, .. } | Type::InterfaceRef { mangled, args, .. } =
            &key
            && let Some(names) = generic_parameter_names(args)
        {
            self.generic_runtime_validators
                .insert(mangled.clone(), (names, idx));
        }
        self.runtime_validator_idx.insert(key, idx);
    }

    /// Function index of a recursive runtime validator keyed by an alias or
    /// interface back-edge.
    pub fn runtime_validator_idx(&self, key: &Type) -> Option<u32> {
        self.runtime_validator_idx
            .get(key)
            .copied()
            .or_else(|| self.generic_runtime_validator(key).map(|(_, idx)| idx))
    }

    pub fn generic_runtime_validator(&self, key: &Type) -> Option<(&[String], u32)> {
        let (Type::AliasRef {
            mangled: identity, ..
        }
        | Type::InterfaceRef {
            mangled: identity, ..
        }) = key.peel()
        else {
            return None;
        };
        let (names, index) = self.generic_runtime_validators.get(identity)?;
        if self
            .runtime_validator_idx
            .get(key)
            .is_some_and(|exact| exact != index)
        {
            return None;
        }
        Some((names.as_slice(), *index))
    }

    pub fn record_func(&mut self, mangled: MangledName, idx: u32) {
        self.funcs.insert(mangled, idx);
    }

    pub fn record_global(&mut self, mangled: MangledName, idx: u32) {
        self.globals.insert(mangled, idx);
    }

    /// A guarded module global's initialization flag; see `init_guard`.
    pub fn record_init_guard(
        &mut self,
        global: MangledName,
        flag: crate::codegen::init_guard::InitFlag,
    ) {
        self.init_guards.insert(global, flag);
    }

    pub fn record_class_declaration_flag(&mut self, index: usize, flag_idx: u32) {
        self.class_declaration_flags
            .entry(index)
            .or_default()
            .push(flag_idx);
    }

    /// Language globals retain their declared type for checked narrowed reads.
    /// Runtime metadata globals only need an index.
    pub fn record_typed_global(&mut self, mangled: MangledName, idx: u32, ty: Type) {
        self.global_types.insert(mangled.clone(), ty);
        self.record_global(mangled, idx);
    }

    /// Writes both the wasm function index and the static-call registry entry;
    /// splitting them invited callers to drop one half by accident.
    pub fn record_imported_fn(
        &mut self,
        mangled: MangledName,
        idx: u32,
        params: Vec<Type>,
        ret: Type,
        is_host: bool,
    ) {
        self.funcs.insert(mangled.clone(), idx);
        self.top_level_fns.insert(
            mangled,
            TopLevelFn {
                wasm_idx: idx,
                params,
                ret,
                is_host,
            },
        );
    }

    pub fn record_local_fn(
        &mut self,
        mangled: MangledName,
        idx: u32,
        params: Vec<Type>,
        ret: Type,
    ) -> Result<(), CompilerFailure> {
        // Guard against an accidental mangle/source-name swap.
        if !mangled.as_str().contains(crate::mangle::SEP) {
            return Err(internal_failure(format!(
                "local function `{}` has no mangled package prefix",
                mangled.as_str()
            )));
        }
        self.funcs.insert(mangled.clone(), idx);
        self.top_level_fns.insert(
            mangled,
            TopLevelFn {
                wasm_idx: idx,
                params,
                ret,
                is_host: false,
            },
        );
        Ok(())
    }

    pub fn top_level_fn(&self, mangled: &MangledName) -> Option<&TopLevelFn> {
        self.top_level_fns.get(mangled)
    }

    pub fn record_iface_dispatch(&mut self, iface: MangledName, dispatch: Dispatch) {
        self.iface_dispatch.insert(iface, dispatch);
    }

    pub fn record_static_value_tag(&mut self, iface: MangledName, tag: String) {
        self.static_value_tags.insert(iface, tag);
    }

    pub fn static_value_tag(&self, iface: &MangledName) -> Option<&str> {
        self.static_value_tags.get(iface).map(String::as_str)
    }

    pub fn iface_dispatch(&self, iface: &MangledName) -> Option<Dispatch> {
        self.iface_dispatch.get(iface).copied()
    }

    pub fn record_iface_method_abi(&mut self, method_key: MangledName, abi: MethodSlotAbi) {
        self.iface_method_abi.insert(method_key, abi);
    }

    pub fn iface_method_abi(&self, method_key: &MangledName) -> Option<&MethodSlotAbi> {
        self.iface_method_abi.get(method_key)
    }

    pub fn record_intrinsic_member(&mut self, mangled: MangledName) {
        self.intrinsic_members.insert(mangled);
    }

    pub fn is_intrinsic_member(&self, mangled: &MangledName) -> bool {
        self.intrinsic_members.contains(mangled)
    }

    pub fn value_type(&self, ty: &Type) -> Result<ValType, crate::compiler_error::CompilerFailure> {
        let ty = ty.peel();
        Ok(match ty {
            Type::Number | Type::NumberLiteral(_) => ValType::F64,
            Type::Boolean | Type::BooleanLiteral(_) => ValType::I32,
            Type::String | Type::StringLiteral(_) => {
                let idx = self.string_type_idx().ok_or_else(|| crate::codegen::internal_failure("Type::String requires the intrinsic types to be declared (declare_intrinsic_types)"))?;
                ValType::Ref(RefType {
                    nullable: false,
                    heap_type: HeapType::Concrete(idx),
                })
            }
            Type::BigInt | Type::BigIntLiteral(_) => {
                let idx = self.bigint_type_idx().ok_or_else(|| crate::codegen::internal_failure("Type::BigInt requires the intrinsic types to be declared (declare_intrinsic_types)"))?;
                ValType::Ref(RefType {
                    nullable: false,
                    heap_type: HeapType::Concrete(idx),
                })
            }
            Type::Object { .. } => {
                // All objects lower to `$ObjectShape` (not the arity-specific subtype):
                // sibling per-arity subtypes are not Wasm subtypes of each other, so
                // width subtyping and object-only unions require `$ObjectShape` as the
                // common supertype.
                let idx = self
                    .intrinsic_type_indices()
                    .ok_or_else(|| {
                        crate::codegen::internal_failure("intrinsics declared by codegen entry")
                    })?
                    .object_shape;
                ValType::Ref(RefType {
                    nullable: false,
                    heap_type: HeapType::Concrete(idx),
                })
            }
            Type::Array(_) => {
                let idx = self.array_type_idx().ok_or_else(|| crate::codegen::internal_failure("Type::Array requires the intrinsic types to be declared (declare_intrinsic_types)"))?;
                ValType::Ref(RefType {
                    nullable: false,
                    heap_type: HeapType::Concrete(idx),
                })
            }
            Type::Tuple(_) => {
                // Tuples lower to `$Array` — they are arrays at runtime; positional
                // element types are tracked by the typechecker only.
                let idx = self.array_type_idx().ok_or_else(|| crate::codegen::internal_failure("Type::Tuple requires the intrinsic types to be declared (declare_intrinsic_types)"))?;
                ValType::Ref(RefType {
                    nullable: false,
                    heap_type: HeapType::Concrete(idx),
                })
            }
            Type::Uint8Array => {
                let idx = self.uint8_array_type_idx().ok_or_else(|| crate::codegen::internal_failure("Type::Uint8Array requires the intrinsic types to be declared (declare_intrinsic_types)"))?;
                ValType::Ref(RefType {
                    nullable: false,
                    heap_type: HeapType::Concrete(idx),
                })
            }
            Type::TypeVar(_) | Type::GenericParam { .. } | Type::Unknown | Type::Void => {
                // Erased-generic and dynamic slots lower to nullable `(ref null $Object)`;
                // nullable so `null` literals can flow in via WasmGC subtyping.
                let object_idx = self
                    .intrinsic_type_indices()
                    .ok_or_else(|| {
                        crate::codegen::internal_failure("intrinsics declared by codegen entry")
                    })?
                    .object;
                ValType::Ref(RefType {
                    nullable: true,
                    heap_type: HeapType::Concrete(object_idx),
                })
            }
            Type::Function { .. } => {
                let sig = crate::codegen::closures::classify(ty)?;
                let idx = self.closure_struct_type_idx(sig).ok_or_else(|| {
                    crate::codegen::internal_failure(format!(
                        "closure signature {sig:?} is not registered"
                    ))
                })?;
                ValType::Ref(RefType {
                    nullable: false,
                    heap_type: HeapType::Concrete(idx),
                })
            }
            Type::Null => {
                let object_idx = self
                    .intrinsic_type_indices()
                    .ok_or_else(|| {
                        crate::codegen::internal_failure("intrinsics declared by codegen entry")
                    })?
                    .object;
                ValType::Ref(RefType {
                    nullable: true,
                    heap_type: HeapType::Concrete(object_idx),
                })
            }
            Type::Undefined => {
                let intrinsic = self.intrinsic_type_indices().ok_or_else(|| {
                    crate::codegen::internal_failure("undefined intrinsic is not declared")
                })?;
                ValType::Ref(RefType {
                    nullable: false,
                    heap_type: HeapType::Concrete(intrinsic.undefined),
                })
            }
            Type::Error => {
                // `Error` only follows a reported typecheck failure.
                return Err(crate::codegen::internal_failure(
                    "error cannot occupy a value slot",
                ));
            }
            Type::Never => {
                // The surrounding expression always diverges, but a `: never` function's
                // result slot still needs a concrete Wasm type for the validator. Share
                // the `Unknown` lowering — the call always throws before any value reaches
                // the slot.
                let object_idx = self
                    .intrinsic_type_indices()
                    .ok_or_else(|| {
                        crate::codegen::internal_failure("intrinsics declared by codegen entry")
                    })?
                    .object;
                ValType::Ref(RefType {
                    nullable: true,
                    heap_type: HeapType::Concrete(object_idx),
                })
            }
            Type::Union(members) => {
                let lowered: Vec<ValType> = members
                    .iter()
                    .map(|m| self.value_type(m))
                    .collect::<Result<_, _>>()?;
                let first_lowering = *lowered.first().ok_or_else(|| {
                    crate::codegen::internal_failure("Type::Union holds ≥2 members")
                })?;
                if lowered.iter().all(|&lowering| lowering == first_lowering) {
                    return Ok(first_lowering);
                }
                // Object-only union → `$ObjectShape`; mixed union → `$Object`.
                let all_object_or_null = members
                    .iter()
                    .all(|m| matches!(m.peel(), Type::Object { .. } | Type::Null));
                let heap_idx = if all_object_or_null {
                    self.intrinsic_type_indices()
                        .ok_or_else(|| {
                            crate::codegen::internal_failure("intrinsics declared by codegen entry")
                        })?
                        .object_shape
                } else {
                    self.intrinsic_type_indices()
                        .ok_or_else(|| {
                            crate::codegen::internal_failure("intrinsics declared by codegen entry")
                        })?
                        .object
                };
                // Nullable iff some member *lowers* nullable, not iff one is
                // spelled `null`: a `TypeVar`, `GenericParam`, `unknown`, or an
                // unrecorded `ClassRef` can hold null after instantiation
                // without naming it, and a non-null slot would trap the write.
                let nullable = lowered.iter().copied().any(is_nullable_ref)
                    || members
                        .iter()
                        .any(|member| matches!(member.peel(), Type::Undefined));
                ValType::Ref(RefType {
                    nullable,
                    heap_type: HeapType::Concrete(heap_idx),
                })
            }
            // ClassRef lowers to the universal `(ref null $Object)` in this
            // typecheck-only slice; the concrete `(ref $Foo)` lands with class
            // codegen (SUB-480).
            // A locally-known class lowers to its concrete `(ref $Foo)` (non-null);
            // `struct.new`/`struct.get`/`struct.set` need the concrete type. A class
            // not in this module's rec group (cross-package, SUB-488) falls back to
            // the universal `(ref null $Object)`.
            Type::ClassRef { mangled, .. } => match self.class_struct_type_idx(mangled) {
                Some(idx) => ValType::Ref(RefType {
                    nullable: false,
                    heap_type: HeapType::Concrete(idx),
                }),
                None => ValType::Ref(RefType {
                    nullable: true,
                    heap_type: HeapType::Concrete(
                        self.intrinsic_type_indices()
                            .ok_or_else(|| {
                                crate::codegen::internal_failure(
                                    "intrinsics declared by codegen entry",
                                )
                            })?
                            .object,
                    ),
                }),
            },
            Type::InterfaceRef { .. } => {
                let object_idx = self
                    .intrinsic_type_indices()
                    .ok_or_else(|| {
                        crate::codegen::internal_failure("intrinsics declared by codegen entry")
                    })?
                    .object;
                ValType::Ref(RefType {
                    nullable: true,
                    heap_type: HeapType::Concrete(object_idx),
                })
            }
            Type::AliasRef { .. } => {
                // A recursion back-edge's runtime value is a heap object
                // (object-shaped alias) or a boxed/erased union member —
                // both lower to the universal `(ref null $Object)`, the
                // same as `InterfaceRef`. The structural type is tracked
                // only at the typechecker layer.
                let object_idx = self
                    .intrinsic_type_indices()
                    .ok_or_else(|| {
                        crate::codegen::internal_failure("intrinsics declared by codegen entry")
                    })?
                    .object;
                ValType::Ref(RefType {
                    nullable: true,
                    heap_type: HeapType::Concrete(object_idx),
                })
            }
            Type::NumberEnum { .. } => {
                let idx = self.boxed_number_type_idx().ok_or_else(|| {
                    crate::codegen::internal_failure(
                        "Type::NumberEnum requires the intrinsic types to be declared",
                    )
                })?;
                ValType::Ref(RefType {
                    nullable: false,
                    heap_type: HeapType::Concrete(idx),
                })
            }
            Type::StringEnum { .. } => {
                let idx = self.string_type_idx().ok_or_else(|| {
                    crate::codegen::internal_failure(
                        "Type::StringEnum requires the intrinsic types to be declared",
                    )
                })?;
                ValType::Ref(RefType {
                    nullable: false,
                    heap_type: HeapType::Concrete(idx),
                })
            }
            Type::Alias { .. } | Type::Refined { .. } | Type::Readonly(_) => {
                return Err(crate::codegen::internal_failure(
                    "unpeeled alias in value type lowering",
                ));
            }
        })
    }

    pub fn wasm_result(
        &self,
        ty: &Type,
    ) -> Result<Vec<ValType>, crate::compiler_error::CompilerFailure> {
        Ok(vec![self.value_type(ty)?])
    }

    /// Wasm value type of a class-method **vtable-slot** parameter or result,
    /// of a **constructor** parameter, or of a **box cell**'s payload.
    ///
    /// These slots erase every class type and type variable to the boxed
    /// object slot. [`value_type`](Self::value_type) cannot serve here because
    /// its `ClassRef` lowering is phase-dependent: it yields the concrete
    /// struct once that struct type is recorded, and imported classes are
    /// reconstructed *before* local slot signatures are built while local
    /// classes are reserved *after* — so one declaration would lower two ways.
    /// Erasing unconditionally keeps a slot's ABI stable across phases and
    /// identical between a producer and a cross-package consumer, and keeps it
    /// in step with the types recorded for each slot ([`MethodSlotAbi`] for a
    /// method, `class_ctor_abi` for a constructor).
    pub fn slot_value_type(
        &self,
        ty: &Type,
    ) -> Result<ValType, crate::compiler_error::CompilerFailure> {
        if is_erased(ty) {
            let object = self
                .intrinsic_type_indices()
                .ok_or_else(|| {
                    crate::codegen::internal_failure(
                        "intrinsics declared before class slot signatures",
                    )
                })?
                .object;
            return Ok(ValType::Ref(RefType {
                nullable: true,
                heap_type: HeapType::Concrete(object),
            }));
        }
        self.value_type(ty)
    }

    pub fn slot_wasm_result(
        &self,
        ty: &Type,
    ) -> Result<Vec<ValType>, crate::compiler_error::CompilerFailure> {
        Ok(vec![self.slot_value_type(ty)?])
    }

    pub fn host_value_type(
        &self,
        ty: &Type,
    ) -> Result<ValType, crate::compiler_error::CompilerFailure> {
        if matches!(ty, Type::String | Type::StringLiteral(_)) {
            let idx = self.raw_string_type_idx().ok_or_else(|| crate::codegen::internal_failure("Type::String requires the intrinsic types to be declared (declare_intrinsic_types)"))?;
            return Ok(ValType::Ref(RefType {
                nullable: false,
                heap_type: HeapType::Concrete(idx),
            }));
        }
        if matches!(ty, Type::Uint8Array) {
            let idx = self.raw_uint8_array_type_idx().ok_or_else(|| crate::codegen::internal_failure("Type::Uint8Array requires the intrinsic types to be declared (declare_intrinsic_types)"))?;
            return Ok(ValType::Ref(RefType {
                nullable: false,
                heap_type: HeapType::Concrete(idx),
            }));
        }
        self.value_type(ty)
    }
}

/// Names of a validator key's type arguments when every one is a generic
/// parameter, so one validator serves each instantiation.
fn generic_parameter_names(args: &[Type]) -> Option<Vec<String>> {
    if args.is_empty() {
        return None;
    }
    args.iter()
        .map(|arg| match arg {
            Type::TypeVar(name) => Some(name.clone()),
            _ => None,
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn func_idx_round_trip_across_name_shapes() {
        let mut map = SymbolTable::default();
        map.record_local_fn(
            crate::mangle::package_symbol("main", "main"),
            10,
            Vec::new(),
            Type::Void,
        )
        .unwrap();
        let unmangled: MangledName = serde_json::from_str("\"main\"").unwrap();
        assert!(
            map.record_local_fn(unmangled.clone(), 13, Vec::new(), Type::Void)
                .is_err()
        );
        assert_eq!(map.func_idx(&unmangled), None);
        map.record_imported_fn(
            crate::mangle::prelude("string_concat"),
            11,
            vec![Type::String, Type::String],
            Type::String,
            false,
        );
        map.record_func(
            crate::mangle::extend(&crate::mangle::prelude("Number"), "toString"),
            12,
        );

        assert_eq!(
            map.func_idx(&crate::mangle::package_symbol("main", "main")),
            Some(10)
        );
        assert_eq!(map.prelude_func_idx("string_concat"), Some(11));
        assert_eq!(
            map.func_idx(&crate::mangle::extend(
                &crate::mangle::prelude("Number"),
                "toString",
            )),
            Some(12),
        );

        assert_eq!(
            map.func_idx(&crate::mangle::package_symbol("main", "string_concat")),
            None,
        );
        assert_eq!(map.prelude_func_idx("toString"), None);
    }
}