mailang-bytecode 0.4.1

Bytecode definitions for MaìLang (no_std capable)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
//! Register-based bytecode and a stack→register translator.
//!
//! The classic compiler emits stack bytecode. A real **register VM** executes
//! three-address instructions (`Add dst, lhs, rhs`) with a flat register file.
//! This module defines that IR and a translator that lowers stack bytecode to
//! register bytecode by simulating the operand stack and assigning each stack
//! slot a virtual register.

use crate::{Bytecode, Opcode, Value};
use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;

/// Three-address register instruction. Registers are `u16` indices into a
/// flat frame-local register file. Constants live in the chunk const table.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum RegOp {
    /// `dst = src`
    Mov { dst: u16, src: u16 },
    /// `dst = constants[k]`
    LoadConst { dst: u16, k: u32 },
    /// `dst = globals[slot]`
    LoadGlobal { dst: u16, slot: u32 },
    /// `globals[slot] = src`
    StoreGlobal { slot: u32, src: u16 },
    /// `dst = upvalues[idx]`
    LoadUpvalue { dst: u16, idx: u32 },
    /// `upvalues[idx] = src`
    StoreUpvalue { idx: u32, src: u16 },
    /// `dst = lhs <op> rhs`
    Bin {
        op: BinKind,
        dst: u16,
        lhs: u16,
        rhs: u16,
    },
    /// `dst = <op> src`
    Un { op: UnKind, dst: u16, src: u16 },
    /// `dst = lhs <cmp> rhs`
    Cmp {
        op: CmpKind,
        dst: u16,
        lhs: u16,
        rhs: u16,
    },
    /// `dst = lhs <cmp> imm` (fused int immediate)
    CmpImm {
        op: CmpKind,
        dst: u16,
        lhs: u16,
        imm: i64,
    },
    /// `dst = lhs <op> imm`
    BinImm {
        op: BinKind,
        dst: u16,
        lhs: u16,
        imm: i64,
    },
    /// Unconditional jump to instruction index `target` (in this chunk).
    Jump { target: u32 },
    /// Jump if `cond` register is falsy.
    JumpIfFalse { target: u32, cond: u16 },
    /// Jump if `cond` register is truthy.
    JumpIfTrue { target: u32, cond: u16 },
    /// `dst = call(func, args[argc])` — args live in consecutive registers.
    Call {
        dst: u16,
        func: u16,
        args: u16,
        argc: u8,
    },
    /// Tail call: same as Call but reuses the frame.
    TailCall { func: u16, args: u16, argc: u8 },
    /// `return src`
    Ret { src: u16 },
    /// `dst = obj.name`
    GetProp { dst: u16, obj: u16, name: u32 },
    /// `obj.name = src`
    SetProp { obj: u16, name: u32, src: u16 },
    /// `dst = obj.name(args[argc])`
    Invoke {
        dst: u16,
        obj: u16,
        name: u32,
        args: u16,
        argc: u8,
    },
    /// `dst = [regs[start] .. start+count)`
    BuildArr { dst: u16, start: u16, count: u16 },
    /// `dst = { k/v pairs from regs[start] .. }`
    BuildMap { dst: u16, start: u16, count: u16 },
    /// `dst = obj[idx]`
    IndexGet { dst: u16, obj: u16, idx: u16 },
    /// `obj[idx] = src`
    IndexSet { obj: u16, idx: u16, src: u16 },
    /// Class / instance helpers (operand carries the same meaning as stack IR).
    CreateClass { dst: u16, k: u32 },
    CreateInstance {
        dst: u16,
        class: u16,
        args: u16,
        argc: u8,
    },
    MakeClosure {
        dst: u16,
        func: u16,
        upvals: u16,
        count: u8,
    },
    /// `dst = wrap(src)` for Ok/Err/Some
    Wrap { kind: WrapKind, dst: u16, src: u16 },
    /// Unwrap Ok/Err/Some: `dst = inner` (bool success in `flag`)
    Unwrap {
        kind: WrapKind,
        dst: u16,
        flag: u16,
        src: u16,
    },
    /// `?` operator: dst = inner or early-return
    TryQ { dst: u16, src: u16 },
    /// Current frame argc (for default-parameter prologues)
    Argc { dst: u16 },
    /// Call a known chunk by index (lowered from stack `CallDirect`).
    CallChunk {
        dst: u16,
        chunk: u32,
        args: u16,
        argc: u8,
    },
    /// No-op
    Nop,
    /// Stop and return `src`
    Halt { src: u16 },
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum BinKind {
    Add,
    Sub,
    Mul,
    Div,
    Mod,
    Pow,
    BitAnd,
    BitOr,
    BitXor,
    Shl,
    Shr,
    And,
    Or,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum UnKind {
    Neg,
    Not,
    BitNot,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum CmpKind {
    Eq,
    Ne,
    Lt,
    Le,
    Gt,
    Ge,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum WrapKind {
    Ok,
    Err,
    Some,
}

/// Parameter / `this` slot count for a chunk: the translator's starting stack
/// height ([`RegChunk::param_slots`]), so `let` locals land on their own
/// registers.
///
/// The register VM and the disassembler must agree on this, so it lives next
/// to the translator. `arity` on a `RegChunk` stays 0 for chunks reached
/// through `CallDirect` (a deep call has no `FunctionObj` to read), which is
/// why the count is recovered from the constant pool instead.
pub fn parameter_slots(bytecode: &Bytecode, chunk_idx: usize) -> u16 {
    if chunk_idx == bytecode.main_chunk {
        return 0;
    }
    let mut best: Option<usize> = None;
    for ch in &bytecode.chunks {
        for c in &ch.constants {
            if let Value::Function(f) = c {
                if f.chunk_index == chunk_idx {
                    best = Some(best.map_or(f.arity, |b: usize| b.max(f.arity)));
                }
            }
            if let Value::Class(cls) = c {
                for (_, ci) in cls.methods.iter() {
                    if *ci == chunk_idx {
                        // Method chunk without a self-describing FunctionObj:
                        // at least `this`.
                        if best.is_none() {
                            best = Some(1);
                        }
                    }
                }
            }
        }
    }
    best.unwrap_or(0) as u16
}

/// A register-mode chunk (function body), i.e. one frame layout.
///
/// Three different quantities used to share one field: the frame's window size,
/// the count of parameter slots to reserve at the bottom of the frame, and the
/// declared parameter count. They are kept apart here because they answer
/// different questions and only happen to coincide for a plain function:
///
/// * [`RegChunk::n_regs`] - how many registers the frame needs (window size);
/// * [`RegChunk::param_slots`] - how many of them are reserved for the
///   parameters and an implicit `this` (the translator's initial stack height);
/// * [`RegChunk::arity`] / [`RegChunk::required`] - the parameter-count contract
///   from the chunk's `FunctionObj`, used to check a call.
#[derive(Debug, Clone)]
pub struct RegChunk {
    pub name: String,
    pub code: Vec<RegOp>,
    pub constants: Vec<Value>,
    /// Registers the frame must allocate: the highest register index any
    /// instruction of the chunk uses, plus one.
    pub n_regs: u16,
    /// Registers reserved at the bottom of the frame for parameters and an
    /// implicit `this`: this is the translator's initial stack height, so the
    /// chunk's own `let`/`var` locals and every expression temp live at
    /// `param_slots..n_regs`.
    ///
    /// It is *not* the declared parameter count and it is not the function's
    /// arity: a method reserves an extra slot for `this`, and a chunk reached
    /// through `CallDirect` has no `FunctionObj` to ask.
    pub param_slots: u16,
    /// Declared parameter count (max) of the chunk's `FunctionObj`, used for
    /// the arity check when the call site holds the function value.
    /// Stays 0 for chunks that only `CallDirect` reaches.
    pub arity: usize,
    /// Declared required-parameter count, as [`RegChunk::arity`].
    pub required: usize,
}

impl RegChunk {
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            code: Vec::new(),
            constants: Vec::new(),
            n_regs: 0,
            param_slots: 0,
            arity: 0,
            required: 0,
        }
    }
}

/// Lower a stack instruction stream to register form.
///
/// Strategy: simulate the operand stack with **dataflow stack heights** so
/// control-flow joins (match arms, if/else, Unwrap success vs fail) get the
/// correct register indices. Registers are the frame's contiguous stack slots
/// (parameters occupy `0..param_slots`, locals and expression temps grow above).
pub struct StackToRegister<'a> {
    src_code: &'a [crate::Instruction],
    #[allow(dead_code)]
    src_consts: &'a [Value],
    out: RegChunk,
    /// Maps stack IP → register IP (for jump patching).
    ip_map: Vec<u32>,
    /// Pending (stack_target, reg_site) jumps to patch.
    jumps: Vec<(usize, usize)>,
    /// Initial stack height (= parameter / `this` slot count).
    param_slots: u16,
    /// Height before each source instruction (dataflow).
    heights: Vec<u16>,
}

