shape-jit 0.3.1

Tiered JIT compiler (Cranelift) for the Shape virtual machine
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
//! Inline typed struct field access for the v2 runtime.
//!
//! Generates Cranelift IR for O(1) typed struct field reads and writes using
//! compile-time constant offsets.  No schema lookup, no HashMap, no FFI call.
//!
//! # v2 Struct Memory Layout
//!
//! ```text
//! offset 0..8   HeapHeader  (refcount u32 @ 0, kind u16 @ 4, flags u8 @ 6, _pad u8 @ 7)
//! offset 8..    fields in declaration order, naturally aligned
//! ```
//!
//! For `type Point { x: number, y: number }`:
//!
//! ```text
//! [0..8)   HeapHeader
//! [8..16)  x: f64
//! [16..24) y: f64
//! ```
//!
//! `point.x` compiles to a single `load f64 [ptr + 8]`.

use cranelift::codegen::ir::FuncRef;
use cranelift::prelude::*;
use shape_vm::type_tracking::NativeKind;

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

/// Size of the v2 HeapHeader in bytes.
///
/// Layout: refcount(u32) + kind(u16) + flags(u8) + _pad(u8) = 8 bytes.
pub const V2_HEAP_HEADER_SIZE: u32 = 8;

/// Byte offset of the refcount field (u32) within the HeapHeader.
pub const V2_HEADER_REFCOUNT_OFFSET: u32 = 0;

/// Byte offset of the kind field (u16) within the HeapHeader.
pub const V2_HEADER_KIND_OFFSET: u32 = 4;

/// Byte offset of the flags field (u8) within the HeapHeader.
pub const V2_HEADER_FLAGS_OFFSET: u32 = 6;

// ---------------------------------------------------------------------------
// NativeKind -> Cranelift type mapping
// ---------------------------------------------------------------------------

/// Map a `NativeKind` to the corresponding Cranelift IR type.
///
/// This determines the load/store width for a given field type.
pub fn cranelift_type_for_slot(kind: NativeKind) -> types::Type {
    match kind {
        NativeKind::Float64 | NativeKind::NullableFloat64 => types::F64,

        NativeKind::Int64 | NativeKind::NullableInt64 | NativeKind::UInt64 | NativeKind::NullableUInt64 => {
            types::I64
        }

        NativeKind::Int32 | NativeKind::NullableInt32 | NativeKind::UInt32 | NativeKind::NullableUInt32 => {
            types::I32
        }

        NativeKind::Int16 | NativeKind::NullableInt16 | NativeKind::UInt16 | NativeKind::NullableUInt16 => {
            types::I16
        }

        NativeKind::Int8
        | NativeKind::NullableInt8
        | NativeKind::UInt8
        | NativeKind::NullableUInt8
        | NativeKind::Bool => types::I8,

        NativeKind::IntSize
        | NativeKind::NullableIntSize
        | NativeKind::UIntSize
        | NativeKind::NullableUIntSize => types::I64, // pointer-width

        // Round 19 S1.5 W12-nativekind-scalar-additions (2026-05-14):
        // ADR-006 §2.7.5 amendment — F32 is 4-byte IEEE-754 single-
        // precision (Cranelift `F32`); Char is 4-byte UTF-32 codepoint
        // stored as a u32 bit pattern (Cranelift `I32` — read/store
        // width matches; `char::from_u32` recovers the semantic type
        // at the consumer boundary).
        NativeKind::Float32 => types::F32,
        NativeKind::Char => types::I32,

        // Wave 2 Agent B W12-StringV2-DecimalV2-NativeKind-additions
        // (2026-05-14): v2-raw `*const StringObj` / `*const DecimalObj`
        // pointers — pointer-width I64 load/store (same as the
        // Arc-wrapped sibling row below).
        NativeKind::StringV2 | NativeKind::DecimalV2 => types::I64,

        // Boxed/pointer-sized values: String (Arc<String> raw ptr) and
        // every `Ptr(_)` heap arm.
        NativeKind::String | NativeKind::Ptr(_) => types::I64,

        // R5b-2-bool-null-sentinel-cluster (ADR-006 §2.7 + §2.7.7/Q9,
        // 2026-05-19): `NativeKind::Null` is the absence-of-value
        // sentinel — single-byte I8 storage.
        NativeKind::Null => types::I8,
    }
}

