shape-vm 0.3.1

Stack-based bytecode virtual machine for the Shape programming language
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
//! Core MIR types: Place, Statement, Terminator, BasicBlock.
//!
//! These represent the mid-level IR that the borrow solver operates on.
//! Places track what can be borrowed (locals, fields, indices).
//! Statements and terminators form basic blocks in a control flow graph.

use shape_ast::ast::{Span, TypeAnnotation};
use std::fmt;

// ── Identifiers ──────────────────────────────────────────────────────

/// Index of a local variable slot.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct SlotId(pub u16);

/// Index of a struct/object field.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct FieldIdx(pub u16);

/// Index of a basic block within a MIR function.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct BasicBlockId(pub u32);

/// A program point (statement index within the function's linearized MIR).
/// Used as the "point" dimension in Datafrog relations.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Point(pub u32);

/// Unique identifier for a loan (borrow).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct LoanId(pub u32);

/// A normalized step in a place projection chain.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ProjectionStep {
    Field(FieldIdx),
    /// Index projections are intentionally summarized without their concrete
    /// operand. The borrow solver only needs to know that an index boundary
    /// exists for provenance and diagnostics.
    Index,
}

impl fmt::Display for SlotId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "_{}", self.0)
    }
}

impl fmt::Display for BasicBlockId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "bb{}", self.0)
    }
}

impl fmt::Display for Point {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "p{}", self.0)
    }
}

impl fmt::Display for LoanId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "L{}", self.0)
    }
}

// ── Places ───────────────────────────────────────────────────────────

/// A place is something that can be borrowed or assigned to.
/// Tracks granular access paths for disjoint borrow analysis.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Place {
    /// A local variable: `x`
    Local(SlotId),
    /// A field of a place: `x.field_name`
    Field(Box<Place>, FieldIdx),
    /// An index into a place: `x[i]` — index analysis is conservative in v1.
    /// The index operand is boxed to break the recursive type cycle (Place → Operand → Place).
    Index(Box<Place>, Box<Operand>),
    /// Dereferencing a reference: `*r`
    Deref(Box<Place>),
}

impl Place {
    /// Get the root local of this place (e.g., `x.a.b` → `x`).
    pub fn root_local(&self) -> SlotId {
        match self {
            Place::Local(slot) => *slot,
            Place::Field(base, _) | Place::Index(base, _) | Place::Deref(base) => base.root_local(),
        }
    }

    /// Check if this place is a prefix of another (for conflict detection).
    /// `x` is a prefix of `x.a`, `x` is a prefix of `x[i]`, etc.
    pub fn is_prefix_of(&self, other: &Place) -> bool {
        if self == other {
            return true;
        }
        match other {
            Place::Local(_) => false,
            Place::Field(base, _) | Place::Index(base, _) | Place::Deref(base) => {
                self.is_prefix_of(base)
            }
        }
    }

    /// Check whether two places conflict (one borrows/writes something the other uses).
    /// Two places conflict if one is a prefix of the other, or they're the same.
    /// In v1, disjoint field borrows are tracked (x.a and x.b don't conflict),
    /// but index borrows are conservative (x[i] and x[j] always conflict).
    pub fn conflicts_with(&self, other: &Place) -> bool {
        // Same root?
        if self.root_local() != other.root_local() {
            return false;
        }
        // Walk both paths to check overlap
        self.is_prefix_of(other) || other.is_prefix_of(self) || self.overlaps(other)
    }

    fn overlaps(&self, other: &Place) -> bool {
        match (self, other) {
            (Place::Local(a), Place::Local(b)) => a == b,
            // Disjoint fields: x.a and x.b do NOT conflict
            (Place::Field(base_a, field_a), Place::Field(base_b, field_b)) => {
                if base_a == base_b {
                    field_a == field_b
                } else {
                    base_a.overlaps(base_b)
                }
            }
            // Conservative: x[i] and x[j] always conflict
            (Place::Index(base_a, _), Place::Index(base_b, _)) => base_a.overlaps(base_b),
            _ => self.is_prefix_of(other) || other.is_prefix_of(self),
        }
    }

    /// Return a normalized projection summary from the root local to this place.
    pub fn projection_steps(&self) -> Vec<ProjectionStep> {
        let mut steps = Vec::new();
        self.collect_projection_steps(&mut steps);
        steps
    }

    fn collect_projection_steps(&self, steps: &mut Vec<ProjectionStep>) {
        match self {
            Place::Local(_) => {}
            Place::Field(base, field) => {
                base.collect_projection_steps(steps);
                steps.push(ProjectionStep::Field(*field));
            }
            Place::Index(base, _) => {
                base.collect_projection_steps(steps);
                steps.push(ProjectionStep::Index);
            }
            Place::Deref(base) => base.collect_projection_steps(steps),
        }
    }
}