impl<'a> StackToRegister<'a> {
    pub fn new(name: &str, code: &'a [crate::Instruction], consts: &'a [Value]) -> Self {
        let mut out = RegChunk::new(name);
        out.constants = consts.to_vec();
        out.arity = 0;
        out.required = 0;
        Self {
            src_code: code,
            src_consts: consts,
            out,
            ip_map: Vec::new(),
            jumps: Vec::new(),
            param_slots: 0,
            heights: Vec::new(),
        }
    }

    /// Set the frame's initial stack height: the parameter / `this` slot count
    /// the chunk was compiled with (see [`RegChunk::param_slots`]).
    pub fn with_param_slots(mut self, param_slots: u16) -> Self {
        self.param_slots = param_slots;
        self
    }

    fn emit(&mut self, op: RegOp) -> usize {
        self.out.code.push(op);
        self.out.code.len() - 1
    }

    fn use_reg(&mut self, r: u16) {
        if r + 1 > self.out.n_regs {
            self.out.n_regs = r + 1;
        }
    }

    #[allow(unused_assignments)]
    pub fn translate(mut self) -> RegChunk {
        let param_slots = self.param_slots;
        self.heights = compute_heights(self.src_code, param_slots);
        self.out.n_regs = self.out.n_regs.max(param_slots);
        self.out.param_slots = param_slots;
        for (sip, ins) in self.src_code.iter().enumerate() {
            self.ip_map.push(self.out.code.len() as u32);
            let mut sp: u16 = self.heights[sip];
            match ins.opcode {
                Opcode::Push => {
                    let k = ins.operand.unwrap_or(0);
                    let dst = sp;
                    self.use_reg(dst);
                    self.emit(RegOp::LoadConst { dst, k });
                    sp += 1;
                }
                Opcode::Pop => {
                    sp = sp.saturating_sub(1);
                }
                Opcode::Dup => {
                    let src = sp.saturating_sub(1);
                    let dst = sp;
                    self.use_reg(dst);
                    self.emit(RegOp::Mov { dst, src });
                    sp += 1;
                }
                Opcode::LoadLocal => {
                    let idx = ins.operand.unwrap_or(0) as u16;
                    let dst = sp;
                    self.use_reg(idx.max(dst));
                    self.emit(RegOp::Mov { dst, src: idx });
                    sp += 1;
                }
                Opcode::StoreLocal => {
                    let idx = ins.operand.unwrap_or(0) as u16;
                    let src = sp.saturating_sub(1);
                    self.use_reg(idx.max(src));
                    self.emit(RegOp::Mov { dst: idx, src });
                    sp = sp.saturating_sub(1);
                }
                Opcode::LoadGlobal => {
                    let slot = ins.operand.unwrap_or(0);
                    let dst = sp;
                    self.use_reg(dst);
                    self.emit(RegOp::LoadGlobal { dst, slot });
                    sp += 1;
                }
                Opcode::StoreGlobal => {
                    let slot = ins.operand.unwrap_or(0);
                    let src = sp.saturating_sub(1);
                    self.use_reg(src);
                    self.emit(RegOp::StoreGlobal { slot, src });
                    sp = sp.saturating_sub(1);
                }
                Opcode::LoadUpvalue => {
                    let idx = ins.operand.unwrap_or(0);
                    let dst = sp;
                    self.use_reg(dst);
                    self.emit(RegOp::LoadUpvalue { dst, idx });
                    sp += 1;
                }
                Opcode::StoreUpvalue => {
                    let idx = ins.operand.unwrap_or(0);
                    let src = sp.saturating_sub(1);
                    self.use_reg(src);
                    self.emit(RegOp::StoreUpvalue { idx, src });
                    sp = sp.saturating_sub(1);
                }
                Opcode::Add
                | Opcode::Sub
                | Opcode::Mul
                | Opcode::Div
                | Opcode::Mod
                | Opcode::Pow
                | Opcode::BitAnd
                | Opcode::BitOr
                | Opcode::BitXor
                | Opcode::Shl
                | Opcode::Shr
                | Opcode::And
                | Opcode::Or => {
                    let kind = bin_kind(ins.opcode);
                    let rhs = sp.saturating_sub(1);
                    let lhs = sp.saturating_sub(2);
                    let dst = lhs;
                    self.use_reg(rhs.max(dst));
                    self.emit(RegOp::Bin {
                        op: kind,
                        dst,
                        lhs,
                        rhs,
                    });
                    sp = sp.saturating_sub(1);
                }
                Opcode::AddImm
                | Opcode::SubImm
                | Opcode::MulImm
                | Opcode::EqImm
                | Opcode::NeImm
                | Opcode::LtImm
                | Opcode::LeImm
                | Opcode::GtImm
                | Opcode::GeImm => {
                    // The compiler stores immediates as `i32` bit patterns in
                    // `operand` (`i32::try_from` at emit time), so sign-extend
                    // exactly like the stack VM does. Without this, `-10` is
                    // read as `4294967286` and every `x < -10` / `x + -10`
                    // silently computes the wrong value.
                    let imm = ins.operand.unwrap_or(0) as i32 as i64;
                    let lhs = sp.saturating_sub(1);
                    let dst = lhs;
                    self.use_reg(dst);
                    let op = ins.opcode;
                    if matches!(op, Opcode::AddImm | Opcode::SubImm | Opcode::MulImm) {
                        self.emit(RegOp::BinImm {
                            op: bin_kind_imm(op),
                            dst,
                            lhs,
                            imm,
                        });
                    } else {
                        self.emit(RegOp::CmpImm {
                            op: cmp_kind_imm(op),
                            dst,
                            lhs,
                            imm,
                        });
                    }
                }
                Opcode::Neg | Opcode::Not | Opcode::BitNot => {
                    let src = sp.saturating_sub(1);
                    let dst = src;
                    self.use_reg(dst);
                    self.emit(RegOp::Un {
                        op: un_kind(ins.opcode),
                        dst,
                        src,
                    });
                }
                Opcode::Eq | Opcode::Ne | Opcode::Lt | Opcode::Le | Opcode::Gt | Opcode::Ge => {
                    let rhs = sp.saturating_sub(1);
                    let lhs = sp.saturating_sub(2);
                    let dst = lhs;
                    self.use_reg(rhs.max(dst));
                    self.emit(RegOp::Cmp {
                        op: cmp_kind(ins.opcode),
                        dst,
                        lhs,
                        rhs,
                    });
                    sp = sp.saturating_sub(1);
                }
                Opcode::Jump => {
                    let t = ins.operand.unwrap_or(0) as usize;
                    let site = self.emit(RegOp::Jump { target: 0 });
                    self.jumps.push((t, site));
                }
                Opcode::JumpIfFalse => {
                    let t = ins.operand.unwrap_or(0) as usize;
                    let cond = sp.saturating_sub(1);
                    self.use_reg(cond);
                    let site = self.emit(RegOp::JumpIfFalse { target: 0, cond });
                    self.jumps.push((t, site));
                }
                Opcode::JumpIfTrue => {
                    let t = ins.operand.unwrap_or(0) as usize;
                    let cond = sp.saturating_sub(1);
                    self.use_reg(cond);
                    let site = self.emit(RegOp::JumpIfTrue { target: 0, cond });
                    self.jumps.push((t, site));
                }
                Opcode::Call => {
                    let argc = ins.operand.unwrap_or(0) as u8;
                    let argc_us = argc as u16;
                    // stack: [func, a0, a1, …]
                    let func = sp.saturating_sub(argc_us + 1);
                    let args = func + 1;
                    let dst = func;
                    self.use_reg(sp.saturating_sub(1).max(dst));
                    self.emit(RegOp::Call {
                        dst,
                        func,
                        args,
                        argc,
                    });
                    sp = func + 1;
                }
                Opcode::TailCall => {
                    let argc = ins.operand.unwrap_or(0) as u8;
                    let argc_us = argc as u16;
                    let func = sp.saturating_sub(argc_us + 1);
                    let args = func + 1;
                    self.use_reg(sp.saturating_sub(1));
                    self.emit(RegOp::TailCall { func, args, argc });
                    sp = 0;
                }
                Opcode::Return => {
                    let src = sp.saturating_sub(1);
                    self.use_reg(src);
                    self.emit(RegOp::Ret { src });
                    sp = 0;
                }
                Opcode::GetProperty => {
                    let name = ins.operand.unwrap_or(0);
                    let obj = sp.saturating_sub(1);
                    let dst = obj;
                    self.use_reg(dst);
                    self.emit(RegOp::GetProp { dst, obj, name });
                }
                Opcode::SetProperty => {
                    let name = ins.operand.unwrap_or(0);
                    let src = sp.saturating_sub(1);
                    let obj = sp.saturating_sub(2);
                    self.use_reg(src.max(obj));
                    self.emit(RegOp::SetProp { obj, name, src });
                    // SetProperty leaves the object on the stack in the stack IR
                    // (value becomes the new stack top after consuming both).
                    // Stack IR: [obj, val] → [obj]. Our src/obj consumed val;
                    // keep obj as top: sp = obj + 1.
                    sp = obj + 1;
                }
                Opcode::Invoke => {
                    let packed = ins.operand.unwrap_or(0);
                    let argc = (packed >> 16) as u8;
                    let name = packed & 0xFFFF;
                    let argc_us = argc as u16;
                    let obj = sp.saturating_sub(argc_us + 1);
                    let args = obj + 1;
                    let dst = obj;
                    self.use_reg(sp.saturating_sub(1).max(dst));
                    self.emit(RegOp::Invoke {
                        dst,
                        obj,
                        name,
                        args,
                        argc,
                    });
                    sp = obj + 1;
                }
                Opcode::BuildArray => {
                    let count = ins.operand.unwrap_or(0) as u16;
                    let start = sp.saturating_sub(count);
                    let dst = start;
                    self.use_reg(sp.saturating_sub(1).max(dst));
                    self.emit(RegOp::BuildArr { dst, start, count });
                    sp = start + 1;
                }
                Opcode::BuildMap => {
                    let count = ins.operand.unwrap_or(0) as u16; // pairs
                    let slots = count * 2;
                    let start = sp.saturating_sub(slots);
                    let dst = start;
                    self.use_reg(sp.saturating_sub(1).max(dst));
                    self.emit(RegOp::BuildMap {
                        dst,
                        start,
                        count: slots,
                    });
                    sp = start + 1;
                }
                Opcode::IndexGet => {
                    let idx = sp.saturating_sub(1);
                    let obj = sp.saturating_sub(2);
                    let dst = obj;
                    self.use_reg(idx.max(dst));
                    self.emit(RegOp::IndexGet { dst, obj, idx });
                    sp = obj + 1;
                }
                Opcode::IndexSet => {
                    let src = sp.saturating_sub(1);
                    let idx = sp.saturating_sub(2);
                    let obj = sp.saturating_sub(3);
                    self.use_reg(src.max(obj));
                    self.emit(RegOp::IndexSet { obj, idx, src });
                    // Stack IR: [obj, idx, val] → [] after IndexSet+Pop in compiler.
                    sp = obj;
                }
                Opcode::CreateClass => {
                    let k = ins.operand.unwrap_or(0);
                    let dst = sp;
                    self.use_reg(dst);
                    self.emit(RegOp::CreateClass { dst, k });
                    sp += 1;
                }
                Opcode::CreateInstance => {
                    // Stack: [class, args...] → [instance]
                    let argc = 0u8; // class call uses Call path in stack IR
                    let _ = argc;
                    let class = sp.saturating_sub(1);
                    let dst = class;
                    self.use_reg(dst);
                    self.emit(RegOp::CreateInstance {
                        dst,
                        class,
                        args: class,
                        argc: 0,
                    });
                }
                Opcode::GetMethod => {
                    let name = ins.operand.unwrap_or(0);
                    let obj = sp.saturating_sub(1);
                    let dst = obj;
                    self.use_reg(dst);
                    self.emit(RegOp::GetProp { dst, obj, name });
                }
                Opcode::MatchPattern => {
                    // Stack VM pushes Bool(true); keep the same effect.
                    let dst = sp;
                    self.use_reg(dst);
                    let k = {
                        // Reuse/add a true constant.
                        let v = Value::Bool(true);
                        if let Some(i) = self.out.constants.iter().position(|c| c == &v) {
                            i as u32
                        } else {
                            self.out.constants.push(v);
                            (self.out.constants.len() - 1) as u32
                        }
                    };
                    self.emit(RegOp::LoadConst { dst, k });
                }
                Opcode::MakeClosure => {
                    let count = ins.operand.unwrap_or(0) as u8;
                    let count_us = count as u16;
                    let upvals = sp.saturating_sub(count_us + 1);
                    let func = sp.saturating_sub(count_us + 1);
                    // stack: [func, uv…]
                    let func_r = sp - count_us - 1;
                    let upvals_r = func_r + 1;
                    let dst = func_r;
                    self.use_reg(sp.saturating_sub(1).max(dst));
                    self.emit(RegOp::MakeClosure {
                        dst,
                        func: func_r,
                        upvals: upvals_r,
                        count,
                    });
                    sp = func_r + 1;
                    let _ = (upvals, func);
                }
                Opcode::Throw => {
                    let src = sp.saturating_sub(1);
                    self.use_reg(src);
                    self.emit(RegOp::Ret { src });
                    sp = 0;
                }
                Opcode::TryBegin | Opcode::TryEnd | Opcode::Nop => {
                    self.emit(RegOp::Nop);
                }
                Opcode::WrapOk | Opcode::WrapErr | Opcode::WrapSome => {
                    let kind = match ins.opcode {
                        Opcode::WrapOk => WrapKind::Ok,
                        Opcode::WrapErr => WrapKind::Err,
                        _ => WrapKind::Some,
                    };
                    let src = sp.saturating_sub(1);
                    let dst = src;
                    self.use_reg(dst);
                    self.emit(RegOp::Wrap { kind, dst, src });
                }
                Opcode::UnwrapOk | Opcode::UnwrapErr | Opcode::UnwrapSome => {
                    let kind = match ins.opcode {
                        Opcode::UnwrapOk => WrapKind::Ok,
                        Opcode::UnwrapErr => WrapKind::Err,
                        _ => WrapKind::Some,
                    };
                    // Success: [inner, true] (dst, flag). Fail: [false] at dst,
                    // and flag is also set false so a following JumpIfFalse
                    // (which peeks the success-layout top) still branches.
                    let src = sp.saturating_sub(1);
                    let dst = src;
                    let flag = src + 1;
                    self.use_reg(flag);
                    self.emit(RegOp::Unwrap {
                        kind,
                        dst,
                        flag,
                        src,
                    });
                    // Dataflow already models out-height as +1 (success layout).
                    let _ = sp;
                }
                Opcode::Try => {
                    let src = sp.saturating_sub(1);
                    let dst = src;
                    self.use_reg(dst);
                    self.emit(RegOp::TryQ { dst, src });
                }
                Opcode::Argc => {
                    let dst = sp;
                    self.use_reg(dst);
                    self.emit(RegOp::Argc { dst });
                    sp += 1;
                }
                Opcode::Slide => {
                    // Keep the top of the window, drop the `n` values below it
                    // (`match` arm cleanup: the scrutinee temp and the pattern
                    // bindings sit under the arm's result).
                    let n = ins.operand.unwrap_or(0) as u16;
                    if n > 0 {
                        let src = sp.saturating_sub(1);
                        let dst = src.saturating_sub(n);
                        self.use_reg(src.max(dst));
                        self.emit(RegOp::Mov { dst, src });
                        sp = sp.saturating_sub(n);
                    }
                }
                Opcode::Halt => {
                    let src = sp.saturating_sub(1);
                    self.use_reg(src);
                    self.emit(RegOp::Halt { src });
                    sp = 0;
                }
                Opcode::CallDirect => {
                    let packed = ins.operand.unwrap_or(0);
                    let chunk = packed >> 16;
                    let argc = (packed & 0xFFFF) as u8;
                    let argc_us = argc as u16;
                    // Stack: [args…] only (no func slot) in CallDirect
                    let args = sp.saturating_sub(argc_us);
                    let dst = args;
                    self.use_reg(sp.saturating_sub(1).max(dst));
                    self.emit(RegOp::CallChunk {
                        dst,
                        chunk,
                        args,
                        argc,
                    });
                    sp = args + 1;
                }
            }
        }
        // Patch jumps
        let mut code = core::mem::take(&mut self.out.code);
        let ip_map = self.ip_map.clone();
        let jumps = self.jumps.clone();
        for (stack_target, site) in jumps {
            let reg_target = if stack_target < ip_map.len() {
                ip_map[stack_target]
            } else {
                code.len() as u32
            };
            match &mut code[site] {
                RegOp::Jump { ref mut target } => *target = reg_target,
                RegOp::JumpIfFalse { ref mut target, .. } => *target = reg_target,
                RegOp::JumpIfTrue { ref mut target, .. } => *target = reg_target,
                _ => {}
            }
        }
        self.out.code = code;
        self.out
    }

