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
//! Host-side declaration of the canonical intrinsic WasmGC rec group.
//!
//! [`build_intrinsic_types`] declares the same types as
//! [`crate::codegen::intrinsics::declare_intrinsic_types`] (the bytes every
//! Submilli module emits), but via wasmtime's `RecGroupBuilder` rather than
//! recovering them from a compiled module. WasmGC structural canonicalization
//! makes the resulting `StructType`/`ArrayType`/`FuncType` handles share the
//! engine type-index the modules use, so a host-built `$string` flows into a
//! guest `(ref $string)` slot without trapping.
//!
//! The grouping must mirror `declare_intrinsic_types` exactly: one
//! `RecGroupBuilder::build()` per rec group — the 14-member `$Object`/`$VTable`
//! group, the self-referential `(rec $ClassVTable)` singleton, the 2-member
//! `(rec $Error_vtable $Error)` pair, plus one singleton per standalone array /
//! `$Object` subtype. Lumping them into one builder would form a different rec
//! group and canonicalize to different indices. The
//! `intrinsic_types_match_codegen` test pins this core mirror to the first 32
//! codegen types. Map, Set, and host backing mirrors are rebuilt by their owning
//! runtime modules from the same canonical layouts.

use std::sync::Arc;

use wasmtime::{
    ArrayType, AsContextMut, Engine, FieldType, Finality, FuncType, Mutability, RecGroupBuilder,
    RefType, StorageType, StructType, ValType,
};

use crate::runtime::StoreData;
use crate::runtime::gc_singleton::{singleton_array, singleton_struct};

/// Canonical handles for the intrinsic types, in `IntrinsicTypeIndices` order.
/// Most fields are unused today; #1 (host-owned vtables) and later per-type ports
/// consume the rest, and the guard test reads every one.
#[allow(dead_code)]
#[derive(Clone)]
pub(crate) struct IntrinsicTypes {
    pub undefined: StructType,
    pub raw_string: ArrayType,
    pub vtable: StructType,
    pub object: StructType,
    pub string: StructType,
    pub boxed_number: StructType,
    pub boxed_boolean: StructType,
    pub field_names: ArrayType,
    pub object_fields: ArrayType,
    pub object_shape: StructType,
    pub to_string_fn: FuncType,
    pub to_json_fn: FuncType,
    pub equals_fn: FuncType,
    pub hash_fn: FuncType,
    pub field_getter: FuncType,
    pub field_setter: FuncType,
    pub raw_array: ArrayType,
    pub array: StructType,
    pub raw_uint8_array: ArrayType,
    pub uint8_array: StructType,
    pub closure: StructType,
    pub class_vtable: StructType,
    pub error_vtable: StructType,
    pub error: StructType,
    pub raw_bigint: ArrayType,
    pub bigint: StructType,
    pub regex_capture_array: ArrayType,
    pub regex_match: StructType,
    pub regex: StructType,
    pub regex_match_box: StructType,
    pub temporal_instant: StructType,
    pub temporal_duration: StructType,
    pub temporal_zdt: StructType,
}

/// The intrinsic types for `store`'s engine. Building them interns every rec
/// group with the engine, which costs far more than the host call that needs
/// them, so a store builds them once and its host functions share the result.
pub(crate) fn intrinsic_types(
    mut store: impl AsContextMut<Data = StoreData>,
) -> wasmtime::Result<Arc<IntrinsicTypes>> {
    let mut ctx = store.as_context_mut();
    if let Some(types) = &ctx.data().intrinsic_types {
        return Ok(Arc::clone(types));
    }
    let types = Arc::new(build_intrinsic_types(ctx.engine())?);
    ctx.data_mut().intrinsic_types = Some(Arc::clone(&types));
    Ok(types)
}