impl fmt::Display for Place {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Place::Local(slot) => write!(f, "{}", slot),
            Place::Field(base, field) => write!(f, "{}.{}", base, field.0),
            Place::Index(base, idx) => write!(f, "{}[{}]", base, idx),
            Place::Deref(base) => write!(f, "*{}", base),
        }
    }
}

// ── Operands ─────────────────────────────────────────────────────────

/// An operand in an Rvalue or terminator.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Operand {
    /// Copy the value from a place (for Copy types).
    Copy(Place),
    /// Move the value from a place (invalidates the source).
    Move(Place),
    /// Explicit source-level move (`move x`) that must not be rewritten into a clone.
    MoveExplicit(Place),
    /// A constant value.
    Constant(MirConstant),
}

impl fmt::Display for Operand {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Operand::Copy(p) => write!(f, "copy {}", p),
            Operand::Move(p) => write!(f, "move {}", p),
            Operand::MoveExplicit(p) => write!(f, "move! {}", p),
            Operand::Constant(c) => write!(f, "{}", c),
        }
    }
}

/// A constant value in MIR.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum MirConstant {
    Int(i64),
    Bool(bool),
    None,
    /// String interned index (legacy — prefer Str for new code)
    StringId(u32),
    /// String literal value (carried through MIR for direct JIT materialization)
    Str(String),
    /// Float (stored as bits for Eq/Hash)
    Float(u64),
    /// Decimal literal — carried through MIR as the source-form lexeme.
    ///
    /// WS-8 (2026-05-22): pre-WS-8 `Literal::Decimal(_)` MIR lowering at
    /// `mir/lowering/expr.rs:1937` collapsed to `MirConstant::Float(0)` ("decimal
    /// not yet modeled"), silently losing the value. The JIT then printed
    /// `0.0` for `print(1.5D)` while the VM printed `1.5D` — a v0.3-gating
    /// silent wrong-answer divergence (WS-8 audit §1.D). The MIR producer now
    /// emits this variant verbatim; the JIT consumer SURFACEs (`compile_constant`
    /// returns Err), triggering the W12 fall-through to the bytecode interpreter
    /// (which materializes the decimal via the VM's `NewDecimalV2` opcode and
    /// prints correctly). VM == JIT, both run the interpreter path. The variant
    /// stores the decimal's lexeme so JIT codegen can light up later without
    /// re-parsing the AST.
    Decimal(String),
    /// Character literal (scalar codepoint).
    ///
    /// Phase 3 cluster-2 Round 4 cw-D-fam12 follow-up (instance 57, 2026-05-16).
    /// ADR-006 §2.7.5 amendment Round 19 S1.5 W12-nativekind-scalar-additions
    /// (2026-05-14): `Char` is a 4-byte scalar `NativeKind` variant (codepoint
    /// in low 32 bits of `ValueSlot`, no Arc wrapping). Producing-site
    /// stamp-at-compile-time discipline requires the MIR layer to preserve the
    /// Char kind through to the JIT's `operand_slot_kind` / `infer_constant_kind`
    /// classifiers — otherwise `Literal::Char('A')` is lost as `MirConstant::Int(65)`
    /// at MIR lowering, the JIT stamps `NativeKind::Int64`, and the `print`
    /// dispatch matches `print_i64(65)` instead of `print_char(65)` → JIT prints
    /// "65" while VM prints "A" (cw-D-fam12 Char production-fixture divergence).
    Char(char),
    /// Function reference by name
    Function(String),
    /// Method name for dispatch
    Method(String),
    /// Placeholder for a closure function reference.
    /// Patched to `Function(name)` after bytecode compilation resolves the closure's function_id.
    ClosurePlaceholder,
}

impl fmt::Display for MirConstant {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            MirConstant::Int(v) => write!(f, "{}", v),
            MirConstant::Bool(v) => write!(f, "{}", v),
            MirConstant::None => write!(f, "none"),
            MirConstant::StringId(id) => write!(f, "str#{}", id),
            MirConstant::Str(s) => write!(f, "\"{}\"", s),
            MirConstant::Float(bits) => write!(f, "{}", f64::from_bits(*bits)),
            MirConstant::Decimal(s) => write!(f, "{}D", s),
            MirConstant::Char(c) => write!(f, "'{}'", c.escape_default()),
            MirConstant::Function(name) => write!(f, "fn:{}", name),
            MirConstant::Method(name) => write!(f, "method:{}", name),
            MirConstant::ClosurePlaceholder => write!(f, "closure_placeholder"),
        }
    }
}

