expr_solver/
ir.rs

1//! Bytecode instruction definitions for the virtual machine.
2
3use crate::ast::{BinOp, UnOp};
4use crate::number::Number;
5#[cfg(feature = "serialization")]
6use serde::{Deserialize, Serialize};
7
8/// Bytecode instructions for the stack-based virtual machine.
9#[derive(Debug, Clone)]
10#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
11pub enum Instr {
12    Push(Number),
13    Load(usize),  // Index into SymTable
14    Store(usize), // Index into SymTable
15    Neg,
16    Add,
17    Sub,
18    Mul,
19    Div,
20    Pow,
21    Fact,
22    Call(usize, usize), // Index into SymTable and argument count
23    Equal,
24    NotEqual,
25    Less,
26    LessEqual,
27    Greater,
28    GreaterEqual,
29    // Control flow
30    Jmp(usize), // Unconditional jump to instruction index
31    Jz(usize),  // Jump to instruction index if top of stack is zero (consumes value)
32}
33
34impl From<UnOp> for Instr {
35    fn from(op: UnOp) -> Self {
36        match op {
37            UnOp::Neg => Instr::Neg,
38            UnOp::Fact => Instr::Fact,
39        }
40    }
41}
42
43impl From<BinOp> for Instr {
44    fn from(op: BinOp) -> Self {
45        match op {
46            BinOp::Add => Instr::Add,
47            BinOp::Sub => Instr::Sub,
48            BinOp::Mul => Instr::Mul,
49            BinOp::Div => Instr::Div,
50            BinOp::Pow => Instr::Pow,
51            BinOp::Equal => Instr::Equal,
52            BinOp::NotEqual => Instr::NotEqual,
53            BinOp::Less => Instr::Less,
54            BinOp::LessEqual => Instr::LessEqual,
55            BinOp::Greater => Instr::Greater,
56            BinOp::GreaterEqual => Instr::GreaterEqual,
57        }
58    }
59}