/// Return the byte width of a `NativeKind` for layout computation.
pub fn slot_byte_width(kind: NativeKind) -> u32 {
    match kind {
        NativeKind::Float64 | NativeKind::NullableFloat64 => 8,
        NativeKind::Int64 | NativeKind::NullableInt64 | NativeKind::UInt64 | NativeKind::NullableUInt64 => {
            8
        }
        NativeKind::Int32 | NativeKind::NullableInt32 | NativeKind::UInt32 | NativeKind::NullableUInt32 => {
            4
        }
        NativeKind::Int16 | NativeKind::NullableInt16 | NativeKind::UInt16 | NativeKind::NullableUInt16 => {
            2
        }
        NativeKind::Int8
        | NativeKind::NullableInt8
        | NativeKind::UInt8
        | NativeKind::NullableUInt8
        | NativeKind::Bool => 1,
        NativeKind::IntSize
        | NativeKind::NullableIntSize
        | NativeKind::UIntSize
        | NativeKind::NullableUIntSize => 8,
        // Round 19 S1.5 W12-nativekind-scalar-additions (2026-05-14):
        // ADR-006 §2.7.5 amendment — F32 + Char are 4 bytes.
        NativeKind::Float32 | NativeKind::Char => 4,
        // Wave 2 Agent B W12-StringV2-DecimalV2-NativeKind-additions
        // (2026-05-14): v2-raw heap-pointer carriers — pointer-width 8 bytes.
        NativeKind::StringV2 | NativeKind::DecimalV2 => 8,
        NativeKind::String | NativeKind::Ptr(_) => 8,
        // R5b-2-bool-null-sentinel-cluster (ADR-006 §2.7 + §2.7.7/Q9,
        // 2026-05-19): `NativeKind::Null` is 1-byte storage (mirror
        // of Bool); kind alone is load-bearing.
        NativeKind::Null => 1,
    }
}

// ---------------------------------------------------------------------------
// Struct layout computation
// ---------------------------------------------------------------------------

/// A pre-computed field descriptor: name, byte offset from struct base, and type.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FieldLayout {
    /// Field name (for diagnostics / debugging).
    pub name: String,
    /// Byte offset from the struct base pointer (includes HeapHeader).
    pub offset: u32,
    /// The slot kind that determines Cranelift load/store type.
    pub kind: NativeKind,
}

/// Compute the layout of a v2 typed struct given its fields in declaration order.
///
/// Fields are placed after the 8-byte HeapHeader with natural alignment:
/// each field is aligned to its own byte width (1, 2, 4, or 8).
///
/// Returns a vector of `FieldLayout` descriptors and the total struct size
/// (including any trailing padding to align the whole struct to 8 bytes).
pub fn compute_struct_layout(fields: &[(String, NativeKind)]) -> (Vec<FieldLayout>, u32) {
    let mut layouts = Vec::with_capacity(fields.len());
    let mut cursor = V2_HEAP_HEADER_SIZE; // start after header

    for (name, kind) in fields {
        let width = slot_byte_width(*kind);
        let align = width; // natural alignment = size for primitive types

        // Align cursor up to the field's natural alignment
        let misalign = cursor % align;
        if misalign != 0 {
            cursor += align - misalign;
        }

        layouts.push(FieldLayout {
            name: name.clone(),
            offset: cursor,
            kind: *kind,
        });

        cursor += width;
    }

    // Pad total size to 8-byte boundary for struct-of-structs arrays
    let misalign = cursor % 8;
    if misalign != 0 {
        cursor += 8 - misalign;
    }

    (layouts, cursor)
}

// ---------------------------------------------------------------------------
// MirToIR - v2 MIR-level Cranelift code generator
// ---------------------------------------------------------------------------

/// MIR-to-Cranelift-IR compiler for the v2 runtime.
///
/// Wraps a Cranelift `FunctionBuilder` and provides methods to emit inline
/// typed struct operations (field get/set, allocation) without any FFI overhead.
pub struct MirToIR<'a, 'b: 'a> {
    /// The Cranelift function builder used to emit instructions.
    pub builder: &'a mut FunctionBuilder<'b>,
}