// ── Rvalues ──────────────────────────────────────────────────────────

/// The kind of borrow.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BorrowKind {
    /// Shared (immutable) borrow: `&x`
    Shared,
    /// Exclusive (mutable) borrow: `&mut x`
    Exclusive,
}

impl fmt::Display for BorrowKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            BorrowKind::Shared => write!(f, "&"),
            BorrowKind::Exclusive => write!(f, "&mut"),
        }
    }
}

/// Result/Option variant tag — classification is producer-side per
/// ADR-006 §2.7.5 stamp-at-compile-time. Carried by `Rvalue::EnumTest`
/// and `Rvalue::EnumPayload`; the JIT consumer dispatches on this enum
/// directly, never decodes from bits (§2.7.7 #4 / #7 forbidden).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum VariantTag {
    Ok,
    Err,
    Some_,
    None_,
}

impl fmt::Display for VariantTag {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            VariantTag::Ok => write!(f, "Ok"),
            VariantTag::Err => write!(f, "Err"),
            VariantTag::Some_ => write!(f, "Some"),
            VariantTag::None_ => write!(f, "None"),
        }
    }
}

impl VariantTag {
    /// Map a constructor name to a VariantTag. Returns `None` for non-
    /// builtin (`Ok`/`Err`/`Some`/`None`) names so the producer site can
    /// fall back to the generic `Aggregate` / `EnumStore` path for user-
    /// defined enum variants.
    #[inline]
    pub fn from_name(name: &str) -> Option<Self> {
        match name {
            "Ok" => Some(VariantTag::Ok),
            "Err" => Some(VariantTag::Err),
            "Some" => Some(VariantTag::Some_),
            "None" => Some(VariantTag::None_),
            _ => None,
        }
    }
}