/// Build the full intrinsic type set against `engine`, mirroring
/// `declare_intrinsic_types` group-by-group.
pub(crate) fn build_intrinsic_types(engine: &Engine) -> wasmtime::Result<IntrinsicTypes> {
    use Finality::{Final, NonFinal};
    let imm = Mutability::Const;
    let mutv = Mutability::Var;

    // $rawString — standalone `(array (mut i16))`.
    let raw_string = singleton_array(engine, Final, FieldType::new(mutv, StorageType::I16))?;

    // The closed `$Object`/`$VTable` cycle, emitted as one 14-member rec group.
    // Declare every label first so forward references (VTable -> method fn types,
    // field_names -> $string, …) resolve. Member order must match index order 1..14.
    let mut b = RecGroupBuilder::new(engine);
    let vtable = b.declare_struct();
    let object = b.declare_struct();
    let string = b.declare_struct();
    let boxed_number = b.declare_struct();
    let boxed_boolean = b.declare_struct();
    let field_names = b.declare_array();
    let object_fields = b.declare_array();
    let object_shape = b.declare_struct();
    let to_string_fn = b.declare_func();
    let to_json_fn = b.declare_func();
    let equals_fn = b.declare_func();
    let hash_fn = b.declare_func();
    let field_getter = b.declare_func();
    let field_setter = b.declare_func();

    let mut def = b.define_struct(vtable);
    def.finality(NonFinal);
    def.forward_ref_field(to_string_fn)
        .mutability(imm)
        .nullable(false)
        .finish();
    def.forward_ref_field(to_json_fn)
        .mutability(imm)
        .nullable(false)
        .finish();
    def.forward_ref_field(equals_fn)
        .mutability(imm)
        .nullable(false)
        .finish();
    def.forward_ref_field(hash_fn)
        .mutability(imm)
        .nullable(false)
        .finish();
    def.finish();

    let mut def = b.define_struct(object);
    def.finality(NonFinal);
    def.forward_ref_field(vtable)
        .mutability(imm)
        .nullable(false)
        .finish();
    def.finish();

    // `$string`'s payload is the already-built standalone `$rawString` (a concrete
    // cross-group ref), matching how the module references type index 0.
    let mut def = b.define_struct(string);
    def.finality(NonFinal);
    def.forward_supertype(object);
    def.forward_ref_field(vtable)
        .mutability(imm)
        .nullable(false)
        .finish();
    def.field(FieldType::new(
        imm,
        StorageType::ValType(ValType::Ref(RefType::new(false, raw_string.clone().into()))),
    ));
    // Zero means not hashed; nonzero stores the unsigned 32-bit hash plus one.
    def.field(FieldType::new(
        Mutability::Var,
        StorageType::ValType(ValType::I64),
    ));
    def.finish();

    let mut def = b.define_struct(boxed_number);
    def.finality(NonFinal);
    def.forward_supertype(object);
    def.forward_ref_field(vtable)
        .mutability(imm)
        .nullable(false)
        .finish();
    def.field(FieldType::new(imm, StorageType::ValType(ValType::F64)));
    def.finish();

    let mut def = b.define_struct(boxed_boolean);
    def.finality(NonFinal);
    def.forward_supertype(object);
    def.forward_ref_field(vtable)
        .mutability(imm)
        .nullable(false)
        .finish();
    def.field(FieldType::new(imm, StorageType::ValType(ValType::I32)));
    def.finish();

    let mut def = b.define_array(field_names);
    def.finality(NonFinal);
    def.forward_ref_element(string)
        .mutability(mutv)
        .nullable(false)
        .finish();
    def.finish();

    let mut def = b.define_array(object_fields);
    def.finality(NonFinal);
    def.forward_ref_element(object)
        .mutability(mutv)
        .nullable(true)
        .finish();
    def.finish();

    let mut def = b.define_struct(object_shape);
    def.finality(NonFinal);
    def.forward_supertype(object);
    def.forward_ref_field(vtable)
        .mutability(imm)
        .nullable(false)
        .finish();
    def.forward_ref_field(field_names)
        .mutability(mutv)
        .nullable(false)
        .finish();
    def.forward_ref_field(object_fields)
        .mutability(mutv)
        .nullable(false)
        .finish();
    def.field(FieldType::new(
        mutv,
        StorageType::ValType(ValType::Ref(RefType::ANYREF)),
    ));
    def.finish();

    let mut def = b.define_func(to_string_fn);
    def.finality(NonFinal);
    def.forward_ref_param(object).nullable(false).finish();
    def.forward_ref_result(string).nullable(false).finish();
    def.finish();

    let mut def = b.define_func(to_json_fn);
    def.finality(NonFinal);
    def.forward_ref_param(object).nullable(false).finish();
    def.forward_ref_result(string).nullable(false).finish();
    def.finish();

    let mut def = b.define_func(equals_fn);
    def.finality(NonFinal);
    def.forward_ref_param(object).nullable(false).finish();
    def.forward_ref_param(object).nullable(false).finish();
    def.result(ValType::I32);
    def.finish();

    let mut def = b.define_func(hash_fn);
    def.finality(NonFinal);
    def.forward_ref_param(object).nullable(false).finish();
    def.result(ValType::I32);
    def.finish();

    let mut def = b.define_func(field_getter);
    def.finality(NonFinal);
    def.forward_ref_param(object_shape).nullable(false).finish();
    def.forward_ref_param(string).nullable(false).finish();
    def.forward_ref_result(object).nullable(true).finish();
    def.finish();

    let mut def = b.define_func(field_setter);
    def.finality(NonFinal);
    def.forward_ref_param(object_shape).nullable(false).finish();
    def.forward_ref_param(string).nullable(false).finish();
    def.forward_ref_param(object).nullable(true).finish();
    def.finish();

    // Each lookup uses this builder's handle and declared kind. A successful
    // build preserves both, and no mutation occurs before lookup.
    let g = b.build().map_err(crate::runtime::host::fatal_host_error)?;
    let vtable = g
        .get_struct(vtable)
        .expect("vtable was declared as a struct");
    let object = g
        .get_struct(object)
        .expect("object was declared as a struct");
    let string = g
        .get_struct(string)
        .expect("string was declared as a struct");
    let boxed_number = g
        .get_struct(boxed_number)
        .expect("boxed_number was declared as a struct");
    let boxed_boolean = g
        .get_struct(boxed_boolean)
        .expect("boxed_boolean was declared as a struct");
    let field_names = g
        .get_array(field_names)
        .expect("field_names was declared as an array");
    let object_fields = g
        .get_array(object_fields)
        .expect("object_fields was declared as an array");
    let object_shape = g
        .get_struct(object_shape)
        .expect("object_shape was declared as a struct");
    let to_string_fn = g
        .get_func(to_string_fn)
        .expect("to_string_fn was declared as a func");
    let to_json_fn = g
        .get_func(to_json_fn)
        .expect("to_json_fn was declared as a func");
    let equals_fn = g
        .get_func(equals_fn)
        .expect("equals_fn was declared as a func");
    let hash_fn = g.get_func(hash_fn).expect("hash_fn was declared as a func");
    let field_getter = g
        .get_func(field_getter)
        .expect("field_getter was declared as a func");
    let field_setter = g
        .get_func(field_setter)
        .expect("field_setter was declared as a func");

    // Standalone types, each its own rec group. Built after the main group so they
    // can reference `$Object`/`$VTable`/`$string`/`$rawString` as concrete handles.
    let raw_array = singleton_array(
        engine,
        Final,
        FieldType::new(
            mutv,
            StorageType::ValType(ValType::Ref(RefType::new(true, object.clone().into()))),
        ),
    )?;
    let array = singleton_struct(
        engine,
        NonFinal,
        Some(object.clone()),
        vec![
            FieldType::new(
                imm,
                StorageType::ValType(ValType::Ref(RefType::new(false, vtable.clone().into()))),
            ),
            FieldType::new(
                mutv,
                StorageType::ValType(ValType::Ref(RefType::new(false, raw_array.clone().into()))),
            ),
            FieldType::new(mutv, StorageType::ValType(ValType::I32)),
        ],
    )?;
    let raw_uint8_array = singleton_array(engine, Final, FieldType::new(mutv, StorageType::I8))?;
    let uint8_array = singleton_struct(
        engine,
        NonFinal,
        Some(object.clone()),
        vec![
            FieldType::new(
                imm,
                StorageType::ValType(ValType::Ref(RefType::new(false, vtable.clone().into()))),
            ),
            FieldType::new(
                imm,
                StorageType::ValType(ValType::Ref(RefType::new(
                    false,
                    raw_uint8_array.clone().into(),
                ))),
            ),
        ],
    )?;
    let closure = singleton_struct(
        engine,
        NonFinal,
        Some(object.clone()),
        vec![FieldType::new(
            imm,
            StorageType::ValType(ValType::Ref(RefType::new(false, vtable.clone().into()))),
        )],
    )?;

    // `(rec $ClassVTable)` — the class-only vtable base: the 4 universal slots
    // plus the nominal-identity parent link and default-JSON marker, its own singleton
    // rec group (mirrors `declare_intrinsic_types`).
    let mut b = RecGroupBuilder::new(engine);
    let class_vtable_label = b.declare_struct();
    let mut def = b.define_struct(class_vtable_label);
    def.finality(NonFinal);
    def.supertype(vtable.clone());
    for slot_fn in [&to_string_fn, &to_json_fn, &equals_fn, &hash_fn] {
        def.field(FieldType::new(
            imm,
            StorageType::ValType(ValType::Ref(RefType::new(false, slot_fn.clone().into()))),
        ));
    }
    def.forward_ref_field(class_vtable_label)
        .mutability(imm)
        .nullable(true)
        .finish();
    def.field(FieldType::new(imm, StorageType::ValType(ValType::I32)));
    def.finish();
    // Each lookup uses this builder's handle and declared kind. A successful
    // build preserves both, and no mutation occurs before lookup.
    let g = b.build().map_err(crate::runtime::host::fatal_host_error)?;
    let class_vtable = g
        .get_struct(class_vtable_label)
        .expect("class_vtable was declared as a struct");

    // `(rec $Error_vtable $Error)` — the class-shaped pair, one 2-member rec
    // group mirroring the user-class emitter's output (`classes.rs`): the vtable
    // is the `$ClassVTable` prefix (universal slots + parent link + default-JSON marker, no methods);
    // the struct has the 4 `$ObjectShape` header slots and an identity ID;
    // named fields remain in the object-fields payload.
    let mut b = RecGroupBuilder::new(engine);
    let error_vtable_label = b.declare_struct();
    let error_label = b.declare_struct();

    let mut def = b.define_struct(error_vtable_label);
    def.finality(NonFinal);
    def.supertype(class_vtable.clone());
    for slot_fn in [&to_string_fn, &to_json_fn, &equals_fn, &hash_fn] {
        def.field(FieldType::new(
            imm,
            StorageType::ValType(ValType::Ref(RefType::new(false, slot_fn.clone().into()))),
        ));
    }
    def.field(FieldType::new(
        imm,
        StorageType::ValType(ValType::Ref(RefType::new(
            true,
            class_vtable.clone().into(),
        ))),
    ));
    def.field(FieldType::new(imm, StorageType::ValType(ValType::I32)));
    def.finish();

    let mut def = b.define_struct(error_label);
    def.finality(NonFinal);
    def.supertype(object_shape.clone());
    def.forward_ref_field(error_vtable_label)
        .mutability(imm)
        .nullable(false)
        .finish();
    def.field(FieldType::new(
        mutv,
        StorageType::ValType(ValType::Ref(RefType::new(
            false,
            field_names.clone().into(),
        ))),
    ));
    def.field(FieldType::new(
        mutv,
        StorageType::ValType(ValType::Ref(RefType::new(
            false,
            object_fields.clone().into(),
        ))),
    ));
    def.field(FieldType::new(
        mutv,
        StorageType::ValType(ValType::Ref(RefType::ANYREF)),
    ));
    def.field(FieldType::new(mutv, StorageType::ValType(ValType::I64)));
    def.finish();

    // Each lookup uses this builder's handle and declared kind. A successful
    // build preserves both, and no mutation occurs before lookup.
    let g = b.build().map_err(crate::runtime::host::fatal_host_error)?;
    let error_vtable = g
        .get_struct(error_vtable_label)
        .expect("error_vtable was declared as a struct");
    let error = g
        .get_struct(error_label)
        .expect("error was declared as a struct");

    let raw_bigint = singleton_array(
        engine,
        Final,
        FieldType::new(mutv, StorageType::ValType(ValType::I64)),
    )?;
    let bigint = singleton_struct(
        engine,
        NonFinal,
        Some(object.clone()),
        vec![
            FieldType::new(
                imm,
                StorageType::ValType(ValType::Ref(RefType::new(false, vtable.clone().into()))),
            ),
            FieldType::new(imm, StorageType::ValType(ValType::I32)),
            FieldType::new(
                imm,
                StorageType::ValType(ValType::Ref(RefType::new(false, raw_bigint.clone().into()))),
            ),
        ],
    )?;

    let regex_capture_array = singleton_array(
        engine,
        Final,
        FieldType::new(
            mutv,
            StorageType::ValType(ValType::Ref(RefType::new(true, raw_string.clone().into()))),
        ),
    )?;
    let regex_match = singleton_struct(
        engine,
        Final,
        None::<StructType>,
        vec![
            FieldType::new(
                imm,
                StorageType::ValType(ValType::Ref(RefType::new(false, raw_string.clone().into()))),
            ),
            FieldType::new(imm, StorageType::ValType(ValType::I32)),
            FieldType::new(
                imm,
                StorageType::ValType(ValType::Ref(RefType::new(false, raw_string.clone().into()))),
            ),
            FieldType::new(
                imm,
                StorageType::ValType(ValType::Ref(RefType::new(
                    false,
                    regex_capture_array.clone().into(),
                ))),
            ),
            FieldType::new(
                imm,
                StorageType::ValType(ValType::Ref(RefType::new(
                    false,
                    regex_capture_array.clone().into(),
                ))),
            ),
            FieldType::new(imm, StorageType::ValType(ValType::I32)),
        ],
    )?;
    let regex = singleton_struct(
        engine,
        NonFinal,
        Some(object.clone()),
        vec![
            FieldType::new(
                imm,
                StorageType::ValType(ValType::Ref(RefType::new(false, vtable.clone().into()))),
            ),
            FieldType::new(imm, StorageType::ValType(ValType::EXTERNREF)),
            FieldType::new(mutv, StorageType::ValType(ValType::I32)),
            FieldType::new(
                imm,
                StorageType::ValType(ValType::Ref(RefType::new(false, string.clone().into()))),
            ),
            FieldType::new(
                imm,
                StorageType::ValType(ValType::Ref(RefType::new(false, string.clone().into()))),
            ),
            FieldType::new(imm, StorageType::ValType(ValType::I32)),
            FieldType::new(mutv, StorageType::ValType(ValType::I64)),
        ],
    )?;
    let regex_match_box = singleton_struct(
        engine,
        NonFinal,
        Some(object.clone()),
        vec![
            FieldType::new(
                imm,
                StorageType::ValType(ValType::Ref(RefType::new(false, vtable.clone().into()))),
            ),
            FieldType::new(
                imm,
                StorageType::ValType(ValType::Ref(RefType::new(false, string.clone().into()))),
            ),
            FieldType::new(imm, StorageType::ValType(ValType::I32)),
            FieldType::new(
                imm,
                StorageType::ValType(ValType::Ref(RefType::new(false, string.clone().into()))),
            ),
            FieldType::new(
                imm,
                StorageType::ValType(ValType::Ref(RefType::new(
                    false,
                    regex_capture_array.clone().into(),
                ))),
            ),
            FieldType::new(
                imm,
                StorageType::ValType(ValType::Ref(RefType::new(
                    false,
                    regex_capture_array.clone().into(),
                ))),
            ),
            FieldType::new(mutv, StorageType::ValType(ValType::I64)),
        ],
    )?;

    let temporal_instant = singleton_struct(
        engine,
        NonFinal,
        Some(object.clone()),
        vec![
            FieldType::new(
                imm,
                StorageType::ValType(ValType::Ref(RefType::new(false, vtable.clone().into()))),
            ),
            FieldType::new(imm, StorageType::ValType(ValType::I64)),
            FieldType::new(imm, StorageType::ValType(ValType::I32)),
        ],
    )?;
    let temporal_duration = singleton_struct(
        engine,
        NonFinal,
        Some(object.clone()),
        vec![
            FieldType::new(
                imm,
                StorageType::ValType(ValType::Ref(RefType::new(false, vtable.clone().into()))),
            ),
            FieldType::new(imm, StorageType::ValType(ValType::I32)),
            FieldType::new(imm, StorageType::ValType(ValType::I32)),
            FieldType::new(imm, StorageType::ValType(ValType::I32)),
            FieldType::new(imm, StorageType::ValType(ValType::I32)),
            FieldType::new(imm, StorageType::ValType(ValType::I64)),
            FieldType::new(imm, StorageType::ValType(ValType::I64)),
            FieldType::new(imm, StorageType::ValType(ValType::I64)),
            FieldType::new(imm, StorageType::ValType(ValType::I64)),
            FieldType::new(imm, StorageType::ValType(ValType::I64)),
            FieldType::new(imm, StorageType::ValType(ValType::I64)),
        ],
    )?;
    let temporal_zdt = singleton_struct(
        engine,
        NonFinal,
        Some(object.clone()),
        vec![
            FieldType::new(
                imm,
                StorageType::ValType(ValType::Ref(RefType::new(false, vtable.clone().into()))),
            ),
            FieldType::new(imm, StorageType::ValType(ValType::I64)),
            FieldType::new(imm, StorageType::ValType(ValType::I32)),
            FieldType::new(
                imm,
                StorageType::ValType(ValType::Ref(RefType::new(false, string.clone().into()))),
            ),
            FieldType::new(
                imm,
                StorageType::ValType(ValType::Ref(RefType::new(
                    false,
                    wasmtime::HeapType::Extern,
                ))),
            ),
        ],
    )?;

    let undefined = singleton_struct(
        engine,
        Final,
        Some(object.clone()),
        vec![
            FieldType::new(
                imm,
                StorageType::ValType(ValType::Ref(RefType::new(false, vtable.clone().into()))),
            ),
            FieldType::new(imm, StorageType::ValType(ValType::I64)),
        ],
    )?;

    Ok(IntrinsicTypes {
        undefined,
        raw_string,
        vtable,
        object,
        string,
        boxed_number,
        boxed_boolean,
        field_names,
        object_fields,
        object_shape,
        to_string_fn,
        to_json_fn,
        equals_fn,
        hash_fn,
        field_getter,
        field_setter,
        raw_array,
        array,
        raw_uint8_array,
        uint8_array,
        closure,
        class_vtable,
        error_vtable,
        error,
        raw_bigint,
        bigint,
        regex_capture_array,
        regex_match,
        regex,
        regex_match_box,
        temporal_instant,
        temporal_duration,
        temporal_zdt,
    })
}