impl<'a, 'b: 'a> MirToIR<'a, 'b> {
    /// Create a new MirToIR code generator wrapping the given function builder.
    pub fn new(builder: &'a mut FunctionBuilder<'b>) -> Self {
        Self { builder }
    }

    // -----------------------------------------------------------------------
    // Typed field access
    // -----------------------------------------------------------------------

    /// Emit an inline typed field read: `load T [struct_ptr + field_offset]`.
    ///
    /// `field_offset` is the absolute byte offset from the struct base pointer
    /// (including the HeapHeader).  `field_type` determines the Cranelift load
    /// width (F64, I64, I32, I16, I8).
    ///
    /// This compiles to a single Cranelift `load` instruction with a constant
    /// offset -- no schema lookup, no FFI call.
    pub fn v2_field_get(
        &mut self,
        struct_ptr: Value,
        field_offset: u32,
        field_type: NativeKind,
    ) -> Value {
        let cl_type = cranelift_type_for_slot(field_type);
        self.builder
            .ins()
            .load(cl_type, MemFlags::trusted(), struct_ptr, field_offset as i32)
    }

    /// Emit an inline typed field write: `store T val -> [struct_ptr + field_offset]`.
    ///
    /// `field_offset` is the absolute byte offset from the struct base pointer
    /// (including the HeapHeader).  `field_type` is used for documentation /
    /// assertions; the actual store width comes from the Cranelift value type.
    ///
    /// This compiles to a single Cranelift `store` instruction.
    pub fn v2_field_set(
        &mut self,
        struct_ptr: Value,
        field_offset: u32,
        val: Value,
        _field_type: NativeKind,
    ) {
        self.builder
            .ins()
            .store(MemFlags::trusted(), val, struct_ptr, field_offset as i32);
    }

    // -----------------------------------------------------------------------
    // Struct allocation
    // -----------------------------------------------------------------------

    /// Emit a call to allocate a v2 typed struct with the given total byte size.
    ///
    /// The `alloc_fn` parameter is a Cranelift `FuncRef` for the runtime's
    /// allocation function with signature `(i64) -> i64` (byte size in, pointer
    /// out).  The allocator is expected to zero-initialize the memory.
    ///
    /// After allocation the caller should write the HeapHeader fields (kind,
    /// refcount) and each struct field using `v2_field_set`.
    pub fn v2_struct_alloc(&mut self, total_size: u32, alloc_fn: FuncRef) -> Value {
        let size_val = self.builder.ins().iconst(types::I64, total_size as i64);
        let inst = self.builder.ins().call(alloc_fn, &[size_val]);
        self.builder.inst_results(inst)[0]
    }

    /// Write the refcount field of a freshly-allocated v2 struct.
    ///
    /// Sets the `u32` at `V2_HEADER_REFCOUNT_OFFSET` to the given initial value
    /// (typically 1).
    pub fn v2_write_refcount(&mut self, struct_ptr: Value, initial: u32) {
        let rc = self.builder.ins().iconst(types::I32, initial as i64);
        self.builder.ins().store(
            MemFlags::trusted(),
            rc,
            struct_ptr,
            V2_HEADER_REFCOUNT_OFFSET as i32,
        );
    }

    /// Write the kind field of a freshly-allocated v2 struct.
    ///
    /// Sets the `u16` at `V2_HEADER_KIND_OFFSET`.
    pub fn v2_write_kind(&mut self, struct_ptr: Value, kind: u16) {
        let k = self.builder.ins().iconst(types::I16, kind as i64);
        self.builder.ins().store(
            MemFlags::trusted(),
            k,
            struct_ptr,
            V2_HEADER_KIND_OFFSET as i32,
        );
    }

    /// Write the flags field of a freshly-allocated v2 struct.
    ///
    /// Sets the `u8` at `V2_HEADER_FLAGS_OFFSET`.
    pub fn v2_write_flags(&mut self, struct_ptr: Value, flags: u8) {
        let f = self.builder.ins().iconst(types::I8, flags as i64);
        self.builder.ins().store(
            MemFlags::trusted(),
            f,
            struct_ptr,
            V2_HEADER_FLAGS_OFFSET as i32,
        );
    }
}