    /// Declare parameter counts (for CallChunk arity checks).
    pub fn with_arity(self, arity: usize, required: usize) -> RegChunk {
        let mut c = self.translate();
        c.arity = arity;
        c.required = required;
        c
    }

    pub fn translate_named(self) -> RegChunk {
        self.translate()
    }
}

fn bin_kind(op: Opcode) -> BinKind {
    match op {
        Opcode::Add | Opcode::AddImm => BinKind::Add,
        Opcode::Sub | Opcode::SubImm => BinKind::Sub,
        Opcode::Mul | Opcode::MulImm => BinKind::Mul,
        Opcode::Div => BinKind::Div,
        Opcode::Mod => BinKind::Mod,
        Opcode::Pow => BinKind::Pow,
        Opcode::BitAnd => BinKind::BitAnd,
        Opcode::BitOr => BinKind::BitOr,
        Opcode::BitXor => BinKind::BitXor,
        Opcode::Shl => BinKind::Shl,
        Opcode::Shr => BinKind::Shr,
        Opcode::And => BinKind::And,
        Opcode::Or => BinKind::Or,
        _ => BinKind::Add,
    }
}

fn bin_kind_imm(op: Opcode) -> BinKind {
    match op {
        Opcode::SubImm => BinKind::Sub,
        Opcode::MulImm => BinKind::Mul,
        _ => BinKind::Add,
    }
}