pub(crate) fn intrinsic_string_type(engine: &Engine) -> wasmtime::Result<StructType> {
    Ok(build_intrinsic_types(engine)?.string)
}

pub(crate) fn intrinsic_uint8_array_type(engine: &Engine) -> wasmtime::Result<StructType> {
    Ok(build_intrinsic_types(engine)?.uint8_array)
}

pub(crate) fn intrinsic_array_type(engine: &Engine) -> wasmtime::Result<StructType> {
    Ok(build_intrinsic_types(engine)?.array)
}

pub(crate) fn intrinsic_bigint_type(engine: &Engine) -> wasmtime::Result<StructType> {
    Ok(build_intrinsic_types(engine)?.bigint)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::codegen::intrinsics::declare_intrinsic_types;
    use wasm_encoder::{
        ConstExpr, ExportKind, ExportSection, GlobalSection, GlobalType, HeapType, Module, RefType,
        TypeSection, ValType as EncValType,
    };
    use wasmtime::Config;

    /// A module that declares the intrinsics and exports `t{idx}` as a nullable
    /// global referencing each type, so the compiled module's canonical handles
    /// can be read back. This is the old type-witness pattern, kept in the test
    /// and generalized from 4 globals to all 30.
    fn witness_module_bytes() -> Vec<u8> {
        let mut module = Module::new();
        let mut types = TypeSection::new();
        let _ = declare_intrinsic_types(&mut types);
        module.section(&types);

        let mut globals = GlobalSection::new();
        let mut exports = ExportSection::new();
        for idx in 0..crate::codegen::intrinsics::INTRINSIC_TYPE_COUNT {
            globals.global(
                GlobalType {
                    val_type: EncValType::Ref(RefType {
                        nullable: true,
                        heap_type: HeapType::Concrete(idx),
                    }),
                    mutable: false,
                    shared: false,
                },
                &ConstExpr::ref_null(HeapType::Concrete(idx)),
            );
            exports.export(&format!("t{idx}"), ExportKind::Global, idx);
        }
        module.section(&globals);
        module.section(&exports);
        module.finish()
    }

    #[test]
    fn intrinsic_types_match_codegen() {
        let mut config = Config::new();
        config.wasm_gc(true);
        config.wasm_function_references(true);
        let engine = Engine::new(&config).unwrap();

        let intr = build_intrinsic_types(&engine).unwrap();
        let module = wasmtime::Module::new(&engine, witness_module_bytes()).unwrap();

        let heap = |idx: u32| {
            module
                .get_export(&format!("t{idx}"))
                .unwrap()
                .global()
                .unwrap()
                .content()
                .as_ref()
                .map(|r| r.heap_type().clone())
                .unwrap()
        };
        let recovered_struct = |idx: u32| heap(idx).as_concrete_struct().unwrap().clone();
        let recovered_array = |idx: u32| heap(idx).as_concrete_array().unwrap().clone();
        let recovered_func = |idx: u32| heap(idx).as_concrete_func().unwrap().clone();

        // (idx, host handle) for every intrinsic, asserted equal to the canonical
        // type the compiled module uses. `eq` compares engine type-indices, so a
        // pass proves the host built the *same* canonical type, not just a look-alike.
        assert!(ArrayType::eq(&intr.raw_string, &recovered_array(0)));
        assert!(StructType::eq(&intr.vtable, &recovered_struct(1)));
        assert!(StructType::eq(&intr.object, &recovered_struct(2)));
        assert!(StructType::eq(&intr.string, &recovered_struct(3)));
        assert!(StructType::eq(&intr.boxed_number, &recovered_struct(4)));
        assert!(StructType::eq(&intr.boxed_boolean, &recovered_struct(5)));
        assert!(StructType::eq(&intr.undefined, &recovered_struct(51)));
        assert!(!StructType::eq(&intr.undefined, &intr.object));
        assert!(!StructType::eq(&intr.undefined, &intr.boxed_boolean));
        assert!(ArrayType::eq(&intr.field_names, &recovered_array(6)));
        assert!(ArrayType::eq(&intr.object_fields, &recovered_array(7)));
        assert!(StructType::eq(&intr.object_shape, &recovered_struct(8)));
        assert!(FuncType::eq(&intr.to_string_fn, &recovered_func(9)));
        assert!(FuncType::eq(&intr.to_json_fn, &recovered_func(10)));
        assert!(FuncType::eq(&intr.equals_fn, &recovered_func(11)));
        assert!(FuncType::eq(&intr.hash_fn, &recovered_func(12)));
        assert!(FuncType::eq(&intr.field_getter, &recovered_func(13)));
        assert!(FuncType::eq(&intr.field_setter, &recovered_func(14)));
        assert!(ArrayType::eq(&intr.raw_array, &recovered_array(15)));
        assert!(StructType::eq(&intr.array, &recovered_struct(16)));
        assert!(ArrayType::eq(&intr.raw_uint8_array, &recovered_array(17)));
        assert!(StructType::eq(&intr.uint8_array, &recovered_struct(18)));
        assert!(StructType::eq(&intr.closure, &recovered_struct(19)));
        assert!(StructType::eq(&intr.class_vtable, &recovered_struct(20)));
        assert!(StructType::eq(&intr.error_vtable, &recovered_struct(21)));
        assert!(StructType::eq(&intr.error, &recovered_struct(22)));
        assert!(ArrayType::eq(&intr.raw_bigint, &recovered_array(23)));
        assert!(StructType::eq(&intr.bigint, &recovered_struct(24)));
        assert!(ArrayType::eq(
            &intr.regex_capture_array,
            &recovered_array(25)
        ));
        assert!(StructType::eq(&intr.regex_match, &recovered_struct(26)));
        assert!(StructType::eq(&intr.regex, &recovered_struct(27)));
        assert!(StructType::eq(&intr.regex_match_box, &recovered_struct(28)));
        assert!(StructType::eq(
            &intr.temporal_instant,
            &recovered_struct(29)
        ));
        assert!(StructType::eq(
            &intr.temporal_duration,
            &recovered_struct(30)
        ));
        assert!(StructType::eq(&intr.temporal_zdt, &recovered_struct(31)));
    }
}