/// Right-hand side of an assignment.
#[derive(Debug, Clone, PartialEq)]
pub enum Rvalue {
    /// Use an operand directly.
    Use(Operand),
    /// Create a borrow: `&place` or `&mut place`
    Borrow(BorrowKind, Place),
    /// Binary operation.
    BinaryOp(BinOp, Operand, Operand),
    /// Unary operation.
    UnaryOp(UnOp, Operand),
    /// Function call result (arguments passed via terminator).
    /// This is a placeholder — actual calls use Call terminators.
    Aggregate(Vec<Operand>),
    /// Clone of a value (explicit or auto-inferred).
    Clone(Operand),
    /// Test whether a Result/Option scrutinee matches a specific variant
    /// (per ADR-006 §2.7.17 / Q18 — kinded `Arc<ResultData>` /
    /// `Arc<OptionData>` carrier). Result: native Bool (`I8`).
    ///
    /// Emitted by `lower_match_pattern_condition_operand` when the scrutinee
    /// is a `Pattern::Constructor` with a recognised `VariantTag::Ok` /
    /// `Err` / `Some_` / `None_`. JIT consumer dispatches to the
    /// `jit_arc_result_is_ok` / `_is_err` / `jit_arc_option_is_some` /
    /// `_is_none` FFI which reads `is_ok` / `is_some` from the
    /// `*const ResultData` / `*const OptionData` directly per §2.7.17
    /// — no NaN-box tag decode, no `is_heap_kind` probe (§2.7.7 #4 / #7
    /// forbidden).
    ///
    /// Producer-side classification per W12-jit-result-option-trinity
    /// audit (`docs/cluster-audits/w12-jit-match-enum-inline-audit.md` §6.1).
    EnumTest {
        operand: Operand,
        variant: VariantTag,
    },
    /// Extract the inner payload bits from a Result/Option scrutinee.
    /// Caller must have already proven the variant via `EnumTest`
    /// (control flow guarantees the matching arm is entered only when
    /// the variant matches; the `variant` tag here is the producer-side
    /// classification for kind sourcing, NOT a runtime check).
    ///
    /// Result: raw `u64` payload bits — the payload's kind flows out of
    /// band via 6A's Call-return-kind track + the EnumStore producer's
    /// kind stamp.
    ///
    /// JIT consumer dispatches to `jit_arc_result_payload` /
    /// `jit_arc_option_payload` which read the inner `KindedSlot.raw()`
    /// from the `*const ResultData` / `*const OptionData` and bump the
    /// inner refcount per the receiver-recovery soundness rule —
    /// the returned bits are an owned slot.
    ///
    /// `VariantTag::None_` is rejected at consumer time (no payload to
    /// extract — None's payload field is a zero-bits Bool placeholder
    /// per ADR-006 §2.7.17 `OptionData::none()`).
    ///
    /// Producer-side classification per W12-jit-result-option-trinity
    /// audit §6.2.
    EnumPayload {
        operand: Operand,
        variant: VariantTag,
    },
    /// Test whether the scrutinee's runtime kind matches a `Pattern::Typed`
    /// type annotation (e.g. `match x { n: int => ..., s: string => ... }`).
    /// Result: native Bool (`I8`).
    ///
    /// W15.2-LANG-5 (Phase 4b, 2026-05-18). Pre-fix the MIR lowering of
    /// `Pattern::Typed` returned `None` for the condition operand — same
    /// shape as `Pattern::Wildcard`/`Pattern::Identifier` — so every typed
    /// match arm was reached via `TerminatorKind::Goto` with NO type
    /// discrimination. The first arm always won and the union-scrutinee
    /// silently took the wrong branch under JIT.
    ///
    /// Producer-side classification per ADR-006 §2.7.5 stamp-at-compile-time:
    /// the type annotation is carried verbatim from `ast::Pattern::Typed`
    /// so consumers do not re-derive it from the operand bits.
    ///
    /// Consumer status:
    /// - JIT MIR preflight (`shape-jit::mir_compiler::preflight`) REJECTS
    ///   on this Rvalue → W12 fall-through routes the program to the
    ///   bytecode interpreter, which compiles the same scrutinee via the
    ///   `OpCode::TypeCheck` path in `compiler/patterns/checking.rs`.
    ///   Native JIT codegen lands as a follow-up (`jit_type_check` FFI +
    ///   per-kind dispatch on the §2.7.7 stack parallel-kind track).
    /// - VM never consumes MIR; `compile_match_expr` in
    ///   `compiler/expressions/advanced.rs` calls `compile_pattern_check`
    ///   directly on the AST and emits `OpCode::TypeCheck` itself.
    ///
    /// The annotation IS the producer-side classification — neither a
    /// Bool-default fabrication nor any of the deleted dispatch families
    /// enumerated under CLAUDE.md Forbidden Patterns.
    TypePatternTest {
        operand: Operand,
        type_annotation: TypeAnnotation,
    },
    /// Test whether the scrutinee's enum discriminant matches a specific
    /// user-defined `Pattern::Constructor` variant (e.g. `match c {
    /// Color::Red => ..., Color::Green => ... }`). Result: native Bool
    /// (`I8`).
    ///
    /// W15.2-LANG-1 (Phase 4b, 2026-05-18). Pre-fix the MIR lowering of
    /// `Pattern::Constructor` for non-trinity (non-`Ok`/`Err`/`Some`/`None`)
    /// variants returned `Some(Operand::Copy(Place::Local(scrutinee_slot)))`
    /// — the raw `Arc<TypedObjectStorage>` pointer bits — as the
    /// `SwitchBool` condition. The JIT consumer's generic I64-truthy
    /// check at `terminators.rs::SwitchBool` then evaluated the non-zero
    /// pointer as `true` for the first arm OR fell to false-branch when
    /// the multi-arm dispatch chain looped past the first arm, producing
    /// silent-empty-output for the user's `match Color::Red { Color::Red
    /// => print("red"), ... }` case (book snippet `enums.mdx:113`).
    ///
    /// Producer-side classification per ADR-006 §2.7.5 stamp-at-compile-
    /// time: the enum name + variant name are carried verbatim from
    /// `ast::Pattern::Constructor` so the consumer dispatches on a known
    /// (`enum_name`, `variant_name`) pair, NEVER on raw scrutinee bits.
    ///
    /// Consumer status:
    /// - JIT MIR preflight (`shape-jit::mir_compiler::preflight`) REJECTS
    ///   on this Rvalue → W12 fall-through routes the program to the
    ///   bytecode interpreter, which compiles the same scrutinee via the
    ///   `compile_typed_enum_pattern_check` path in
    ///   `compiler/patterns/checking.rs` (emits `GetFieldTyped(__variant,
    ///   I64)` + `PushConst(expected_variant_id)` + `EqInt`).
    /// - VM never consumes MIR; `compile_match_expr` in
    ///   `compiler/expressions/advanced.rs` calls `compile_pattern_check`
    ///   directly on the AST and emits the typed-object discriminant
    ///   check itself.
    ///
    /// The (enum_name, variant_name) pair IS the producer-side
    /// classification — neither a Bool-default fabrication nor any of
    /// the deleted dispatch families enumerated under CLAUDE.md
    /// Forbidden Patterns. Mirrors the LANG-5 `TypePatternTest`
    /// precedent (W15.2-LANG-5 close 2026-05-18) for `Pattern::Typed`.
    EnumDiscriminantTest {
        operand: Operand,
        enum_name: Option<String>,
        variant_name: String,
    },
}

