Skip to main content

vihaco_cpu/
component.rs

1// SPDX-FileCopyrightText: 2026 The vihaco Authors
2// SPDX-License-Identifier: MIT
3
4#[cfg(not(feature = "typed-declarations"))]
5use crate::RuntimeInstruction;
6use crate::StepOutcome;
7use crate::Word;
8use crate::data::CPU;
9use crate::word::*;
10use eyre::Result;
11#[cfg(not(feature = "typed-declarations"))]
12use vihaco::Effects;
13#[cfg(not(feature = "typed-declarations"))]
14use vihaco::dispatch;
15use vihaco::{frame::Frame, traits::*};
16
17impl Reset for CPU {
18    fn reset(&mut self) {
19        self.frames.clear();
20        self.clear_heap();
21        self.stack.clear();
22        self.span = (0, 0, 0);
23        self.pending_pc = None;
24        self.current_pc = 0;
25        self.return_values.clear();
26    }
27}
28
29#[cfg(not(feature = "typed-declarations"))]
30impl CPU {
31    #[inline(always)]
32    fn execute_generated(
33        &mut self,
34        inst: &RuntimeInstruction,
35        msg: CPUMessage,
36    ) -> eyre::Result<Effects<StepOutcome>> {
37        use RuntimeInstruction::*;
38
39        self.clear_pending_pc();
40        match (inst, msg) {
41            (Print, CPUMessage::Print(text)) => {
42                self.stack_pop()?;
43                drop(text);
44                return Ok(Effects::one(StepOutcome::Continue));
45            }
46            (Print, _) => return Err(eyre::eyre!("Print requires CPUMessage::Print")),
47            (_, CPUMessage::Print(_)) => {
48                return Err(eyre::eyre!(
49                    "CPUMessage::Print is only valid for Print instruction"
50                ));
51            }
52            (Call(arity, target), CPUMessage::FunctionInfo { local_count, .. }) => {
53                return self.op_call(*arity, *target, local_count).map(Effects::one);
54            }
55            (
56                IndirectCall,
57                CPUMessage::FunctionInfo {
58                    arity,
59                    start_address,
60                    local_count,
61                },
62            ) => {
63                return self
64                    .op_indirect_call(arity, start_address, local_count)
65                    .map(Effects::one);
66            }
67            (_, CPUMessage::FunctionInfo { .. }) => {
68                return Err(eyre::eyre!(
69                    "CPUMessage::FunctionInfo is only valid for call instructions"
70                ));
71            }
72            (_, CPUMessage::None) => {}
73        }
74
75        let outcome = match inst {
76            Span(file, start, end) => self.op_span(*file, *start, *end),
77            Label(_) | FunctionStart | FunctionEnd => Ok(StepOutcome::Continue),
78            Breakpoint => Ok(StepOutcome::Breakpoint),
79            Branch(target) => self.op_branch(*target),
80            ConditionalBranch(true_target, false_target) => {
81                self.op_conditional_branch(*true_target, *false_target)
82            }
83            Return(keep) => self.op_return(*keep),
84            Call(..) | IndirectCall => Err(eyre::eyre!("call requires CPUMessage::FunctionInfo")),
85            Halt => Ok(StepOutcome::Halt),
86            Print => Err(eyre::eyre!(
87                "Print must be handled via execute with CPUMessage::Print"
88            )),
89            LoadI32(addr) => self.op_load(*addr),
90            LoadI64(addr) => self.op_load(*addr),
91            LoadU32(addr) => self.op_load(*addr),
92            LoadU64(addr) => self.op_load(*addr),
93            LoadF32(addr) => self.op_load(*addr),
94            LoadF64(addr) => self.op_load(*addr),
95            LoadBool(addr) => self.op_load(*addr),
96            StoreI32(addr) => self.op_store(*addr),
97            StoreI64(addr) => self.op_store(*addr),
98            StoreU32(addr) => self.op_store(*addr),
99            StoreU64(addr) => self.op_store(*addr),
100            StoreF32(addr) => self.op_store(*addr),
101            StoreF64(addr) => self.op_store(*addr),
102            StoreBool(addr) => self.op_store(*addr),
103            Dup => self.op_dup(),
104            HeapAlloc(n_elements) => self.op_heap_alloc(*n_elements),
105            GetItem => self.op_get_item(),
106            HeapDealloc => self.op_heap_dealloc(),
107            HeapReserve => self.op_heap_reserve(),
108            HeapPush => self.op_heap_push(),
109            HeapLen => self.op_heap_len(),
110            ConstI32(v) | ConstI64(v) | ConstU32(v) | ConstU64(v) | ConstF32(v) | ConstF64(v)
111            | ConstBool(v) | ConstString(v) | ConstFunctionRef(v) | ConstHeapRef(v) => {
112                self.op_const(*v)
113            }
114            AddI32 => self.add_i32(),
115            AddI64 => self.add_i64(),
116            AddU32 => self.add_u32(),
117            AddU64 => self.add_u64(),
118            AddF32 => self.add_f32(),
119            AddF64 => self.add_f64(),
120            SubI32 => self.sub_i32(),
121            SubI64 => self.sub_i64(),
122            SubU32 => self.sub_u32(),
123            SubU64 => self.sub_u64(),
124            SubF32 => self.sub_f32(),
125            SubF64 => self.sub_f64(),
126            MulI32 => self.mul_i32(),
127            MulI64 => self.mul_i64(),
128            MulU32 => self.mul_u32(),
129            MulU64 => self.mul_u64(),
130            MulF32 => self.mul_f32(),
131            MulF64 => self.mul_f64(),
132            DivI32 => self.div_i32(),
133            DivI64 => self.div_i64(),
134            DivU32 => self.div_u32(),
135            DivU64 => self.div_u64(),
136            DivF32 => self.div_f32(),
137            DivF64 => self.div_f64(),
138            RemI32 => self.rem_i32(),
139            RemI64 => self.rem_i64(),
140            RemU32 => self.rem_u32(),
141            RemU64 => self.rem_u64(),
142            RemF32 => self.rem_f32(),
143            RemF64 => self.rem_f64(),
144            NegI32 => self.neg_i32(),
145            NegI64 => self.neg_i64(),
146            NegF32 => self.neg_f32(),
147            NegF64 => self.neg_f64(),
148            ShlI32 => self.shl_i32(),
149            ShlI64 => self.shl_i64(),
150            ShlU32 => self.shl_u32(),
151            ShlU64 => self.shl_u64(),
152            ShrI32 => self.shr_i32(),
153            ShrI64 => self.shr_i64(),
154            ShrU32 => self.shr_u32(),
155            ShrU64 => self.shr_u64(),
156            RolI32 => self.rol_i32(),
157            RolI64 => self.rol_i64(),
158            RolU32 => self.rol_u32(),
159            RolU64 => self.rol_u64(),
160            RorI32 => self.ror_i32(),
161            RorI64 => self.ror_i64(),
162            RorU32 => self.ror_u32(),
163            RorU64 => self.ror_u64(),
164            BitAndI32 => self.bitand_i32(),
165            BitAndI64 => self.bitand_i64(),
166            BitAndU32 => self.bitand_u32(),
167            BitAndU64 => self.bitand_u64(),
168            BitOrI32 => self.bitor_i32(),
169            BitOrI64 => self.bitor_i64(),
170            BitOrU32 => self.bitor_u32(),
171            BitOrU64 => self.bitor_u64(),
172            BitXorI32 => self.bitxor_i32(),
173            BitXorI64 => self.bitxor_i64(),
174            BitXorU32 => self.bitxor_u32(),
175            BitXorU64 => self.bitxor_u64(),
176            Not => self.op_not(),
177            And => self.op_and(),
178            Or => self.op_or(),
179            Xor => self.op_xor(),
180            EqI32 => self.eq_i32(),
181            EqI64 => self.eq_i64(),
182            EqU32 => self.eq_u32(),
183            EqU64 => self.eq_u64(),
184            EqF32 => self.eq_f32(),
185            EqF64 => self.eq_f64(),
186            NeI32 => self.ne_i32(),
187            NeI64 => self.ne_i64(),
188            NeU32 => self.ne_u32(),
189            NeU64 => self.ne_u64(),
190            NeF32 => self.ne_f32(),
191            NeF64 => self.ne_f64(),
192            LtI32 => self.lt_i32(),
193            LtI64 => self.lt_i64(),
194            LtU32 => self.lt_u32(),
195            LtU64 => self.lt_u64(),
196            LtF32 => self.lt_f32(),
197            LtF64 => self.lt_f64(),
198            GtI32 => self.gt_i32(),
199            GtI64 => self.gt_i64(),
200            GtU32 => self.gt_u32(),
201            GtU64 => self.gt_u64(),
202            GtF32 => self.gt_f32(),
203            GtF64 => self.gt_f64(),
204            LeI32 => self.le_i32(),
205            LeI64 => self.le_i64(),
206            LeU32 => self.le_u32(),
207            LeU64 => self.le_u64(),
208            LeF32 => self.le_f32(),
209            LeF64 => self.le_f64(),
210            GeI32 => self.ge_i32(),
211            GeI64 => self.ge_i64(),
212            GeU32 => self.ge_u32(),
213            GeU64 => self.ge_u64(),
214            GeF32 => self.ge_f32(),
215            GeF64 => self.ge_f64(),
216        }?;
217        Ok(Effects::one(outcome))
218    }
219}
220
221#[cfg(not(feature = "typed-declarations"))]
222#[derive(Debug, Clone, PartialEq, vihaco::Message)]
223pub enum CPUMessage {
224    None,
225    /// Target metadata selected by the composite for the executing CPU device.
226    FunctionInfo {
227        arity: u32,
228        start_address: u32,
229        local_count: u32,
230    },
231    Print(String),
232}
233
234#[cfg(not(feature = "typed-declarations"))]
235#[dispatch(instruction = RuntimeInstruction, message = CPUMessage, effect = StepOutcome)]
236impl CPU {
237    fn execute(
238        &mut self,
239        inst: &RuntimeInstruction,
240        msg: CPUMessage,
241    ) -> eyre::Result<Effects<StepOutcome>> {
242        self.execute_generated(inst, msg)
243    }
244}
245
246impl CPU {
247    #[cfg(not(feature = "typed-declarations"))]
248    pub fn op_span(&mut self, file: u32, start: u32, end: u32) -> eyre::Result<StepOutcome> {
249        self.span = (file, start, end);
250        Ok(StepOutcome::Continue)
251    }
252
253    #[cfg(not(feature = "typed-declarations"))]
254    pub fn op_branch(&mut self, target: u32) -> eyre::Result<StepOutcome> {
255        self.set_pending_pc(target);
256        Ok(StepOutcome::Continue)
257    }
258
259    #[cfg(not(feature = "typed-declarations"))]
260    pub fn op_conditional_branch(
261        &mut self,
262        true_target: u32,
263        false_target: u32,
264    ) -> eyre::Result<StepOutcome> {
265        let cond = self.stack_pop()?;
266        match canonical_bool(cond)? {
267            true => {
268                self.set_pending_pc(true_target);
269                Ok(StepOutcome::Continue)
270            }
271            false => {
272                self.set_pending_pc(false_target);
273                Ok(StepOutcome::Continue)
274            }
275        }
276    }
277
278    #[cfg(not(feature = "typed-declarations"))]
279    pub fn op_return(&mut self, keep: u32) -> eyre::Result<StepOutcome> {
280        let frame = *self.get_frame()?;
281        let available = self
282            .stack
283            .len()
284            .checked_sub(frame.operands_index())
285            .ok_or_else(|| eyre::eyre!("frame locals out of bounds"))?;
286        if available < keep as usize {
287            return Err(eyre::eyre!("not enough values to return"));
288        }
289
290        self.pop_frame()?;
291        // Collect return values before truncating
292        let top = self.stack.len() - keep as usize;
293        let return_values: Vec<Word> = self.stack[top..].to_vec();
294        self.stack.drain(frame.base..top);
295
296        if self.get_frame().is_err() {
297            // No more frames - program is returning
298            self.set_return_values(return_values);
299            Ok(StepOutcome::Return)
300        } else {
301            self.set_pending_pc(frame.ret_pc);
302            Ok(StepOutcome::Continue)
303        }
304    }
305
306    /// Start a program function from arguments already on the operand stack.
307    ///
308    /// Push the entry arguments before calling this method, then begin execution
309    /// at the pending PC returned by `take_pending_pc`. `local_count`
310    /// includes parameters and comes from the composite's function metadata.
311    ///
312    /// # Errors
313    /// Returns an error if a function is already active, for insufficient
314    /// operand arguments, a local count
315    /// smaller than the arity, or an overflowing frame size or return address.
316    pub fn start_function(
317        &mut self,
318        arity: u32,
319        target: u32,
320        local_count: u32,
321        function: usize,
322    ) -> eyre::Result<StepOutcome> {
323        eyre::ensure!(self.frames.is_empty(), "a function is already active");
324        self.enter_function(arity, target, local_count, Some(function))
325    }
326
327    /// Shared frame setup for program entry and call instructions.
328    pub(crate) fn enter_function(
329        &mut self,
330        arity: u32,
331        target: u32,
332        local_count: u32,
333        function: Option<usize>,
334    ) -> eyre::Result<StepOutcome> {
335        self.require_operands(arity as usize)?;
336        self.ensure_local_count_is_at_least_arity(arity, local_count)?;
337        let base = self.stack.len() - arity as usize;
338        let end = base
339            .checked_add(local_count as usize)
340            .ok_or_else(|| eyre::eyre!("frame size overflow"))?;
341        let ret_pc = if self.frames.is_empty() {
342            0
343        } else {
344            self.current_pc
345                .checked_add(1)
346                .ok_or_else(|| eyre::eyre!("return address overflow"))?
347        };
348        self.stack.resize(end, 0);
349        self.push_frame(Frame {
350            base,
351            local_count: local_count as usize,
352            span: self.span,
353            function,
354            ret_pc,
355        });
356        self.set_pending_pc(target);
357        Ok(StepOutcome::Continue)
358    }
359
360    #[cfg(not(feature = "typed-declarations"))]
361    pub fn op_call(
362        &mut self,
363        arity: u32,
364        target: u32,
365        local_count: u32,
366    ) -> eyre::Result<StepOutcome> {
367        self.enter_function(arity, target, local_count, None)
368    }
369
370    #[cfg(not(feature = "typed-declarations"))]
371    pub fn op_indirect_call(
372        &mut self,
373        arity: u32,
374        target: u32,
375        local_count: u32,
376    ) -> eyre::Result<StepOutcome> {
377        // Only the function reference is an operand; metadata comes from the message.
378        let required = (arity as usize)
379            .checked_add(1)
380            .ok_or_else(|| eyre::eyre!("argument count overflow"))?;
381        self.require_operands(required)?;
382        let function = decode_function_ref(*self.stack_top()?);
383        self.stack_pop()?;
384        self.enter_function(arity, target, local_count, Some(function as usize))
385    }
386
387    #[cfg(not(feature = "typed-declarations"))]
388    fn op_load(&mut self, addr: u32) -> eyre::Result<StepOutcome> {
389        // addr should be local to frame.
390        let value = self.get_local(addr as usize)?;
391        self.stack_push(*value);
392        Ok(StepOutcome::Continue)
393    }
394
395    #[cfg(not(feature = "typed-declarations"))]
396    pub fn op_store(&mut self, addr: u32) -> Result<StepOutcome> {
397        let address = self.local_address(addr as usize)?;
398        let value: Word = self.stack_pop()?;
399        *self
400            .stack
401            .get_mut(address)
402            .ok_or_else(|| eyre::eyre!("local index out of bounds"))? = value;
403        Ok(StepOutcome::Continue)
404    }
405
406    #[cfg(not(feature = "typed-declarations"))]
407    pub fn op_dup(&mut self) -> Result<StepOutcome> {
408        let v = *self.stack_top()?;
409        self.stack.push(v);
410        Ok(StepOutcome::Continue)
411    }
412
413    #[cfg(not(feature = "typed-declarations"))]
414    pub fn op_heap_alloc(&mut self, n_elements: u32) -> Result<StepOutcome> {
415        let n: usize = n_elements as usize;
416        self.require_operands(n)?;
417        let start = self.stack.len() - n;
418        let values: Vec<Word> = self.stack.drain(start..).collect();
419        let heap_id = self.push_heap_object(values);
420        self.stack_push(encode_heap_ref(heap_id));
421        Ok(StepOutcome::Continue)
422    }
423
424    #[cfg(not(feature = "typed-declarations"))]
425    pub fn op_get_item(&mut self) -> Result<StepOutcome> {
426        let index = Self::heap_index(self.stack_pop()?)?;
427        let heap_id = decode_heap_ref(self.stack_pop()?);
428        let value = *self
429            .heap_object(heap_id)?
430            .get(index)
431            .ok_or_else(|| eyre::eyre!("heap index {} out of bounds", index))?;
432        self.stack_push(value);
433        Ok(StepOutcome::Continue)
434    }
435
436    #[cfg(not(feature = "typed-declarations"))]
437    pub fn op_heap_dealloc(&mut self) -> Result<StepOutcome> {
438        let id = decode_heap_ref(self.stack_pop()?);
439        self.dealloc_heap_object(id)?;
440        Ok(StepOutcome::Continue)
441    }
442
443    #[cfg(not(feature = "typed-declarations"))]
444    fn op_heap_reserve(&mut self) -> Result<StepOutcome> {
445        let capacity = decode_u64(self.stack_pop()?);
446        let capacity = usize::try_from(capacity)
447            .map_err(|_| eyre::eyre!("heap capacity {} does not fit in usize", capacity))?;
448        let heap_id = self.heap.reserve(capacity)?;
449        self.stack_push(encode_heap_ref(heap_id));
450        Ok(StepOutcome::Continue)
451    }
452
453    #[cfg(not(feature = "typed-declarations"))]
454    fn op_heap_push(&mut self) -> Result<StepOutcome> {
455        self.require_operands(2)?;
456        let value = self.stack_pop()?;
457        let heap_ref = self.stack_pop()?;
458        self.heap.push(decode_heap_ref(heap_ref), value)?;
459        self.stack_push(heap_ref);
460        Ok(StepOutcome::Continue)
461    }
462
463    #[cfg(not(feature = "typed-declarations"))]
464    fn op_heap_len(&mut self) -> Result<StepOutcome> {
465        let heap_id = decode_heap_ref(self.stack_pop()?);
466        let len = u64::try_from(self.heap_object(heap_id)?.len())?;
467        self.stack_push(encode_u64(len));
468        Ok(StepOutcome::Continue)
469    }
470
471    #[cfg(not(feature = "typed-declarations"))]
472    pub fn op_const(&mut self, v: Word) -> Result<StepOutcome> {
473        self.stack.push(v);
474        Ok(StepOutcome::Continue)
475    }
476
477    pub(crate) fn heap_index(value: Word) -> Result<usize> {
478        match decode_i64(value) {
479            index if index >= 0 => usize::try_from(index)
480                .map_err(|_| eyre::eyre!("heap index {} does not fit in usize", index)),
481            index => Err(eyre::eyre!(
482                "heap index must be non-negative, got {}",
483                index
484            )),
485        }
486    }
487}
488
489#[cfg(all(test, not(feature = "typed-declarations")))]
490#[allow(clippy::items_after_test_module)]
491mod tests {
492    use super::*;
493    use vihaco::{Effects, GeneratedComponent, frame::Frame, traits::StackMemory};
494    use vihaco_parser::Ident;
495
496    trait ExecuteInstruction {
497        fn execute_instruction(&mut self, instruction: RuntimeInstruction) -> Result<StepOutcome>;
498    }
499
500    impl ExecuteInstruction for CPU {
501        fn execute_instruction(&mut self, instruction: RuntimeInstruction) -> Result<StepOutcome> {
502            vihaco::expect_exactly_one_effect(GeneratedComponent::execute_generated(
503                self,
504                &instruction,
505                CPUMessage::None,
506            )?)
507        }
508    }
509
510    #[test]
511    fn cpu_generated_component_executes_instruction_without_message() {
512        let mut cpu = CPU::default();
513
514        GeneratedComponent::execute_generated(
515            &mut cpu,
516            &RuntimeInstruction::ConstI64(encode_i64(7)),
517            CPUMessage::None,
518        )
519        .unwrap();
520
521        assert_eq!(cpu.stack(), &vec![encode_i64(7)]);
522    }
523
524    #[test]
525    fn execute_instruction_applies_control_flow_without_action() {
526        let mut cpu = CPU::default();
527
528        let branch = cpu
529            .execute_instruction(RuntimeInstruction::Branch(9))
530            .unwrap();
531        assert_eq!(branch, StepOutcome::Continue);
532        assert_eq!(cpu.take_pending_pc(), Some(9));
533
534        let halt = cpu.execute_instruction(RuntimeInstruction::Halt).unwrap();
535        assert_eq!(halt, StepOutcome::Halt);
536        assert_eq!(cpu.take_pending_pc(), None);
537    }
538
539    #[test]
540    #[cfg(not(feature = "typed-declarations"))]
541    fn op_return_stores_terminal_values_in_runtime_state() {
542        let mut cpu = CPU::default();
543        cpu.push_frame(Frame {
544            base: 0,
545            local_count: 0,
546            span: (0, 0, 0),
547            function: None,
548            ret_pc: 0,
549        });
550        cpu.stack_push(encode_i64(7));
551
552        let outcome = cpu
553            .execute_instruction(RuntimeInstruction::Return(1))
554            .unwrap();
555
556        assert_eq!(outcome, StepOutcome::Return);
557        assert_eq!(cpu.return_values(), &[encode_i64(7)]);
558    }
559
560    #[test]
561    #[cfg(not(feature = "typed-declarations"))]
562    fn op_return_restores_callers_pc() {
563        let mut cpu = CPU {
564            current_pc: 10,
565            ..Default::default()
566        };
567        // Outer ("main") frame so the inner Return takes the Continue branch.
568        cpu.push_frame(Frame {
569            base: 0,
570            local_count: 0,
571            span: (0, 0, 0),
572            function: None,
573            ret_pc: 0,
574        });
575
576        // Caller would be executing `call 0, 100` at some PC; op_call sets
577        // pending_pc to the callee target.
578        GeneratedComponent::execute_generated(
579            &mut cpu,
580            &RuntimeInstruction::Call(0, 100),
581            CPUMessage::FunctionInfo {
582                arity: 0,
583                start_address: 100,
584                local_count: 0,
585            },
586        )
587        .unwrap();
588        assert_eq!(cpu.take_pending_pc(), Some(100));
589        assert_eq!(cpu.frames[1].ret_pc, 11);
590
591        // Callee returns immediately. pending_pc should be restored to the
592        // instruction after the call.
593        let outcome = cpu
594            .execute_instruction(RuntimeInstruction::Return(0))
595            .unwrap();
596        assert_eq!(outcome, StepOutcome::Continue);
597        assert_eq!(cpu.take_pending_pc(), Some(11),);
598    }
599
600    #[test]
601    #[cfg(not(feature = "typed-declarations"))]
602    fn op_indirect_call_records_return_pc_after_call_site() {
603        let mut cpu = CPU {
604            current_pc: 10,
605            ..Default::default()
606        };
607        cpu.push_frame(Frame {
608            base: 0,
609            local_count: 0,
610            span: (0, 0, 0),
611            function: None,
612            ret_pc: 0,
613        });
614
615        // The composite supplies arity/address/count; only FunctionRef is on the stack.
616        cpu.stack_push(encode_function_ref(7));
617        GeneratedComponent::execute_generated(
618            &mut cpu,
619            &RuntimeInstruction::IndirectCall,
620            CPUMessage::FunctionInfo {
621                arity: 0,
622                start_address: 100,
623                local_count: 0,
624            },
625        )
626        .unwrap();
627        assert_eq!(cpu.take_pending_pc(), Some(100));
628        assert_eq!(cpu.frames[1].ret_pc, 11);
629
630        let outcome = cpu
631            .execute_instruction(RuntimeInstruction::Return(0))
632            .unwrap();
633        assert_eq!(outcome, StepOutcome::Continue);
634        assert_eq!(cpu.take_pending_pc(), Some(11));
635    }
636
637    #[test]
638    #[cfg(not(feature = "typed-declarations"))]
639    fn op_return_keeps_bottom_of_frame_when_callee_leaves_scratch() {
640        let mut cpu = CPU::default();
641        // Outer frame so Return takes the Continue branch.
642        cpu.push_frame(Frame {
643            base: 0,
644            local_count: 0,
645            span: (0, 0, 0),
646            function: None,
647            ret_pc: 0,
648        });
649
650        // Simulate a callee frame holding [scratch_a, scratch_b, return_val]
651        // where only `return_val` (the top) should survive `ret 1`.
652        cpu.push_frame(Frame {
653            base: 0,
654            local_count: 0,
655            span: (0, 0, 0),
656            function: None,
657            ret_pc: 0,
658        });
659        cpu.stack_push(encode_i64(111)); // scratch — bottom of callee frame
660        cpu.stack_push(encode_i64(222)); // scratch — middle
661        cpu.stack_push(encode_i64(999)); // intended return value — top
662
663        let outcome = cpu
664            .execute_instruction(RuntimeInstruction::Return(1))
665            .unwrap();
666        assert_eq!(outcome, StepOutcome::Continue);
667
668        assert_eq!(cpu.stack(), &vec![encode_i64(999)],);
669    }
670
671    #[test]
672    #[cfg(not(feature = "typed-declarations"))]
673    fn op_heap_alloc_preserves_natural_push_order_and_returns_heap_ref() {
674        let mut cpu = CPU::default();
675        cpu.stack_push(encode_i64(10));
676        cpu.stack_push(encode_i64(20));
677        cpu.stack_push(encode_i64(30));
678
679        let outcome = cpu
680            .execute_instruction(RuntimeInstruction::HeapAlloc(3))
681            .unwrap();
682
683        assert_eq!(outcome, StepOutcome::Continue);
684        assert_eq!(cpu.stack(), &vec![encode_heap_ref(0)]);
685        assert_eq!(
686            cpu.heap_object(0).unwrap(),
687            &[encode_i64(10), encode_i64(20), encode_i64(30)]
688        );
689    }
690
691    #[test]
692    #[cfg(not(feature = "typed-declarations"))]
693    fn op_heap_alloc_supports_empty_heap_objects() {
694        let mut cpu = CPU::default();
695
696        let outcome = cpu
697            .execute_instruction(RuntimeInstruction::HeapAlloc(0))
698            .unwrap();
699
700        assert_eq!(outcome, StepOutcome::Continue);
701        assert_eq!(cpu.stack(), &vec![encode_heap_ref(0)]);
702        assert_eq!(cpu.heap_object(0).unwrap(), &[] as &[Word]);
703    }
704
705    #[test]
706    fn reserved_heap_appends_in_order_and_returns_same_reference() {
707        let mut cpu = CPU::default();
708        cpu.stack_push(encode_u32(2));
709        assert_eq!(
710            cpu.execute_instruction(RuntimeInstruction::HeapReserve)
711                .unwrap(),
712            StepOutcome::Continue
713        );
714        let heap_ref = *cpu.stack_top().unwrap();
715        assert_eq!(cpu.heap_object(decode_heap_ref(heap_ref)).unwrap(), &[]);
716
717        for value in [10, 20] {
718            cpu.stack_push(encode_i64(value));
719            assert_eq!(
720                cpu.execute_instruction(RuntimeInstruction::HeapPush)
721                    .unwrap(),
722                StepOutcome::Continue
723            );
724            assert_eq!(cpu.stack(), &[heap_ref]);
725        }
726        assert_eq!(
727            cpu.heap_object(decode_heap_ref(heap_ref)).unwrap(),
728            &[encode_i64(10), encode_i64(20)]
729        );
730
731        cpu.stack_push(encode_i64(30));
732        let err = cpu
733            .execute_instruction(RuntimeInstruction::HeapPush)
734            .unwrap_err();
735        assert!(err.to_string().contains("full"));
736        assert_eq!(
737            cpu.heap_object(decode_heap_ref(heap_ref)).unwrap(),
738            &[encode_i64(10), encode_i64(20)]
739        );
740
741        cpu.stack_push(heap_ref);
742        cpu.stack_push(encode_u32(1));
743        cpu.execute_instruction(RuntimeInstruction::GetItem)
744            .unwrap();
745        assert_eq!(cpu.stack(), &[encode_i64(20)]);
746    }
747
748    #[test]
749    fn heap_len_consumes_reference_and_preserves_other_stack_values() {
750        for values in [vec![], vec![encode_i64(10), encode_i64(20)]] {
751            let mut cpu = CPU::default();
752            let heap_id = cpu.push_heap_object(values.clone());
753            cpu.stack_push(encode_i64(42));
754            cpu.stack_push(encode_heap_ref(heap_id));
755
756            let outcome = cpu
757                .execute_instruction(RuntimeInstruction::HeapLen)
758                .unwrap();
759
760            assert_eq!(outcome, StepOutcome::Continue);
761            assert_eq!(
762                cpu.stack(),
763                &[encode_i64(42), encode_u64(values.len() as u64)]
764            );
765            assert_eq!(cpu.heap_object(heap_id).unwrap(), values);
766        }
767    }
768
769    #[test]
770    fn heap_len_reports_current_length_of_reserved_object() {
771        let mut cpu = CPU::default();
772        cpu.stack_push(encode_u64(3));
773        cpu.execute_instruction(RuntimeInstruction::HeapReserve)
774            .unwrap();
775        let heap_ref = *cpu.stack_top().unwrap();
776
777        cpu.execute_instruction(RuntimeInstruction::HeapLen)
778            .unwrap();
779        assert_eq!(cpu.stack_pop().unwrap(), encode_u64(0));
780
781        cpu.stack_push(heap_ref);
782        cpu.stack_push(encode_i64(10));
783        cpu.execute_instruction(RuntimeInstruction::HeapPush)
784            .unwrap();
785        cpu.execute_instruction(RuntimeInstruction::HeapLen)
786            .unwrap();
787        assert_eq!(cpu.stack(), &[encode_u64(1)]);
788    }
789
790    #[test]
791    fn heap_len_rejects_invalid_and_deallocated_objects() {
792        let mut cpu = CPU::default();
793        let heap_id = cpu.push_heap_object(vec![]);
794        cpu.dealloc_heap_object(heap_id).unwrap();
795        for (id, message) in [(heap_id, "deallocated"), (42, "invalid heap object id")] {
796            cpu.stack_push(encode_heap_ref(id));
797            let err = cpu
798                .execute_instruction(RuntimeInstruction::HeapLen)
799                .unwrap_err();
800            assert!(err.to_string().contains(message));
801        }
802    }
803
804    #[test]
805    fn heap_len_requires_operand() {
806        let mut cpu = CPU::default();
807        assert!(
808            cpu.execute_instruction(RuntimeInstruction::HeapLen)
809                .is_err()
810        );
811    }
812
813    #[test]
814    fn reserved_heap_get_item_checks_current_length() {
815        let mut cpu = CPU::default();
816        cpu.stack_push(encode_u64(3));
817        cpu.execute_instruction(RuntimeInstruction::HeapReserve)
818            .unwrap();
819        cpu.stack_push(encode_i64(10));
820        cpu.execute_instruction(RuntimeInstruction::HeapPush)
821            .unwrap();
822        cpu.stack_push(encode_u32(1));
823        let err = cpu
824            .execute_instruction(RuntimeInstruction::GetItem)
825            .unwrap_err();
826        assert!(err.to_string().contains("out of bounds"));
827    }
828
829    #[test]
830    fn heap_push_rejects_allocated_and_zero_capacity_objects() {
831        for instruction in [
832            RuntimeInstruction::HeapAlloc(1),
833            RuntimeInstruction::HeapReserve,
834        ] {
835            let mut cpu = CPU::default();
836            cpu.stack_push(encode_u64(0));
837            cpu.execute_instruction(instruction).unwrap();
838            cpu.stack_push(encode_i64(42));
839            let err = cpu
840                .execute_instruction(RuntimeInstruction::HeapPush)
841                .unwrap_err();
842            assert!(err.to_string().contains("full"));
843        }
844    }
845
846    #[test]
847    fn heap_push_rejects_invalid_and_deallocated_objects() {
848        let mut cpu = CPU::default();
849        cpu.stack_push(encode_u64(1));
850        cpu.execute_instruction(RuntimeInstruction::HeapReserve)
851            .unwrap();
852        cpu.execute_instruction(RuntimeInstruction::HeapDealloc)
853            .unwrap();
854        for (id, message) in [(0, "deallocated"), (42, "invalid heap object id")] {
855            cpu.stack_push(encode_heap_ref(id));
856            cpu.stack_push(encode_i64(1));
857            let err = cpu
858                .execute_instruction(RuntimeInstruction::HeapPush)
859                .unwrap_err();
860            assert!(err.to_string().contains(message));
861        }
862        cpu.stack_push(encode_u64(1));
863        cpu.execute_instruction(RuntimeInstruction::HeapReserve)
864            .unwrap();
865        assert_eq!(cpu.stack(), &[encode_heap_ref(0)]);
866        cpu.stack_push(encode_i64(7));
867        cpu.execute_instruction(RuntimeInstruction::HeapPush)
868            .unwrap();
869        assert_eq!(cpu.heap_object(0).unwrap(), &[encode_i64(7)]);
870    }
871
872    #[test]
873    fn heap_reserve_rejects_unrepresentable_allocation() {
874        let mut cpu = CPU::default();
875        cpu.stack_push(encode_u64(u64::MAX));
876        assert!(
877            cpu.execute_instruction(RuntimeInstruction::HeapReserve)
878                .is_err()
879        );
880        assert!(cpu.heap_is_empty());
881    }
882
883    #[test]
884    fn heap_append_instructions_require_operands() {
885        let mut cpu = CPU::default();
886        assert!(
887            cpu.execute_instruction(RuntimeInstruction::HeapReserve)
888                .is_err()
889        );
890        assert!(
891            cpu.execute_instruction(RuntimeInstruction::HeapPush)
892                .is_err()
893        );
894        cpu.stack_push(encode_heap_ref(0));
895        assert!(
896            cpu.execute_instruction(RuntimeInstruction::HeapPush)
897                .is_err()
898        );
899        assert_eq!(cpu.stack(), &[encode_heap_ref(0)]);
900    }
901
902    #[test]
903    #[cfg(not(feature = "typed-declarations"))]
904    fn op_get_item_reads_heap_value() {
905        let mut cpu = CPU::default();
906        cpu.stack_push(encode_i64(10));
907        cpu.stack_push(encode_i64(20));
908        cpu.stack_push(encode_i64(30));
909        cpu.execute_instruction(RuntimeInstruction::HeapAlloc(3))
910            .unwrap();
911        cpu.stack_push(encode_u32(1));
912
913        let outcome = cpu
914            .execute_instruction(RuntimeInstruction::GetItem)
915            .unwrap();
916
917        assert_eq!(outcome, StepOutcome::Continue);
918        assert_eq!(cpu.stack(), &vec![encode_i64(20)]);
919    }
920
921    #[test]
922    #[cfg(not(feature = "typed-declarations"))]
923    fn op_get_item_rejects_non_heap_refs() {
924        let mut cpu = CPU::default();
925        cpu.stack_push(encode_i64(7));
926        cpu.stack_push(encode_u32(0));
927
928        let err = cpu
929            .execute_instruction(RuntimeInstruction::GetItem)
930            .unwrap_err();
931
932        assert!(err.to_string().contains("heap"));
933    }
934
935    #[test]
936    #[cfg(not(feature = "typed-declarations"))]
937    fn op_get_item_rejects_invalid_heap_ids() {
938        let mut cpu = CPU::default();
939        cpu.stack_push(encode_heap_ref(99));
940        cpu.stack_push(encode_u32(0));
941
942        let err = cpu
943            .execute_instruction(RuntimeInstruction::GetItem)
944            .unwrap_err();
945
946        assert!(err.to_string().contains("heap"));
947    }
948
949    #[test]
950    #[cfg(not(feature = "typed-declarations"))]
951    fn op_get_item_rejects_out_of_bounds_indices() {
952        let mut cpu = CPU::default();
953        cpu.stack_push(encode_i64(10));
954        cpu.execute_instruction(RuntimeInstruction::HeapAlloc(1))
955            .unwrap();
956        cpu.stack_push(encode_u32(3));
957
958        let err = cpu
959            .execute_instruction(RuntimeInstruction::GetItem)
960            .unwrap_err();
961
962        assert!(err.to_string().contains("index"));
963    }
964
965    #[test]
966    fn reset_clears_heap_allocations() {
967        let mut cpu = CPU::default();
968        cpu.stack_push(encode_i64(10));
969        cpu.execute_instruction(RuntimeInstruction::HeapAlloc(1))
970            .unwrap();
971
972        cpu.reset();
973
974        assert!(cpu.heap_is_empty());
975        assert!(cpu.stack().is_empty());
976    }
977
978    #[test]
979    fn execute_generated_dispatches_instruction_without_message() {
980        let mut cpu = CPU::default();
981        cpu.push_frame(Frame {
982            base: 0,
983            local_count: 0,
984            span: (0, 0, 0),
985            function: None,
986            ret_pc: 0,
987        });
988
989        let outcome = GeneratedComponent::execute_generated(
990            &mut cpu,
991            &RuntimeInstruction::ConstI64(encode_i64(99)),
992            CPUMessage::None,
993        )
994        .unwrap();
995
996        assert_eq!(outcome, Effects::one(StepOutcome::Continue));
997        assert_eq!(cpu.stack(), &vec![encode_i64(99)]);
998    }
999
1000    #[test]
1001    fn execute_generated_function_info_is_only_accepted_for_calls() {
1002        let mut cpu = CPU::default();
1003        cpu.push_frame(Frame {
1004            base: 0,
1005            local_count: 0,
1006            span: (0, 0, 0),
1007            function: None,
1008            ret_pc: 0,
1009        });
1010
1011        let outcome = GeneratedComponent::execute_generated(
1012            &mut cpu,
1013            &RuntimeInstruction::Label(Ident("label".to_owned())),
1014            CPUMessage::FunctionInfo {
1015                arity: 2,
1016                start_address: 42,
1017                local_count: 2,
1018            },
1019        )
1020        .unwrap_err();
1021
1022        assert!(outcome.to_string().contains("only valid for call"));
1023        assert!(cpu.stack().is_empty());
1024    }
1025
1026    #[test]
1027    fn execute_generated_print_returns_control_effect_and_pops_stack() {
1028        let mut cpu = CPU::default();
1029        cpu.push_frame(Frame {
1030            base: 0,
1031            local_count: 0,
1032            span: (0, 0, 0),
1033            function: None,
1034            ret_pc: 0,
1035        });
1036        cpu.stack_push(encode_i64(42));
1037
1038        let outcome = GeneratedComponent::execute_generated(
1039            &mut cpu,
1040            &RuntimeInstruction::Print,
1041            CPUMessage::Print("hello".into()),
1042        )
1043        .unwrap();
1044
1045        assert_eq!(outcome, Effects::one(StepOutcome::Continue));
1046        assert!(cpu.stack().is_empty());
1047    }
1048
1049    #[test]
1050    fn execute_generated_print_rejects_wrong_message() {
1051        let mut cpu = CPU::default();
1052        cpu.push_frame(Frame {
1053            base: 0,
1054            local_count: 0,
1055            span: (0, 0, 0),
1056            function: None,
1057            ret_pc: 0,
1058        });
1059        cpu.stack_push(encode_i64(42));
1060
1061        let err = GeneratedComponent::execute_generated(
1062            &mut cpu,
1063            &RuntimeInstruction::Print,
1064            CPUMessage::None,
1065        )
1066        .unwrap_err();
1067
1068        assert!(err.to_string().contains("Print requires"));
1069    }
1070
1071    #[test]
1072    #[cfg(not(feature = "typed-declarations"))]
1073    fn op_heap_dealloc_marks_slot_dead() {
1074        let mut cpu = CPU::default();
1075        cpu.stack_push(encode_i64(42));
1076        cpu.execute_instruction(RuntimeInstruction::HeapAlloc(1))
1077            .unwrap();
1078        cpu.stack_push(encode_heap_ref(0));
1079
1080        cpu.execute_instruction(RuntimeInstruction::HeapDealloc)
1081            .unwrap();
1082
1083        assert!(
1084            cpu.heap_object(0)
1085                .unwrap_err()
1086                .to_string()
1087                .contains("deallocated")
1088        );
1089    }
1090
1091    #[test]
1092    #[cfg(not(feature = "typed-declarations"))]
1093    fn op_heap_dealloc_slot_is_reused_on_next_alloc() {
1094        let mut cpu = CPU::default();
1095        cpu.stack_push(encode_i64(1));
1096        cpu.execute_instruction(RuntimeInstruction::HeapAlloc(1))
1097            .unwrap();
1098        cpu.execute_instruction(RuntimeInstruction::HeapDealloc)
1099            .unwrap();
1100
1101        cpu.stack_push(encode_i64(2));
1102        cpu.execute_instruction(RuntimeInstruction::HeapAlloc(1))
1103            .unwrap();
1104
1105        assert_eq!(cpu.stack(), &vec![encode_heap_ref(0)]);
1106        assert_eq!(cpu.heap_object(0).unwrap(), &[encode_i64(2)]);
1107    }
1108
1109    #[test]
1110    #[cfg(not(feature = "typed-declarations"))]
1111    fn op_heap_dealloc_rejects_double_free() {
1112        let mut cpu = CPU::default();
1113        cpu.stack_push(encode_i64(1));
1114        cpu.execute_instruction(RuntimeInstruction::HeapAlloc(1))
1115            .unwrap();
1116        cpu.stack_push(encode_heap_ref(0));
1117        cpu.execute_instruction(RuntimeInstruction::HeapDealloc)
1118            .unwrap();
1119
1120        cpu.stack_push(encode_heap_ref(0));
1121        let err = cpu
1122            .execute_instruction(RuntimeInstruction::HeapDealloc)
1123            .unwrap_err();
1124
1125        assert!(err.to_string().contains("double-free"));
1126    }
1127
1128    #[test]
1129    #[cfg(not(feature = "typed-declarations"))]
1130    fn op_heap_dealloc_rejects_invalid_id() {
1131        let mut cpu = CPU::default();
1132        cpu.stack_push(encode_heap_ref(99));
1133
1134        let err = cpu
1135            .execute_instruction(RuntimeInstruction::HeapDealloc)
1136            .unwrap_err();
1137
1138        assert!(err.to_string().contains("invalid heap object id"));
1139    }
1140
1141    #[test]
1142    fn reset_clears_free_list() {
1143        let mut cpu = CPU::default();
1144        cpu.stack_push(encode_i64(1));
1145        cpu.execute_instruction(RuntimeInstruction::HeapAlloc(1))
1146            .unwrap();
1147        cpu.stack_push(encode_heap_ref(0));
1148        cpu.execute_instruction(RuntimeInstruction::HeapDealloc)
1149            .unwrap();
1150
1151        cpu.reset();
1152
1153        assert!(cpu.heap_is_empty());
1154    }
1155
1156    #[test]
1157    fn typed_word_arithmetic_canonicalizes_narrow_results() {
1158        let mut cpu = CPU::default();
1159        cpu.stack_push(encode_i32(i32::MAX));
1160        cpu.stack_push(encode_i32(1));
1161        cpu.execute_instruction(RuntimeInstruction::AddI32).unwrap();
1162        assert_eq!(cpu.stack_pop().unwrap(), encode_i32(i32::MIN));
1163
1164        cpu.stack_push(encode_u32(u32::MAX));
1165        cpu.stack_push(encode_u32(1));
1166        cpu.execute_instruction(RuntimeInstruction::AddU32).unwrap();
1167        assert_eq!(cpu.stack_pop().unwrap(), 0);
1168
1169        cpu.stack_push(encode_f32(1.5));
1170        cpu.stack_push(encode_f32(2.0));
1171        cpu.execute_instruction(RuntimeInstruction::MulF32).unwrap();
1172        assert_eq!(decode_f32(cpu.stack_pop().unwrap()), 3.0);
1173    }
1174
1175    #[test]
1176    fn integer_division_and_remainder_report_errors() {
1177        let mut cpu = CPU::default();
1178        cpu.stack_push(encode_i64(7));
1179        cpu.stack_push(encode_i64(0));
1180        assert!(cpu.execute_instruction(RuntimeInstruction::DivI64).is_err());
1181
1182        cpu.stack_push(encode_u32(7));
1183        cpu.stack_push(encode_u32(0));
1184        assert!(cpu.execute_instruction(RuntimeInstruction::RemU32).is_err());
1185    }
1186
1187    #[test]
1188    fn boolean_words_must_be_canonical() {
1189        let mut cpu = CPU::default();
1190        cpu.stack_push(2u64);
1191        assert!(cpu.execute_instruction(RuntimeInstruction::Not).is_err());
1192
1193        cpu.stack_push(2u64);
1194        assert!(
1195            cpu.execute_instruction(RuntimeInstruction::ConditionalBranch(1, 2))
1196                .is_err()
1197        );
1198    }
1199}
1200
1201pub(crate) fn canonical_bool(value: Word) -> Result<bool> {
1202    match value {
1203        0 => Ok(false),
1204        1 => Ok(true),
1205        other => Err(eyre::eyre!("invalid boolean word {}", other)),
1206    }
1207}
1208
1209#[cfg(not(feature = "typed-declarations"))]
1210macro_rules! int_wrapping {
1211    ($($name:ident {
1212        decode: $decode:ident,
1213        encode: $encode:ident,
1214        operation: $op:ident
1215    });+ $(;)?) => {$ (
1216        #[inline(always)]
1217        fn $name(&mut self) -> Result<StepOutcome> {
1218            let rhs = $decode(self.stack_pop()?);
1219            let lhs = $decode(self.stack_pop()?);
1220            self.stack_push($encode(lhs.$op(rhs)));
1221            Ok(StepOutcome::Continue)
1222        }
1223    )+ };
1224}
1225
1226#[cfg(not(feature = "typed-declarations"))]
1227macro_rules! int_checked {
1228    ($($name:ident {
1229        decode: $decode:ident,
1230        encode: $encode:ident,
1231        operation: $op:ident,
1232        error: $message:literal
1233    });+ $(;)?) => {$ (
1234        #[inline(always)]
1235        fn $name(&mut self) -> Result<StepOutcome> {
1236            let rhs = $decode(self.stack_pop()?);
1237            let lhs = $decode(self.stack_pop()?);
1238            let value = lhs.$op(rhs).ok_or_else(|| eyre::eyre!($message))?;
1239            self.stack_push($encode(value));
1240            Ok(StepOutcome::Continue)
1241        }
1242    )+ };
1243}
1244
1245#[cfg(not(feature = "typed-declarations"))]
1246macro_rules! float_binary {
1247    ($($name:ident {
1248        decode: $decode:ident,
1249        encode: $encode:ident,
1250        operator: $op:tt
1251    });+ $(;)?) => {$ (
1252        #[inline(always)]
1253        fn $name(&mut self) -> Result<StepOutcome> {
1254            let rhs = $decode(self.stack_pop()?);
1255            let lhs = $decode(self.stack_pop()?);
1256            self.stack_push($encode(lhs $op rhs));
1257            Ok(StepOutcome::Continue)
1258        }
1259    )+ };
1260}
1261
1262#[cfg(not(feature = "typed-declarations"))]
1263macro_rules! shift {
1264    ($($name:ident {
1265        decode: $decode:ident,
1266        encode: $encode:ident,
1267        operation: $op:ident,
1268        count_mask: $mask:expr
1269    });+ $(;)?) => {$ (
1270        #[inline(always)]
1271        fn $name(&mut self) -> Result<StepOutcome> {
1272            let rhs = decode_u32(self.stack_pop()?);
1273            let lhs = $decode(self.stack_pop()?);
1274            self.stack_push($encode(lhs.$op(rhs & $mask)));
1275            Ok(StepOutcome::Continue)
1276        }
1277    )+ };
1278}
1279
1280#[cfg(not(feature = "typed-declarations"))]
1281macro_rules! rotate {
1282    ($($name:ident {
1283        decode: $decode:ident,
1284        encode: $encode:ident,
1285        operation: $op:ident
1286    });+ $(;)?) => {$ (
1287        #[inline(always)]
1288        fn $name(&mut self) -> Result<StepOutcome> {
1289            let rhs = decode_u32(self.stack_pop()?);
1290            let lhs = $decode(self.stack_pop()?);
1291            self.stack_push($encode(lhs.$op(rhs)));
1292            Ok(StepOutcome::Continue)
1293        }
1294    )+ };
1295}
1296
1297#[cfg(not(feature = "typed-declarations"))]
1298macro_rules! bitwise {
1299    ($($name:ident {
1300        decode: $decode:ident,
1301        encode: $encode:ident,
1302        operator: $op:tt
1303    });+ $(;)?) => {$ (
1304        #[inline(always)]
1305        fn $name(&mut self) -> Result<StepOutcome> {
1306            let rhs = $decode(self.stack_pop()?);
1307            let lhs = $decode(self.stack_pop()?);
1308            self.stack_push($encode(lhs $op rhs));
1309            Ok(StepOutcome::Continue)
1310        }
1311    )+ };
1312}
1313
1314#[cfg(not(feature = "typed-declarations"))]
1315macro_rules! compare {
1316    ($($name:ident {
1317        decode: $decode:ident,
1318        operator: $op:tt
1319    });+ $(;)?) => {$ (
1320        #[inline(always)]
1321        fn $name(&mut self) -> Result<StepOutcome> {
1322            let rhs = $decode(self.stack_pop()?);
1323            let lhs = $decode(self.stack_pop()?);
1324            self.stack_push(encode_bool(lhs $op rhs));
1325            Ok(StepOutcome::Continue)
1326        }
1327    )+ };
1328}
1329
1330#[cfg(not(feature = "typed-declarations"))]
1331impl CPU {
1332    int_wrapping! {
1333        add_i32 { decode: decode_i32, encode: encode_i32, operation: wrapping_add };
1334        add_i64 { decode: decode_i64, encode: encode_i64, operation: wrapping_add };
1335        add_u32 { decode: decode_u32, encode: encode_u32, operation: wrapping_add };
1336        add_u64 { decode: decode_u64, encode: encode_u64, operation: wrapping_add };
1337        sub_i32 { decode: decode_i32, encode: encode_i32, operation: wrapping_sub };
1338        sub_i64 { decode: decode_i64, encode: encode_i64, operation: wrapping_sub };
1339        sub_u32 { decode: decode_u32, encode: encode_u32, operation: wrapping_sub };
1340        sub_u64 { decode: decode_u64, encode: encode_u64, operation: wrapping_sub };
1341        mul_i32 { decode: decode_i32, encode: encode_i32, operation: wrapping_mul };
1342        mul_i64 { decode: decode_i64, encode: encode_i64, operation: wrapping_mul };
1343        mul_u32 { decode: decode_u32, encode: encode_u32, operation: wrapping_mul };
1344        mul_u64 { decode: decode_u64, encode: encode_u64, operation: wrapping_mul };
1345    }
1346    int_checked! {
1347        div_i32 { decode: decode_i32, encode: encode_i32, operation: checked_div, error: "integer division error" };
1348        div_i64 { decode: decode_i64, encode: encode_i64, operation: checked_div, error: "integer division error" };
1349        div_u32 { decode: decode_u32, encode: encode_u32, operation: checked_div, error: "integer division error" };
1350        div_u64 { decode: decode_u64, encode: encode_u64, operation: checked_div, error: "integer division error" };
1351        rem_i32 { decode: decode_i32, encode: encode_i32, operation: checked_rem, error: "integer remainder error" };
1352        rem_i64 { decode: decode_i64, encode: encode_i64, operation: checked_rem, error: "integer remainder error" };
1353        rem_u32 { decode: decode_u32, encode: encode_u32, operation: checked_rem, error: "integer remainder error" };
1354        rem_u64 { decode: decode_u64, encode: encode_u64, operation: checked_rem, error: "integer remainder error" };
1355    }
1356    float_binary! {
1357        add_f32 { decode: decode_f32, encode: encode_f32, operator: + };
1358        add_f64 { decode: decode_f64, encode: encode_f64, operator: + };
1359        sub_f32 { decode: decode_f32, encode: encode_f32, operator: - };
1360        sub_f64 { decode: decode_f64, encode: encode_f64, operator: - };
1361        mul_f32 { decode: decode_f32, encode: encode_f32, operator: * };
1362        mul_f64 { decode: decode_f64, encode: encode_f64, operator: * };
1363        div_f32 { decode: decode_f32, encode: encode_f32, operator: / };
1364        div_f64 { decode: decode_f64, encode: encode_f64, operator: / };
1365        rem_f32 { decode: decode_f32, encode: encode_f32, operator: % };
1366        rem_f64 { decode: decode_f64, encode: encode_f64, operator: % };
1367    }
1368
1369    #[inline(always)]
1370    fn neg_i32(&mut self) -> Result<StepOutcome> {
1371        let value = decode_i32(self.stack_pop()?).wrapping_neg();
1372        self.stack_push(encode_i32(value));
1373        Ok(StepOutcome::Continue)
1374    }
1375    #[inline(always)]
1376    fn neg_i64(&mut self) -> Result<StepOutcome> {
1377        let value = decode_i64(self.stack_pop()?).wrapping_neg();
1378        self.stack_push(encode_i64(value));
1379        Ok(StepOutcome::Continue)
1380    }
1381    #[inline(always)]
1382    fn neg_f32(&mut self) -> Result<StepOutcome> {
1383        let value = -decode_f32(self.stack_pop()?);
1384        self.stack_push(encode_f32(value));
1385        Ok(StepOutcome::Continue)
1386    }
1387    #[inline(always)]
1388    fn neg_f64(&mut self) -> Result<StepOutcome> {
1389        let value = -decode_f64(self.stack_pop()?);
1390        self.stack_push(encode_f64(value));
1391        Ok(StepOutcome::Continue)
1392    }
1393
1394    shift! {
1395        shl_i32 { decode: decode_i32, encode: encode_i32, operation: wrapping_shl, count_mask: 31 };
1396        shl_i64 { decode: decode_i64, encode: encode_i64, operation: wrapping_shl, count_mask: 63 };
1397        shl_u32 { decode: decode_u32, encode: encode_u32, operation: wrapping_shl, count_mask: 31 };
1398        shl_u64 { decode: decode_u64, encode: encode_u64, operation: wrapping_shl, count_mask: 63 };
1399        shr_i32 { decode: decode_i32, encode: encode_i32, operation: wrapping_shr, count_mask: 31 };
1400        shr_i64 { decode: decode_i64, encode: encode_i64, operation: wrapping_shr, count_mask: 63 };
1401        shr_u32 { decode: decode_u32, encode: encode_u32, operation: wrapping_shr, count_mask: 31 };
1402        shr_u64 { decode: decode_u64, encode: encode_u64, operation: wrapping_shr, count_mask: 63 };
1403    }
1404    rotate! {
1405        rol_i32 { decode: decode_i32, encode: encode_i32, operation: rotate_left };
1406        rol_i64 { decode: decode_i64, encode: encode_i64, operation: rotate_left };
1407        rol_u32 { decode: decode_u32, encode: encode_u32, operation: rotate_left };
1408        rol_u64 { decode: decode_u64, encode: encode_u64, operation: rotate_left };
1409        ror_i32 { decode: decode_i32, encode: encode_i32, operation: rotate_right };
1410        ror_i64 { decode: decode_i64, encode: encode_i64, operation: rotate_right };
1411        ror_u32 { decode: decode_u32, encode: encode_u32, operation: rotate_right };
1412        ror_u64 { decode: decode_u64, encode: encode_u64, operation: rotate_right };
1413    }
1414    bitwise! {
1415        bitand_i32 { decode: decode_i32, encode: encode_i32, operator: & };
1416        bitand_i64 { decode: decode_i64, encode: encode_i64, operator: & };
1417        bitand_u32 { decode: decode_u32, encode: encode_u32, operator: & };
1418        bitand_u64 { decode: decode_u64, encode: encode_u64, operator: & };
1419        bitor_i32 { decode: decode_i32, encode: encode_i32, operator: | };
1420        bitor_i64 { decode: decode_i64, encode: encode_i64, operator: | };
1421        bitor_u32 { decode: decode_u32, encode: encode_u32, operator: | };
1422        bitor_u64 { decode: decode_u64, encode: encode_u64, operator: | };
1423        bitxor_i32 { decode: decode_i32, encode: encode_i32, operator: ^ };
1424        bitxor_i64 { decode: decode_i64, encode: encode_i64, operator: ^ };
1425        bitxor_u32 { decode: decode_u32, encode: encode_u32, operator: ^ };
1426        bitxor_u64 { decode: decode_u64, encode: encode_u64, operator: ^ };
1427    }
1428    compare! {
1429        eq_i32 { decode: decode_i32, operator: == };
1430        eq_i64 { decode: decode_i64, operator: == };
1431        eq_u32 { decode: decode_u32, operator: == };
1432        eq_u64 { decode: decode_u64, operator: == };
1433        eq_f32 { decode: decode_f32, operator: == };
1434        eq_f64 { decode: decode_f64, operator: == };
1435        ne_i32 { decode: decode_i32, operator: != };
1436        ne_i64 { decode: decode_i64, operator: != };
1437        ne_u32 { decode: decode_u32, operator: != };
1438        ne_u64 { decode: decode_u64, operator: != };
1439        ne_f32 { decode: decode_f32, operator: != };
1440        ne_f64 { decode: decode_f64, operator: != };
1441        lt_i32 { decode: decode_i32, operator: < };
1442        lt_i64 { decode: decode_i64, operator: < };
1443        lt_u32 { decode: decode_u32, operator: < };
1444        lt_u64 { decode: decode_u64, operator: < };
1445        lt_f32 { decode: decode_f32, operator: < };
1446        lt_f64 { decode: decode_f64, operator: < };
1447        gt_i32 { decode: decode_i32, operator: > };
1448        gt_i64 { decode: decode_i64, operator: > };
1449        gt_u32 { decode: decode_u32, operator: > };
1450        gt_u64 { decode: decode_u64, operator: > };
1451        gt_f32 { decode: decode_f32, operator: > };
1452        gt_f64 { decode: decode_f64, operator: > };
1453        le_i32 { decode: decode_i32, operator: <= };
1454        le_i64 { decode: decode_i64, operator: <= };
1455        le_u32 { decode: decode_u32, operator: <= };
1456        le_u64 { decode: decode_u64, operator: <= };
1457        le_f32 { decode: decode_f32, operator: <= };
1458        le_f64 { decode: decode_f64, operator: <= };
1459        ge_i32 { decode: decode_i32, operator: >= };
1460        ge_i64 { decode: decode_i64, operator: >= };
1461        ge_u32 { decode: decode_u32, operator: >= };
1462        ge_u64 { decode: decode_u64, operator: >= };
1463        ge_f32 { decode: decode_f32, operator: >= };
1464        ge_f64 { decode: decode_f64, operator: >= };
1465    }
1466
1467    #[cfg(not(feature = "typed-declarations"))]
1468    fn op_not(&mut self) -> Result<StepOutcome> {
1469        let value = !canonical_bool(self.stack_pop()?)?;
1470        self.stack_push(encode_bool(value));
1471        Ok(StepOutcome::Continue)
1472    }
1473    #[cfg(not(feature = "typed-declarations"))]
1474    fn op_and(&mut self) -> Result<StepOutcome> {
1475        let rhs = canonical_bool(self.stack_pop()?)?;
1476        let lhs = canonical_bool(self.stack_pop()?)?;
1477        self.stack_push(encode_bool(lhs && rhs));
1478        Ok(StepOutcome::Continue)
1479    }
1480    #[cfg(not(feature = "typed-declarations"))]
1481    fn op_or(&mut self) -> Result<StepOutcome> {
1482        let rhs = canonical_bool(self.stack_pop()?)?;
1483        let lhs = canonical_bool(self.stack_pop()?)?;
1484        self.stack_push(encode_bool(lhs || rhs));
1485        Ok(StepOutcome::Continue)
1486    }
1487    #[cfg(not(feature = "typed-declarations"))]
1488    fn op_xor(&mut self) -> Result<StepOutcome> {
1489        let rhs = canonical_bool(self.stack_pop()?)?;
1490        let lhs = canonical_bool(self.stack_pop()?)?;
1491        self.stack_push(encode_bool(lhs ^ rhs));
1492        Ok(StepOutcome::Continue)
1493    }
1494}