fn cmp_kind(op: Opcode) -> CmpKind {
    match op {
        Opcode::Eq | Opcode::EqImm => CmpKind::Eq,
        Opcode::Ne | Opcode::NeImm => CmpKind::Ne,
        Opcode::Lt | Opcode::LtImm => CmpKind::Lt,
        Opcode::Le | Opcode::LeImm => CmpKind::Le,
        Opcode::Gt | Opcode::GtImm => CmpKind::Gt,
        Opcode::Ge | Opcode::GeImm => CmpKind::Ge,
        _ => CmpKind::Eq,
    }
}

fn cmp_kind_imm(op: Opcode) -> CmpKind {
    cmp_kind(op)
}

fn un_kind(op: Opcode) -> UnKind {
    match op {
        Opcode::Not => UnKind::Not,
        Opcode::BitNot => UnKind::BitNot,
        _ => UnKind::Neg,
    }
}

fn is_unwrap(op: Opcode) -> bool {
    matches!(
        op,
        Opcode::UnwrapOk | Opcode::UnwrapErr | Opcode::UnwrapSome
    )
}

/// Stack height after `op` given height `h` before it (success layout for Unwrap).
fn stack_out(op: Opcode, h: u16, operand: Option<u32>) -> u16 {
    match op {
        Opcode::Push
        | Opcode::Dup
        | Opcode::LoadLocal
        | Opcode::LoadGlobal
        | Opcode::LoadUpvalue
        | Opcode::Argc
        | Opcode::CreateClass
        | Opcode::CreateInstance
        | Opcode::GetMethod
        | Opcode::MatchPattern => h.saturating_add(1),
        Opcode::Pop | Opcode::StoreGlobal | Opcode::StoreUpvalue | Opcode::Throw => {
            h.saturating_sub(1)
        }
        Opcode::Slide => h.saturating_sub(operand.unwrap_or(0) as u16),
        Opcode::StoreLocal => {
            let idx = operand.unwrap_or(0) as u16;
            let after = h.saturating_sub(1);
            if idx >= after {
                idx + 1
            } else {
                after
            }
        }
        Opcode::Add
        | Opcode::Sub
        | Opcode::Mul
        | Opcode::Div
        | Opcode::Mod
        | Opcode::Pow
        | Opcode::BitAnd
        | Opcode::BitOr
        | Opcode::BitXor
        | Opcode::Shl
        | Opcode::Shr
        | Opcode::And
        | Opcode::Or
        | Opcode::Eq
        | Opcode::Ne
        | Opcode::Lt
        | Opcode::Le
        | Opcode::Gt
        | Opcode::Ge
        | Opcode::IndexGet => h.saturating_sub(1),
        Opcode::IndexSet => h.saturating_sub(2),
        Opcode::Call => {
            let argc = operand.unwrap_or(0) as u16;
            // pop func + argc, push result
            h.saturating_sub(argc + 1).saturating_add(1)
        }
        Opcode::CallDirect => {
            let argc = operand.unwrap_or(0) as u16;
            h.saturating_sub(argc).saturating_add(1)
        }
        Opcode::Invoke => {
            let packed = operand.unwrap_or(0);
            let argc = (packed >> 16) as u16;
            h.saturating_sub(argc + 1).saturating_add(1)
        }
        Opcode::BuildArray => {
            let count = operand.unwrap_or(0) as u16;
            h.saturating_sub(count).saturating_add(1)
        }
        Opcode::BuildMap => {
            let pairs = operand.unwrap_or(0) as u16;
            h.saturating_sub(pairs * 2).saturating_add(1)
        }
        Opcode::SetProperty => h.saturating_sub(1),
        // pop object, push property value → net 0
        Opcode::GetProperty => h,
        Opcode::MakeClosure => {
            let count = operand.unwrap_or(0) as u16;
            h.saturating_sub(count + 1).saturating_add(1)
        }
        Opcode::WrapOk | Opcode::WrapErr | Opcode::WrapSome => h,
        // Success layout: pop 1, push 2 → +1. Fail path is handled by the
        // JumpIfFalse taken-edge rule (one less value).
        Opcode::UnwrapOk | Opcode::UnwrapErr | Opcode::UnwrapSome => h.saturating_add(1),
        Opcode::Try => h,
        Opcode::AddImm
        | Opcode::SubImm
        | Opcode::MulImm
        | Opcode::EqImm
        | Opcode::NeImm
        | Opcode::LtImm
        | Opcode::LeImm
        | Opcode::GtImm
        | Opcode::GeImm
        | Opcode::Neg
        | Opcode::Not
        | Opcode::BitNot
        | Opcode::Jump
        | Opcode::JumpIfFalse
        | Opcode::JumpIfTrue
        | Opcode::TryBegin
        | Opcode::TryEnd
        | Opcode::Nop => h,
        Opcode::Return | Opcode::Halt | Opcode::TailCall => h,
    }
}

