Skip to main content

rhue_bytecode/
instr.rs

1use std::fmt;
2
3use crate::Op;
4
5/// A 32-bit instruction.
6///
7/// ```text
8///  31      24 23      16 15       8 7        0
9/// +----------+----------+----------+----------+
10/// |    C     |    B     |    A     |    op    |   ABC
11/// +----------+----------+----------+----------+
12/// |        Bx / sBx     |    A     |    op    |   ABx / AsBx
13/// +---------------------+----------+----------+
14/// |              sAx               |    op    |   sAx (JMP)
15/// +--------------------------------+----------+
16/// ```
17///
18/// The opcode's in the low byte (like Luau), so decoding it is one `as u8`.
19#[derive(Clone, Copy, PartialEq, Eq, Hash)]
20pub struct Instr(pub u32);
21
22impl Instr {
23    pub const fn abc(op: Op, a: u8, b: u8, c: u8) -> Self {
24        Instr(op as u32 | (a as u32) << 8 | (b as u32) << 16 | (c as u32) << 24)
25    }
26
27    pub const fn abx(op: Op, a: u8, bx: u16) -> Self {
28        Instr(op as u32 | (a as u32) << 8 | (bx as u32) << 16)
29    }
30
31    pub const fn asbx(op: Op, a: u8, sbx: i16) -> Self {
32        Self::abx(op, a, sbx as u16)
33    }
34
35    /// Largest |offset| a `JMP` can encode (24-bit signed).
36    pub const MAX_SAX: i32 = (1 << 23) - 1;
37
38    /// A 24-bit signed operand in the A, B and C fields (used by `JMP`).
39    pub const fn asax(op: Op, sax: i32) -> Self {
40        Instr(op as u32 | ((sax as u32) << 8))
41    }
42
43    /// The opcode, or `None` if the instruction's corrupt.
44    #[inline]
45    pub fn op(self) -> Option<Op> {
46        Op::from_u8(self.0 as u8)
47    }
48
49    #[inline]
50    pub const fn a(self) -> u8 {
51        (self.0 >> 8) as u8
52    }
53
54    #[inline]
55    pub const fn b(self) -> u8 {
56        (self.0 >> 16) as u8
57    }
58
59    #[inline]
60    pub const fn c(self) -> u8 {
61        (self.0 >> 24) as u8
62    }
63
64    #[inline]
65    pub const fn bx(self) -> u16 {
66        (self.0 >> 16) as u16
67    }
68
69    #[inline]
70    pub const fn sbx(self) -> i16 {
71        self.bx() as i16
72    }
73
74    /// arithmetic shift sign-extends the top 24 bits
75    #[inline]
76    pub const fn sax(self) -> i32 {
77        (self.0 as i32) >> 8
78    }
79}
80
81impl fmt::Debug for Instr {
82    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83        match self.op() {
84            Some(op) => write!(
85                f,
86                "{} {} {} {}",
87                op.mnemonic(),
88                self.a(),
89                self.b(),
90                self.c()
91            ),
92            None => write!(f, "<bad {:#010x}>", self.0),
93        }
94    }
95}
96
97#[cfg(test)]
98mod tests {
99    use super::*;
100
101    #[test]
102    fn abc_roundtrip() {
103        let i = Instr::abc(Op::AddK, 1, 200, 255);
104        assert_eq!(i.op(), Some(Op::AddK));
105        assert_eq!((i.a(), i.b(), i.c()), (1, 200, 255));
106    }
107
108    #[test]
109    fn bx_roundtrip() {
110        let i = Instr::abx(Op::LoadK, 7, 65535);
111        assert_eq!((i.op(), i.a(), i.bx()), (Some(Op::LoadK), 7, 65535));
112    }
113
114    #[test]
115    fn sbx_roundtrip() {
116        for v in [i16::MIN, -1, 0, 1, i16::MAX] {
117            let i = Instr::asbx(Op::LoadN, 3, v);
118            assert_eq!((i.a(), i.sbx()), (3, v));
119        }
120    }
121
122    #[test]
123    fn sax_roundtrip() {
124        for v in [-Instr::MAX_SAX, -1, 0, 1, 1000, Instr::MAX_SAX] {
125            let i = Instr::asax(Op::Jmp, v);
126            assert_eq!((i.op(), i.sax()), (Some(Op::Jmp), v));
127        }
128    }
129
130    #[test]
131    fn bad_opcode() {
132        assert_eq!(Instr(0xff).op(), None);
133    }
134
135    #[test]
136    fn every_opcode_roundtrips_through_u8() {
137        for (i, op) in Op::ALL.iter().enumerate() {
138            assert_eq!(*op as usize, i);
139            assert_eq!(Op::from_u8(i as u8), Some(*op));
140        }
141    }
142}