/// Binary operations in MIR.
///
/// W11-fup-A (Phase 3d, 2026-05-18) extends this enum with `Pow` + the five
/// bitwise variants (`BitAnd`/`BitOr`/`BitXor`/`BitShl`/`BitShr`) per the
/// W11-jit-new-array close §4 Class A residual: the bytecode VM already
/// emits typed opcodes for these operators (`PowInt`/`PowNumber`,
/// `BitAndInt`/`BitOrInt`/`BitXorInt`/`BitShlInt`/`BitShrInt` at
/// `crates/shape-vm/src/bytecode/opcode_defs.rs:317-322 / 1860-1873`); the
/// MIR layer was the gap forcing `lower_binary_op` to fall through to
/// `Rvalue::Aggregate(vec![l, r])` and surface-and-stop in JIT (`Route A`
/// at `crates/shape-jit/src/mir_compiler/rvalues.rs:145`).
///
/// Fuzzy ops + `NullCoalesce` / `ErrorContext` / `Pipe` remain unhandled
/// here per the same close doc's "different semantics" disposition — those
/// are tracked by their own follow-up sub-clusters.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BinOp {
    Add,
    Sub,
    Mul,
    Div,
    Mod,
    Pow,
    BitAnd,
    BitOr,
    BitXor,
    BitShl,
    BitShr,
    Eq,
    Ne,
    Lt,
    Le,
    Gt,
    Ge,
    And,
    Or,
}

/// Unary operations in MIR.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnOp {
    Neg,
    Not,
    // W14.2-A1 (Phase 4b, 2026-05-18): `BitNot` (`~x`) lowers to native
    // Int64 bitwise-NOT, mirroring the bytecode VM's `BitNotInt` typed
    // opcode (`arithmetic/mod.rs:229`). The MIR enum extension mirrors
    // the W11-fup-A `BinOp` Pow/BitAnd/BitOr/BitXor/Shl/Shr pattern at
    // `mir/types.rs:373-407` (close commit `46be6b0d`) — without this
    // variant, `lower_unary_op(BitNot)` returned `None` and the
    // expression fell through to the kind-blind `Rvalue::Aggregate(vec![
    // operand])` arm at `mir/lowering/expr.rs:1722-1727`, which the JIT
    // consumer surface-and-stops as W11-followup-unop-bitnot per
    // W11-fup-A close §"Residuals" line 4 ("Class F NEW UnOp::BitNot:
    // op_bitwise JIT → W11-followup-unop-bitnot").
    BitNot,
}

// ── Task Boundary Kind ───────────────────────────────────────────────

/// Distinguishes detached vs structured async task boundaries.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TaskBoundaryKind {
    /// Detached async task (not joined in declaring scope).
    Detached,
    /// Structured child task (joined before parent scope exits).
    Structured,
}

// ── Statements ───────────────────────────────────────────────────────

/// A statement within a basic block (doesn't affect control flow).
#[derive(Debug, Clone, PartialEq)]
pub struct MirStatement {
    pub kind: StatementKind,
    pub span: Span,
    /// The program point of this statement (assigned during linearization).
    pub point: Point,
}