// ===========================================================================
// Unit tests
// ===========================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use cranelift_jit::{JITBuilder, JITModule};
    use cranelift_module::Module;

    // -----------------------------------------------------------------------
    // Layout computation tests (pure, no Cranelift needed)
    // -----------------------------------------------------------------------

    #[test]
    fn v2_field_layout_point_all_f64() {
        // type Point { x: number, y: number }
        let fields = vec![
            ("x".to_string(), NativeKind::Float64),
            ("y".to_string(), NativeKind::Float64),
        ];
        let (layout, total) = compute_struct_layout(&fields);

        assert_eq!(layout.len(), 2);
        assert_eq!(layout[0].name, "x");
        assert_eq!(layout[0].offset, 8); // right after 8-byte header
        assert_eq!(layout[0].kind, NativeKind::Float64);

        assert_eq!(layout[1].name, "y");
        assert_eq!(layout[1].offset, 16); // 8 (header) + 8 (x)
        assert_eq!(layout[1].kind, NativeKind::Float64);

        assert_eq!(total, 24); // 8 header + 8 x + 8 y
    }

    #[test]
    fn v2_field_layout_mixed_types() {
        // type Mixed { flag: bool, count: i32, value: number }
        let fields = vec![
            ("flag".to_string(), NativeKind::Bool),
            ("count".to_string(), NativeKind::Int32),
            ("value".to_string(), NativeKind::Float64),
        ];
        let (layout, total) = compute_struct_layout(&fields);

        assert_eq!(layout.len(), 3);

        // flag: i8, at offset 8 (right after header, 1-byte aligned)
        assert_eq!(layout[0].name, "flag");
        assert_eq!(layout[0].offset, 8);
        assert_eq!(layout[0].kind, NativeKind::Bool);

        // count: i32, needs 4-byte alignment. cursor was at 9, aligns to 12.
        assert_eq!(layout[1].name, "count");
        assert_eq!(layout[1].offset, 12);
        assert_eq!(layout[1].kind, NativeKind::Int32);

        // value: f64, needs 8-byte alignment. cursor was at 16, already aligned.
        assert_eq!(layout[2].name, "value");
        assert_eq!(layout[2].offset, 16);
        assert_eq!(layout[2].kind, NativeKind::Float64);

        // total = 16 + 8 = 24, already 8-byte aligned
        assert_eq!(total, 24);
    }

    #[test]
    fn v2_field_layout_i16_alignment() {
        // type Shorts { a: i16, b: i16, c: i64 }
        let fields = vec![
            ("a".to_string(), NativeKind::Int16),
            ("b".to_string(), NativeKind::Int16),
            ("c".to_string(), NativeKind::Int64),
        ];
        let (layout, total) = compute_struct_layout(&fields);

        // a: i16, at offset 8
        assert_eq!(layout[0].offset, 8);
        // b: i16, at offset 10 (2-byte aligned, cursor was 10)
        assert_eq!(layout[1].offset, 10);
        // c: i64, needs 8-byte alignment. cursor was 12, aligns to 16.
        assert_eq!(layout[2].offset, 16);

        // total = 16 + 8 = 24
        assert_eq!(total, 24);
    }

    #[test]
    fn v2_field_layout_single_bool() {
        // type Flag { active: bool }
        let fields = vec![("active".to_string(), NativeKind::Bool)];
        let (layout, total) = compute_struct_layout(&fields);

        assert_eq!(layout[0].offset, 8);
        // total: 8 (header) + 1 (bool) = 9, padded to 16? No: padded to 8-byte boundary = 16
        assert_eq!(total, 16);
    }

    #[test]
    fn v2_field_layout_empty_struct() {
        let fields: Vec<(String, NativeKind)> = vec![];
        let (layout, total) = compute_struct_layout(&fields);

        assert_eq!(layout.len(), 0);
        assert_eq!(total, 8); // just the header, already 8-byte aligned
    }

    #[test]
    fn v2_field_layout_padding_between_fields() {
        // type Padded { a: bool, b: i64 }
        // a is 1 byte at offset 8, then padding to align b at offset 16.
        let fields = vec![
            ("a".to_string(), NativeKind::Bool),
            ("b".to_string(), NativeKind::Int64),
        ];
        let (layout, total) = compute_struct_layout(&fields);

        assert_eq!(layout[0].offset, 8);
        assert_eq!(layout[1].offset, 16); // 8 + 1 -> pad to 16
        assert_eq!(total, 24); // 16 + 8
    }

    #[test]
    fn v2_field_layout_all_i32() {
        // type Vec3i { x: i32, y: i32, z: i32 }
        let fields = vec![
            ("x".to_string(), NativeKind::Int32),
            ("y".to_string(), NativeKind::Int32),
            ("z".to_string(), NativeKind::Int32),
        ];
        let (layout, total) = compute_struct_layout(&fields);

        assert_eq!(layout[0].offset, 8);
        assert_eq!(layout[1].offset, 12);
        assert_eq!(layout[2].offset, 16);
        // total = 16 + 4 = 20, padded to 24
        assert_eq!(total, 24);
    }

    // -----------------------------------------------------------------------
    // cranelift_type_for_slot mapping tests
    // -----------------------------------------------------------------------

    #[test]
    fn v2_field_slot_to_cranelift_type() {
        assert_eq!(cranelift_type_for_slot(NativeKind::Float64), types::F64);
        assert_eq!(cranelift_type_for_slot(NativeKind::NullableFloat64), types::F64);
        assert_eq!(cranelift_type_for_slot(NativeKind::Int64), types::I64);
        assert_eq!(cranelift_type_for_slot(NativeKind::Int32), types::I32);
        assert_eq!(cranelift_type_for_slot(NativeKind::Int16), types::I16);
        assert_eq!(cranelift_type_for_slot(NativeKind::Bool), types::I8);
        assert_eq!(cranelift_type_for_slot(NativeKind::Int8), types::I8);
        // W11: `NativeKind::Dynamic` deleted by the strict-typing bulldozer
        // (see `crates/shape-value/src/native_kind.rs:103-107`). The
        // ex-`Dynamic` slot mapping (raw u64 storage) is now covered by
        // any heap-pointer kind — `Ptr(HeapKind::TypedArray)` stands in.
        assert_eq!(
            cranelift_type_for_slot(NativeKind::Ptr(shape_value::heap_value::HeapKind::TypedArray)),
            types::I64
        );
        assert_eq!(cranelift_type_for_slot(NativeKind::String), types::I64);
    }

    // -----------------------------------------------------------------------
    // slot_byte_width tests
    // -----------------------------------------------------------------------

    #[test]
    fn v2_field_slot_byte_widths() {
        assert_eq!(slot_byte_width(NativeKind::Float64), 8);
        assert_eq!(slot_byte_width(NativeKind::Int64), 8);
        assert_eq!(slot_byte_width(NativeKind::Int32), 4);
        assert_eq!(slot_byte_width(NativeKind::Int16), 2);
        assert_eq!(slot_byte_width(NativeKind::Bool), 1);
        assert_eq!(slot_byte_width(NativeKind::Int8), 1);
        assert_eq!(slot_byte_width(NativeKind::String), 8);
    }

    // -----------------------------------------------------------------------
    // Cranelift codegen integration tests
    // -----------------------------------------------------------------------

    /// Build a minimal Cranelift JIT environment for testing MirToIR code gen.
    fn make_jit_env() -> (
        JITModule,
        cranelift::codegen::Context,
        FunctionBuilderContext,
    ) {
        let mut flag_builder = settings::builder();
        flag_builder.set("opt_level", "speed").unwrap();
        flag_builder.set("is_pic", "false").unwrap();
        let isa_builder = cranelift_native::builder().unwrap();
        let isa = isa_builder
            .finish(settings::Flags::new(flag_builder))
            .unwrap();
        let builder = JITBuilder::with_isa(isa, cranelift_module::default_libcall_names());
        let module = JITModule::new(builder);
        let ctx = cranelift::codegen::Context::new();
        let fb_ctx = FunctionBuilderContext::new();
        (module, ctx, fb_ctx)
    }

    /// Helper: allocate a fake struct with HeapHeader + field data, return pointer.
    unsafe fn alloc_test_struct(total_bytes: usize) -> *mut u8 {
        let layout = std::alloc::Layout::from_size_align(total_bytes, 8).unwrap();
        let ptr = unsafe { std::alloc::alloc_zeroed(layout) };
        assert!(!ptr.is_null());
        ptr
    }

    /// Helper: free a test struct allocated by `alloc_test_struct`.
    unsafe fn free_test_struct(ptr: *mut u8, total_bytes: usize) {
        let layout = std::alloc::Layout::from_size_align(total_bytes, 8).unwrap();
        unsafe { std::alloc::dealloc(ptr, layout) };
    }

    #[test]
    fn v2_field_get_f64_codegen_and_execute() {
        // Compile a function: fn(ptr: i64) -> f64 { load f64 [ptr + 8] }
        let (mut module, mut ctx, mut fb_ctx) = make_jit_env();

        let ptr_type = module.target_config().pointer_type();

        let mut sig = module.make_signature();
        sig.params.push(AbiParam::new(ptr_type));
        sig.returns.push(AbiParam::new(types::F64));

        let func_id = module
            .declare_function("test_get_f64", cranelift_module::Linkage::Local, &sig)
            .unwrap();

        ctx.func.signature = sig;
        {
            let mut builder = FunctionBuilder::new(&mut ctx.func, &mut fb_ctx);
            let entry = builder.create_block();
            builder.append_block_params_for_function_params(entry);
            builder.switch_to_block(entry);
            builder.seal_block(entry);

            let struct_ptr = builder.block_params(entry)[0];

            let result = {
                let mut mir = MirToIR::new(&mut builder);
                mir.v2_field_get(struct_ptr, 8, NativeKind::Float64)
            };
            builder.ins().return_(&[result]);
            builder.finalize();
        }

        module.define_function(func_id, &mut ctx).unwrap();
        module.clear_context(&mut ctx);
        module.finalize_definitions().unwrap();

        let code_ptr = module.get_finalized_function(func_id);

        unsafe {
            let struct_mem = alloc_test_struct(24);
            let field_ptr = struct_mem.add(8) as *mut f64;
            *field_ptr = 42.5;

            let func: unsafe fn(u64) -> f64 = std::mem::transmute(code_ptr);
            let result = func(struct_mem as u64);
            assert_eq!(result, 42.5);

            free_test_struct(struct_mem, 24);
        }
    }

    #[test]
    fn v2_field_set_f64_codegen_and_execute() {
        // Compile a function: fn(ptr: i64, val: f64) { store f64 val -> [ptr + 16] }
        let (mut module, mut ctx, mut fb_ctx) = make_jit_env();

        let ptr_type = module.target_config().pointer_type();

        let mut sig = module.make_signature();
        sig.params.push(AbiParam::new(ptr_type));
        sig.params.push(AbiParam::new(types::F64));

        let func_id = module
            .declare_function("test_set_f64", cranelift_module::Linkage::Local, &sig)
            .unwrap();

        ctx.func.signature = sig;
        {
            let mut builder = FunctionBuilder::new(&mut ctx.func, &mut fb_ctx);
            let entry = builder.create_block();
            builder.append_block_params_for_function_params(entry);
            builder.switch_to_block(entry);
            builder.seal_block(entry);

            let struct_ptr = builder.block_params(entry)[0];
            let val = builder.block_params(entry)[1];

            {
                let mut mir = MirToIR::new(&mut builder);
                mir.v2_field_set(struct_ptr, 16, val, NativeKind::Float64);
            }
            builder.ins().return_(&[]);
            builder.finalize();
        }

        module.define_function(func_id, &mut ctx).unwrap();
        module.clear_context(&mut ctx);
        module.finalize_definitions().unwrap();

        let code_ptr = module.get_finalized_function(func_id);

        unsafe {
            let struct_mem = alloc_test_struct(24);

            let func: unsafe fn(u64, f64) = std::mem::transmute(code_ptr);
            func(struct_mem as u64, 99.75);

            let stored = *(struct_mem.add(16) as *const f64);
            assert_eq!(stored, 99.75);

            free_test_struct(struct_mem, 24);
        }
    }

    #[test]
    fn v2_field_get_i32_codegen_and_execute() {
        // Compile a function: fn(ptr: i64) -> i32 { load i32 [ptr + 12] }
        let (mut module, mut ctx, mut fb_ctx) = make_jit_env();

        let ptr_type = module.target_config().pointer_type();

        let mut sig = module.make_signature();
        sig.params.push(AbiParam::new(ptr_type));
        sig.returns.push(AbiParam::new(types::I32));

        let func_id = module
            .declare_function("test_get_i32", cranelift_module::Linkage::Local, &sig)
            .unwrap();

        ctx.func.signature = sig;
        {
            let mut builder = FunctionBuilder::new(&mut ctx.func, &mut fb_ctx);
            let entry = builder.create_block();
            builder.append_block_params_for_function_params(entry);
            builder.switch_to_block(entry);
            builder.seal_block(entry);

            let struct_ptr = builder.block_params(entry)[0];

            let result = {
                let mut mir = MirToIR::new(&mut builder);
                mir.v2_field_get(struct_ptr, 12, NativeKind::Int32)
            };
            builder.ins().return_(&[result]);
            builder.finalize();
        }

        module.define_function(func_id, &mut ctx).unwrap();
        module.clear_context(&mut ctx);
        module.finalize_definitions().unwrap();

        let code_ptr = module.get_finalized_function(func_id);

        unsafe {
            let struct_mem = alloc_test_struct(16);
            let field_ptr = struct_mem.add(12) as *mut i32;
            *field_ptr = 0x7FFF_FFFE;

            let func: unsafe fn(u64) -> i32 = std::mem::transmute(code_ptr);
            let result = func(struct_mem as u64);
            assert_eq!(result, 0x7FFF_FFFE);

            free_test_struct(struct_mem, 16);
        }
    }

    #[test]
    fn v2_field_get_bool_codegen_and_execute() {
        // Compile a function: fn(ptr: i64) -> i8 { load i8 [ptr + 8] }
        let (mut module, mut ctx, mut fb_ctx) = make_jit_env();

        let ptr_type = module.target_config().pointer_type();

        let mut sig = module.make_signature();
        sig.params.push(AbiParam::new(ptr_type));
        sig.returns.push(AbiParam::new(types::I8));

        let func_id = module
            .declare_function("test_get_bool", cranelift_module::Linkage::Local, &sig)
            .unwrap();

        ctx.func.signature = sig;
        {
            let mut builder = FunctionBuilder::new(&mut ctx.func, &mut fb_ctx);
            let entry = builder.create_block();
            builder.append_block_params_for_function_params(entry);
            builder.switch_to_block(entry);
            builder.seal_block(entry);

            let struct_ptr = builder.block_params(entry)[0];

            let result = {
                let mut mir = MirToIR::new(&mut builder);
                mir.v2_field_get(struct_ptr, 8, NativeKind::Bool)
            };
            builder.ins().return_(&[result]);
            builder.finalize();
        }

        module.define_function(func_id, &mut ctx).unwrap();
        module.clear_context(&mut ctx);
        module.finalize_definitions().unwrap();

        let code_ptr = module.get_finalized_function(func_id);

        unsafe {
            let struct_mem = alloc_test_struct(16);
            *struct_mem.add(8) = 1u8;

            let func: unsafe fn(u64) -> i8 = std::mem::transmute(code_ptr);
            assert_eq!(func(struct_mem as u64), 1);

            *struct_mem.add(8) = 0u8;
            assert_eq!(func(struct_mem as u64), 0);

            free_test_struct(struct_mem, 16);
        }
    }

    #[test]
    fn v2_field_point_two_fields_codegen_and_execute() {
        // End-to-end: type Point { x: number, y: number }
        // Compile fn(ptr) -> f64 that returns x + y.
        let (mut module, mut ctx, mut fb_ctx) = make_jit_env();

        let ptr_type = module.target_config().pointer_type();

        let mut sig = module.make_signature();
        sig.params.push(AbiParam::new(ptr_type));
        sig.returns.push(AbiParam::new(types::F64));

        let func_id = module
            .declare_function("test_point_sum", cranelift_module::Linkage::Local, &sig)
            .unwrap();

        let fields = vec![
            ("x".to_string(), NativeKind::Float64),
            ("y".to_string(), NativeKind::Float64),
        ];
        let (layout, total) = compute_struct_layout(&fields);
        assert_eq!(layout[0].offset, 8);
        assert_eq!(layout[1].offset, 16);

        ctx.func.signature = sig;
        {
            let mut builder = FunctionBuilder::new(&mut ctx.func, &mut fb_ctx);
            let entry = builder.create_block();
            builder.append_block_params_for_function_params(entry);
            builder.switch_to_block(entry);
            builder.seal_block(entry);

            let struct_ptr = builder.block_params(entry)[0];

            let (x, y) = {
                let mut mir = MirToIR::new(&mut builder);
                let x = mir.v2_field_get(struct_ptr, layout[0].offset, layout[0].kind);
                let y = mir.v2_field_get(struct_ptr, layout[1].offset, layout[1].kind);
                (x, y)
            };
            let sum = builder.ins().fadd(x, y);
            builder.ins().return_(&[sum]);
            builder.finalize();
        }

        module.define_function(func_id, &mut ctx).unwrap();
        module.clear_context(&mut ctx);
        module.finalize_definitions().unwrap();

        let code_ptr = module.get_finalized_function(func_id);

        unsafe {
            let struct_mem = alloc_test_struct(total as usize);
            *(struct_mem.add(8) as *mut f64) = 3.0;
            *(struct_mem.add(16) as *mut f64) = 4.0;

            let func: unsafe fn(u64) -> f64 = std::mem::transmute(code_ptr);
            assert_eq!(func(struct_mem as u64), 7.0);

            free_test_struct(struct_mem, total as usize);
        }
    }

    #[test]
    fn v2_field_mixed_struct_codegen_and_execute() {
        // type Mixed { flag: bool, count: i32, value: number }
        // Compile fn(ptr) -> f64 -- reads the `value` field at its naturally
        // aligned offset to verify mixed-type layout correctness.
        let (mut module, mut ctx, mut fb_ctx) = make_jit_env();

        let ptr_type = module.target_config().pointer_type();

        let mut sig = module.make_signature();
        sig.params.push(AbiParam::new(ptr_type));
        sig.returns.push(AbiParam::new(types::F64));

        let func_id = module
            .declare_function(
                "test_mixed_value",
                cranelift_module::Linkage::Local,
                &sig,
            )
            .unwrap();

        let fields = vec![
            ("flag".to_string(), NativeKind::Bool),
            ("count".to_string(), NativeKind::Int32),
            ("value".to_string(), NativeKind::Float64),
        ];
        let (layout, total) = compute_struct_layout(&fields);

        ctx.func.signature = sig;
        {
            let mut builder = FunctionBuilder::new(&mut ctx.func, &mut fb_ctx);
            let entry = builder.create_block();
            builder.append_block_params_for_function_params(entry);
            builder.switch_to_block(entry);
            builder.seal_block(entry);

            let struct_ptr = builder.block_params(entry)[0];

            let value = {
                let mut mir = MirToIR::new(&mut builder);
                mir.v2_field_get(struct_ptr, layout[2].offset, layout[2].kind)
            };
            builder.ins().return_(&[value]);
            builder.finalize();
        }

        module.define_function(func_id, &mut ctx).unwrap();
        module.clear_context(&mut ctx);
        module.finalize_definitions().unwrap();

        let code_ptr = module.get_finalized_function(func_id);

        unsafe {
            let struct_mem = alloc_test_struct(total as usize);
            *struct_mem.add(layout[0].offset as usize) = 1u8;
            *(struct_mem.add(layout[1].offset as usize) as *mut i32) = 42;
            *(struct_mem.add(layout[2].offset as usize) as *mut f64) = 3.14;

            let func: unsafe fn(u64) -> f64 = std::mem::transmute(code_ptr);
            assert_eq!(func(struct_mem as u64), 3.14);

            free_test_struct(struct_mem, total as usize);
        }
    }

    #[test]
    fn v2_field_write_then_read_roundtrip() {
        // Compile two functions:
        //   writer(ptr, f64): stores val at offset 8
        //   reader(ptr) -> f64: loads from offset 8
        // Verify roundtrip.
        let (mut module, mut ctx, mut fb_ctx) = make_jit_env();

        let ptr_type = module.target_config().pointer_type();

        // Writer: (i64, f64) -> void
        let mut writer_sig = module.make_signature();
        writer_sig.params.push(AbiParam::new(ptr_type));
        writer_sig.params.push(AbiParam::new(types::F64));

        let writer_id = module
            .declare_function(
                "test_roundtrip_w",
                cranelift_module::Linkage::Local,
                &writer_sig,
            )
            .unwrap();

        ctx.func.signature = writer_sig;
        {
            let mut builder = FunctionBuilder::new(&mut ctx.func, &mut fb_ctx);
            let entry = builder.create_block();
            builder.append_block_params_for_function_params(entry);
            builder.switch_to_block(entry);
            builder.seal_block(entry);

            let sp = builder.block_params(entry)[0];
            let val = builder.block_params(entry)[1];

            {
                let mut mir = MirToIR::new(&mut builder);
                mir.v2_field_set(sp, 8, val, NativeKind::Float64);
            }
            builder.ins().return_(&[]);
            builder.finalize();
        }
        module.define_function(writer_id, &mut ctx).unwrap();
        module.clear_context(&mut ctx);

        // Reader: (i64) -> f64
        let mut reader_sig = module.make_signature();
        reader_sig.params.push(AbiParam::new(ptr_type));
        reader_sig.returns.push(AbiParam::new(types::F64));

        let reader_id = module
            .declare_function(
                "test_roundtrip_r",
                cranelift_module::Linkage::Local,
                &reader_sig,
            )
            .unwrap();

        ctx.func.signature = reader_sig;
        {
            let mut builder = FunctionBuilder::new(&mut ctx.func, &mut fb_ctx);
            let entry = builder.create_block();
            builder.append_block_params_for_function_params(entry);
            builder.switch_to_block(entry);
            builder.seal_block(entry);

            let sp = builder.block_params(entry)[0];

            let result = {
                let mut mir = MirToIR::new(&mut builder);
                mir.v2_field_get(sp, 8, NativeKind::Float64)
            };
            builder.ins().return_(&[result]);
            builder.finalize();
        }
        module.define_function(reader_id, &mut ctx).unwrap();
        module.clear_context(&mut ctx);

        module.finalize_definitions().unwrap();

        let writer_ptr = module.get_finalized_function(writer_id);
        let reader_ptr = module.get_finalized_function(reader_id);

        unsafe {
            let struct_mem = alloc_test_struct(16);

            let writer: unsafe fn(u64, f64) = std::mem::transmute(writer_ptr);
            let reader: unsafe fn(u64) -> f64 = std::mem::transmute(reader_ptr);

            writer(struct_mem as u64, -123.456);
            let got = reader(struct_mem as u64);
            assert_eq!(got, -123.456);

            writer(struct_mem as u64, f64::INFINITY);
            assert_eq!(reader(struct_mem as u64), f64::INFINITY);

            free_test_struct(struct_mem, 16);
        }
    }
}