/// Dataflow stack height before each instruction.
fn compute_heights(code: &[crate::Instruction], param_slots: u16) -> Vec<u16> {
    let n = code.len();
    if n == 0 {
        return Vec::new();
    }
    let mut height = vec![u16::MAX; n];
    let mut work = alloc::collections::VecDeque::new();
    height[0] = param_slots;
    work.push_back(0usize);

    while let Some(ip) = work.pop_front() {
        if ip >= n {
            continue;
        }
        let h = height[ip];
        let ins = &code[ip];
        let out = stack_out(ins.opcode, h, ins.operand);
        match ins.opcode {
            Opcode::Jump => {
                let t = ins.operand.unwrap_or(0) as usize;
                if t < n {
                    let cur = height[t];
                    if cur == u16::MAX {
                        height[t] = out;
                        work.push_back(t);
                    } else if cur != out {
                        let m = cur.max(out);
                        if m != cur {
                            height[t] = m;
                            work.push_back(t);
                        }
                    }
                }
            }
            Opcode::JumpIfFalse | Opcode::JumpIfTrue => {
                // Peeks top; both edges keep `out` unless the previous op was
                // Unwrap, whose fail path has one fewer value.
                let taken = if ip > 0 && is_unwrap(code[ip - 1].opcode) {
                    out.saturating_sub(1)
                } else {
                    out
                };
                // fallthrough
                let ft = ip + 1;
                if ft < n {
                    let cur = height[ft];
                    if cur == u16::MAX {
                        height[ft] = out;
                        work.push_back(ft);
                    } else if cur != out {
                        let m = cur.max(out);
                        if m != cur {
                            height[ft] = m;
                            work.push_back(ft);
                        }
                    }
                }
                let t = ins.operand.unwrap_or(0) as usize;
                if t < n {
                    let cur = height[t];
                    if cur == u16::MAX {
                        height[t] = taken;
                        work.push_back(t);
                    } else if cur != taken {
                        let m = cur.max(taken);
                        if m != cur {
                            height[t] = m;
                            work.push_back(t);
                        }
                    }
                }
            }
            // A frame-exiting instruction has no successor: `Return`, `Halt`,
            // `TailCall` and `Throw` never fall through to `ip + 1`. Letting
            // them propagate a height there (the old code did) meant that the
            // *unreachable* instruction after an early `return` joined the
            // height of the taken branch into code that the fall-through path
            // also reaches — e.g. `if c { return x } var total = …` — so every
            // register above the parameter slots shifted by one and the
            // function's own locals were read from (and written to) the wrong
            // register. Instructions that nothing reaches keep the
            // `param_slots` fallback applied at the end of this function.
            Opcode::Return | Opcode::Halt | Opcode::TailCall | Opcode::Throw => {}
            _ => {
                let ft = ip + 1;
                if ft < n {
                    let cur = height[ft];
                    if cur == u16::MAX {
                        height[ft] = out;
                        work.push_back(ft);
                    } else if cur != out {
                        let m = cur.max(out);
                        if m != cur {
                            height[ft] = m;
                            work.push_back(ft);
                        }
                    }
                }
            }
        }
    }

    for h in height.iter_mut() {
        if *h == u16::MAX {
            *h = param_slots;
        }
    }
    height
}