#[derive(Debug, Clone, PartialEq)]
pub enum StatementKind {
    /// Assign a value to a place: `place = rvalue`
    Assign(Place, Rvalue),
    /// Drop a place (scope exit, explicit drop).
    /// Generates invalidation facts for any loans on this place.
    Drop(Place),
    /// Cross a task boundary (spawn/join branch capture).
    /// Operands are the values flowing into the spawned task.
    /// The kind distinguishes detached vs structured tasks.
    TaskBoundary(Vec<Operand>, TaskBoundaryKind),
    /// Capture values into a closure environment.
    /// Operands are the outer values flowing into the closure.
    /// `function_id` is patched after bytecode compilation resolves the closure's index.
    ClosureCapture {
        closure_slot: SlotId,
        operands: Vec<Operand>,
        function_id: Option<u16>,
    },
    /// Store values into an array literal.
    /// Operands are the array elements being stored.
    ArrayStore {
        container_slot: SlotId,
        operands: Vec<Operand>,
    },
    /// Store values into an object or struct literal.
    /// Operands are the fields/spreads being stored.
    /// `field_names` carries the string key for each operand (from the AST).
    /// When present, JIT codegen can construct a proper object with named fields.
    ///
    /// `schema_id` carries the user-declared (or anonymous-inline) schema id
    /// from the bytecode-side `OpCode::NewTypedObject` operand
    /// (`Operand::TypedObjectAlloc { schema_id, field_count }`). MIR lowering
    /// emits `None`; the bytecode compiler back-patches the resolved
    /// `SchemaId` via `crate::compiler::mir_schema_threading::
    /// back_patch_schema_ids` (Phase 3 cluster-0 Round 16 W17-narrow-
    /// follow-up-A, ADR-006 §2.7.5 stamp-at-compile-time). The JIT MIR
    /// consumer at `crates/shape-jit/src/mir_compiler/statements.rs::
    /// StatementKind::ObjectStore` uses this id directly for
    /// `typed_object_alloc`, preserving the user-declared schema identity
    /// (e.g. `X` schema = 53 in Smoke 3) instead of the prior
    /// `register_predeclared_any_schema` `__predecl_*`-named id (54).
    ///
    /// `None` when the back-patch could not resolve the schema (the
    /// downstream JIT consumer surfaces-and-stops per §2.7.5 — no
    /// `register_predeclared_any_schema` fallback, no Bool-default).
    ObjectStore {
        container_slot: SlotId,
        operands: Vec<Operand>,
        field_names: Vec<String>,
        schema_id: Option<u32>,
    },
    /// Store values into an enum payload.
    /// Operands are the tuple/struct payload values being stored.
    ///
    /// `variant_name` carries the constructor name (Ok / Err / Some /
    /// user-defined variant) — known at MIR-lowering time and threaded
    /// through so the JIT EnumStore consumer can dispatch to the right
    /// typed-Arc producer (`jit_v2_make_result_ok` / `_err` /
    /// `jit_v2_make_option_some`). `None` is permitted for paths that
    /// haven't been migrated to thread the variant; downstream JIT
    /// consumers surface-and-stop on `None` for non-empty payloads per
    /// ADR-006 §2.7.5 / §2.7.7 #9 (no Bool-default fallback).
    EnumStore {
        container_slot: SlotId,
        operands: Vec<Operand>,
        variant_name: Option<String>,
    },
    /// No-op (placeholder, padding).
    Nop,
}

// ── Terminators ──────────────────────────────────────────────────────

/// A block terminator (controls flow between basic blocks).
#[derive(Debug, Clone, PartialEq)]
pub struct Terminator {
    pub kind: TerminatorKind,
    pub span: Span,
}

#[derive(Debug, Clone, PartialEq)]
pub enum TerminatorKind {
    /// Unconditional jump.
    Goto(BasicBlockId),
    /// Conditional branch.
    SwitchBool {
        operand: Operand,
        true_bb: BasicBlockId,
        false_bb: BasicBlockId,
    },
    /// Function call.
    Call {
        func: Operand,
        args: Vec<Operand>,
        /// Where to store the return value.
        destination: Place,
        /// Block to jump to after the call returns.
        next: BasicBlockId,
    },
    /// Return from function.
    Return,
    /// Unreachable (after diverging calls, infinite loops).
    Unreachable,
}

// ── Basic Blocks ─────────────────────────────────────────────────────

/// A basic block: a sequence of statements ending in a terminator.
#[derive(Debug, Clone)]
pub struct BasicBlock {
    pub id: BasicBlockId,
    pub statements: Vec<MirStatement>,
    pub terminator: Terminator,
}

// ── MIR Function ─────────────────────────────────────────────────────

/// The MIR representation of a single function.
#[derive(Debug, Clone)]
pub struct MirFunction {
    pub name: String,
    /// The basic blocks forming the CFG.
    pub blocks: Vec<BasicBlock>,
    /// Number of local variable slots.
    pub num_locals: u16,
    /// Which locals are function parameters.
    pub param_slots: Vec<SlotId>,
    /// Per-parameter reference kind, aligned with `param_slots`.
    pub param_reference_kinds: Vec<Option<BorrowKind>>,
    /// Type information for locals (for Copy/Clone inference).
    pub local_types: Vec<LocalTypeInfo>,
    /// Source span of the function.
    pub span: Span,
    /// Mapping from FieldIdx to field name, for JIT field access resolution.
    pub field_name_table: std::collections::HashMap<FieldIdx, String>,
    /// Per-slot user-struct type name for slots produced by
    /// `Expr::StructLiteral { name, .. }` lowering.
    ///
    /// ADR-006 §2.7.5 producing-site classification — Phase 3 cluster-0
    /// Round 13 T1' gap 1 closure. The bytecode compiler's
    /// `concrete_type_from_annotation`
    /// (`crates/shape-vm/src/compiler/v2_map_emission.rs:357`) does
    /// NOT resolve user-struct names to a per-struct `StructLayoutId`
    /// (the `_ => None` arm at line 378), and the conduit producer at
    /// `compiler/helpers.rs:508` stamps `Struct(StructLayoutId(0))`
    /// for every `ObjectStore` regardless of struct identity. Neither
    /// path makes user-struct type name observable at conduit-time.
    ///
    /// This map is populated at MIR lowering for
    /// `Expr::StructLiteral { name, .. }` sites (the canonical
    /// user-struct construction shape — `let t = X {}`,
    /// `let p = Point { x: 1, y: 2 }`). The conduit producer reads
    /// the map at Call-terminator destination-stamp time for
    /// `MirConstant::Method(_)` terminators to look up the trait method
    /// declared return ConcreteType via the
    /// `find_default_trait_impl_for_type_method` chain.
    ///
    /// `None` (no entry) for slots that aren't user-struct constructions
    /// — primitives, collections, plain object literals, function returns,
    /// etc. The downstream classifier surfaces unstamped per §2.7.7 #9 /
    /// forbidden #9 (no fabricated default).
    pub local_struct_type_names:
        std::collections::HashMap<SlotId, String>,
    /// Per-slot empty-typed-array element ConcreteType for slots produced by
    /// `let mut <name>: Array<C> = []` lowering (where `C` is a
    /// `concrete_type_from_annotation`-resolvable element type).
    ///
    /// ADR-006 §2.7.5 stamp-at-compile-time — V3-S6e-jit-specialized-vec-
    /// map-aggregate-classify (Phase 3 cluster-0+1 Wave 3 Stabilize Round 2,
    /// 2026-05-16; V3-S6 multi-session chain checkpoint-final).
    ///
    /// Closes the W11-jit-new-array gap inside monomorphized `Vec.map<U>` /
    /// `Vec.filter<U>` specialization bodies. V3-S6a's
    /// `synthesize_empty_array_result_annotation` writes
    /// `Array<C>` onto the `let mut result = []` var-decl AST node for the
    /// specialized function; this map captures that annotation at MIR
    /// lowering so the conduit producer at
    /// `crates/shape-vm/src/compiler/helpers.rs::infer_top_level_concrete_
    /// types_from_mir_with_resolvers` can stamp `concrete_types[result_slot]
    /// = Array(elem)`.
    ///
    /// Why MIR-level rather than just bytecode-side: the empty array literal
    /// at MIR lowering goes through `lower_array_expr` →
    /// `emit_container_store_if_needed` which short-circuits for
    /// `ContainerStoreKind::Array` with empty operands (helpers.rs:128-130).
    /// No `StatementKind::ArrayStore` is emitted, so the
    /// `helpers.rs:687` ArrayStore walker never fires on empty literals.
    /// The conduit producer has no other source for the element kind on
    /// an empty Aggregate slot.
    ///
    /// Producer: `mir/lowering/stmt.rs::lower_var_decl` (var-decl with
    /// annotation `Array<C>` AND value `Expr::Array(items)` with
    /// `items.is_empty()`).
    /// Consumer: `compiler/helpers.rs::infer_top_level_concrete_types_from_
    /// mir_with_resolvers` (new pass before slot-move propagation).
    ///
    /// `None` (no entry) for slots that aren't empty-typed-array-literal
    /// initializations — non-empty array literals flow through the existing
    /// `ArrayStore` operand-kind inference path; absent annotation means
    /// no proven element kind and the JIT surfaces-and-stops per §2.7.7 #9
    /// forbidden Bool-default.
    pub local_typed_array_element_types:
        std::collections::HashMap<SlotId, shape_value::v2::ConcreteType>,
    /// Per-slot declared scalar `ConcreteType` for `let`-bindings whose
    /// type annotation resolves to a narrow integer width (`i8`/`i16`/
    /// `i32`/`u8`/`u16`/`u32`).
    ///
    /// ADR-006 §2.7.5 stamp-at-compile-time — R5c-2-β-γ (c)
    /// jit-narrow-wrap. The MIR `Rvalue::Use(Constant(Int(_)))` carrier
    /// is width-blind: a bare integer literal has no width, so
    /// `infer_top_level_concrete_types_from_mir` classifies every
    /// `MirConstant::Int` as `ConcreteType::I64`. Top-level `let a: i32 =
    /// 100` bindings are module bindings (not bytecode locals — see
    /// `compiler/compiler_impl_reference_model.rs:1472`), so the
    /// bytecode-compiler's per-local side-tables never carry the
    /// declared narrow width either. Without a width source the JIT
    /// declares the slot as a Cranelift `I64` variable and emits
    /// `iadd`/`isub`/`imul` at 64-bit width — overflow does not wrap to
    /// the declared width, diverging from the bytecode VM's
    /// `AddI32`/`AddTyped` truncating opcodes.
    ///
    /// This map is populated at MIR lowering for var-decls whose
    /// `type_annotation` resolves through `concrete_type_from_annotation`
    /// to one of the narrow integer scalar `ConcreteType` variants. The
    /// conduit producer
    /// (`compiler/helpers.rs::infer_top_level_concrete_types_from_mir_
    /// with_resolvers`) reads it to stamp `concrete_types[slot]` with the
    /// proven narrow width, which the JIT then projects to
    /// `NativeKind::Int32`/`Int8`/etc., declares the slot at the matching
    /// Cranelift width, and lowers arithmetic so overflow wraps.
    ///
    /// `None` (no entry) for slots without a narrow-int annotation —
    /// plain `int`/`number`/heap types are unaffected.
    ///
    /// Producer: `mir/lowering/stmt.rs::lower_var_decl`.
    /// Consumer: `compiler/helpers.rs::infer_top_level_concrete_types_
    /// from_mir_with_resolvers`.
    pub local_declared_scalar_types:
        std::collections::HashMap<SlotId, shape_value::v2::ConcreteType>,
}

/// Type information for a local variable, used for Copy/Clone inference.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LocalTypeInfo {
    /// Primitive (int, number, bool, none) — implicitly Copy, no borrow tracking.
    Copy,
    /// Heap type (String, Array, TypedObject, etc.) — requires borrow/move/clone tracking.
    NonCopy,
    /// Unknown type (will be resolved during analysis).
    Unknown,
}

impl MirFunction {
    /// Get the entry block (always block 0).
    pub fn entry_block(&self) -> BasicBlockId {
        BasicBlockId(0)
    }

    /// Iterate over all blocks.
    pub fn iter_blocks(&self) -> impl Iterator<Item = &BasicBlock> {
        self.blocks.iter()
    }

    /// Get a block by ID.
    pub fn block(&self, id: BasicBlockId) -> &BasicBlock {
        &self.blocks[id.0 as usize]
    }

    /// Linearize all statements into a flat list of points.
    /// Returns (point, block_id, statement_index) triples.
    pub fn all_points(&self) -> Vec<(Point, BasicBlockId, usize)> {
        let mut points = Vec::new();
        for block in &self.blocks {
            for (i, stmt) in block.statements.iter().enumerate() {
                points.push((stmt.point, block.id, i));
            }
        }
        points
    }
}

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

    #[test]
    fn test_place_root_local() {
        let p = Place::Field(Box::new(Place::Local(SlotId(0))), FieldIdx(1));
        assert_eq!(p.root_local(), SlotId(0));
    }

    #[test]
    fn test_place_prefix() {
        let x = Place::Local(SlotId(0));
        let xa = Place::Field(Box::new(Place::Local(SlotId(0))), FieldIdx(0));
        assert!(x.is_prefix_of(&xa));
        assert!(!xa.is_prefix_of(&x));
    }

    #[test]
    fn test_disjoint_fields_no_conflict() {
        let xa = Place::Field(Box::new(Place::Local(SlotId(0))), FieldIdx(0));
        let xb = Place::Field(Box::new(Place::Local(SlotId(0))), FieldIdx(1));
        // Disjoint fields should not overlap
        assert!(!xa.overlaps(&xb));
    }

    #[test]
    fn test_same_field_conflicts() {
        let xa1 = Place::Field(Box::new(Place::Local(SlotId(0))), FieldIdx(0));
        let xa2 = Place::Field(Box::new(Place::Local(SlotId(0))), FieldIdx(0));
        assert!(xa1.conflicts_with(&xa2));
    }

    #[test]
    fn test_different_locals_no_conflict() {
        let x = Place::Local(SlotId(0));
        let y = Place::Local(SlotId(1));
        assert!(!x.conflicts_with(&y));
    }

    #[test]
    fn test_parent_child_conflict() {
        let x = Place::Local(SlotId(0));
        let xa = Place::Field(Box::new(Place::Local(SlotId(0))), FieldIdx(0));
        assert!(x.conflicts_with(&xa));
        assert!(xa.conflicts_with(&x));
    }
}