Skip to main content

runec/
bytecode.rs

1/// RS2 opcodes matching the actual wire format.
2/// These values correspond to the opcodes used by the RuneScape 2 script engine.
3#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4pub enum Opcode {
5    PushConstantInt = 0,
6    PushVarp = 1,
7    PopVarp = 2,
8    PushConstantString = 3,
9    PushVarn = 4,
10    PopVarn = 5,
11    Branch = 6,
12    BranchNot = 7,
13    BranchEquals = 8,
14    BranchLessThan = 9,
15    BranchGreaterThan = 10,
16    PushVars = 11,
17    PopVars = 12,
18    Return = 21,
19    Gosub = 22,
20    Jump = 23,
21    Switch = 24,
22    PushVarbit = 25,
23    PopVarbit = 27,
24    BranchLessThanOrEquals = 31,
25    BranchGreaterThanOrEquals = 32,
26    PushIntLocal = 33,
27    PopIntLocal = 34,
28    PushStringLocal = 35,
29    PopStringLocal = 36,
30    JoinString = 37,
31    PopIntDiscard = 38,
32    PopStringDiscard = 39,
33    GosubWithParams = 40,
34    JumpWithParams = 41,
35    DefineArray = 44,
36    PushArrayInt = 45,
37    PopArrayInt = 46,
38    PushConstantLong = 54,
39    PushLongLocal = 55,
40    PopLongLocal = 56,
41    PopLongDiscard = 57,
42    // Long branch operations
43    LongBranchNot = 68,
44    LongBranchEquals = 69,
45    LongBranchLessThan = 70,
46    LongBranchGreaterThan = 71,
47    LongBranchLessThanOrEquals = 72,
48    LongBranchGreaterThanOrEquals = 73,
49    // Object/string branch operations
50    ObjBranchEquals = 86,
51    ObjBranchNot = 87,
52    // Arithmetic operations (4600+ range — engine commands)
53    Add = 4600,
54    Sub = 4601,
55    Multiply = 4602,
56    Divide = 4603,
57    Random = 4604,
58    RandomInc = 4605,
59    Interpolate = 4606,
60    AddPercent = 4607,
61    SetBit = 4608,
62    ClearBit = 4609,
63    TestBit = 4610,
64    Modulo = 4611,
65    Pow = 4612,
66    InvPow = 4613,
67    And = 4614,
68    Or = 4615,
69    Min = 4616,
70    Max = 4617,
71    Scale = 4618,
72    BitCount = 4619,
73    ToggleBit = 4620,
74    SetBitRange = 4621,
75    ClearBitRange = 4622,
76    GetBitRange = 4623,
77    SetBitRangeToVal = 4624,
78    SinDeg = 4625,
79    CosDeg = 4626,
80    Atan2Deg = 4627,
81    Abs = 4628,
82    // String operations (4200+ range)
83    // Command is used for engine commands - opcode is looked up dynamically
84    Command = 65535,
85    // Line number metadata (not a real opcode, used for debugging)
86    LineNumber = 65534,
87}
88
89/// A single instruction in the compiled bytecode.
90#[derive(Debug, Clone)]
91pub struct Instruction {
92    pub opcode: Opcode,
93    pub operand: Operand,
94}
95
96/// The operand (data) associated with an instruction.
97///
98/// Kept as small as possible (each script holds a `Vec<Instruction>`, and the
99/// corpus runs to ~half a million instructions): the two heap-backed payloads —
100/// string literals and switch tables — live in side pools on the owning
101/// `CompiledScript`, and the operand stores only a `u32` index into them. That
102/// keeps every variant ≤ 8 B, so `Operand` is 16 B and `Instruction` is 24 B
103/// (vs 24/32 when the payloads were inline `Box<str>`/`Box<[_]>`).
104#[derive(Debug, Clone)]
105pub enum Operand {
106    None,
107    Int(i32),
108    Long(i64),
109    /// Index into the owning `CompiledScript::strings` pool.
110    Str(u32),
111    /// Jump target as instruction index within the script
112    JumpTarget(usize),
113    /// Index into the owning `CompiledScript::switch_tables` pool.
114    SwitchTable(u32),
115    /// String join with N parts
116    StringCount(u32),
117    /// Array definition: (var_id, element_type_char)
118    ArrayDef(i32, u8),
119}
120
121impl Instruction {
122    pub fn new(opcode: Opcode, operand: Operand) -> Self {
123        Instruction { opcode, operand }
124    }
125
126    pub fn simple(opcode: Opcode) -> Self {
127        Instruction {
128            opcode,
129            operand: Operand::None,
130        }
131    }
132
133    pub fn push_int(value: i32) -> Self {
134        Instruction::new(Opcode::PushConstantInt, Operand::Int(value))
135    }
136
137    pub fn push_long(value: i64) -> Self {
138        Instruction::new(Opcode::PushConstantLong, Operand::Long(value))
139    }
140
141    pub fn jump(target: usize) -> Self {
142        Instruction::new(Opcode::Branch, Operand::JumpTarget(target))
143    }
144
145    pub fn branch_not(target: usize) -> Self {
146        Instruction::new(Opcode::BranchNot, Operand::JumpTarget(target))
147    }
148
149    pub fn branch_equals(target: usize) -> Self {
150        Instruction::new(Opcode::BranchEquals, Operand::JumpTarget(target))
151    }
152
153    pub fn branch_less_than(target: usize) -> Self {
154        Instruction::new(Opcode::BranchLessThan, Operand::JumpTarget(target))
155    }
156
157    pub fn branch_greater_than(target: usize) -> Self {
158        Instruction::new(Opcode::BranchGreaterThan, Operand::JumpTarget(target))
159    }
160
161    pub fn branch_less_than_or_equals(target: usize) -> Self {
162        Instruction::new(Opcode::BranchLessThanOrEquals, Operand::JumpTarget(target))
163    }
164
165    pub fn branch_greater_than_or_equals(target: usize) -> Self {
166        Instruction::new(
167            Opcode::BranchGreaterThanOrEquals,
168            Operand::JumpTarget(target),
169        )
170    }
171
172    pub fn gosub(script_id: i32) -> Self {
173        Instruction::new(Opcode::Gosub, Operand::Int(script_id))
174    }
175
176    pub fn gosub_with_params(script_id: i32) -> Self {
177        Instruction::new(Opcode::GosubWithParams, Operand::Int(script_id))
178    }
179
180    pub fn push_int_local(var_id: i32) -> Self {
181        Instruction::new(Opcode::PushIntLocal, Operand::Int(var_id))
182    }
183
184    pub fn pop_int_local(var_id: i32) -> Self {
185        Instruction::new(Opcode::PopIntLocal, Operand::Int(var_id))
186    }
187
188    pub fn push_string_local(var_id: i32) -> Self {
189        Instruction::new(Opcode::PushStringLocal, Operand::Int(var_id))
190    }
191
192    pub fn pop_string_local(var_id: i32) -> Self {
193        Instruction::new(Opcode::PopStringLocal, Operand::Int(var_id))
194    }
195
196    pub fn push_long_local(var_id: i32) -> Self {
197        Instruction::new(Opcode::PushLongLocal, Operand::Int(var_id))
198    }
199
200    pub fn pop_long_local(var_id: i32) -> Self {
201        Instruction::new(Opcode::PopLongLocal, Operand::Int(var_id))
202    }
203
204    pub fn join_string(count: u32) -> Self {
205        Instruction::new(Opcode::JoinString, Operand::StringCount(count))
206    }
207}
208
209/// Compiled bytecode for a single script.
210#[derive(Debug, Clone)]
211pub struct CompiledScript {
212    pub name: String,
213    pub id: i32,
214    pub trigger: String,
215    pub source_path: String,
216    /// Lookup key for fast engine dispatch (-1 if not applicable).
217    pub lookup_key: i32,
218    pub param_types: Vec<crate::types::Type>,
219    pub instructions: Vec<Instruction>,
220    pub local_table: crate::symbol::LocalTable,
221    pub int_local_count: u16,
222    pub string_local_count: u16,
223    pub long_local_count: u16,
224    pub int_arg_count: u16,
225    pub string_arg_count: u16,
226    pub long_arg_count: u16,
227    /// String-literal / unknown-command-name payloads, referenced by
228    /// `Operand::Str(index)`. Kept out of the instruction so `Operand` stays 8 B.
229    pub strings: Vec<Box<str>>,
230    /// Switch-case tables `(case_value, jump_target)`, referenced by
231    /// `Operand::SwitchTable(index)`. Stored in instruction-encounter order.
232    pub switch_tables: Vec<Box<[(i32, usize)]>>,
233}
234
235impl CompiledScript {
236    pub fn new(name: String, id: i32) -> Self {
237        Self {
238            name,
239            id,
240            trigger: String::new(),
241            source_path: String::new(),
242            lookup_key: -1,
243            param_types: Vec::new(),
244            instructions: Vec::new(),
245            local_table: crate::symbol::LocalTable::new(),
246            int_local_count: 0,
247            string_local_count: 0,
248            long_local_count: 0,
249            int_arg_count: 0,
250            string_arg_count: 0,
251            long_arg_count: 0,
252            strings: Vec::new(),
253            switch_tables: Vec::new(),
254        }
255    }
256
257    pub fn push(&mut self, instruction: Instruction) {
258        self.instructions.push(instruction);
259    }
260
261    /// Add a string payload to the pool and return its `Operand::Str` index.
262    pub fn intern_str(&mut self, value: String) -> u32 {
263        let idx = self.strings.len() as u32;
264        self.strings.push(value.into_boxed_str());
265        idx
266    }
267
268    /// Emit a `PushConstantString` whose literal is interned into the pool.
269    pub fn push_string(&mut self, value: String) {
270        let idx = self.intern_str(value);
271        self.instructions.push(Instruction::new(
272            Opcode::PushConstantString,
273            Operand::Str(idx),
274        ));
275    }
276
277    pub fn len(&self) -> usize {
278        self.instructions.len()
279    }
280
281    pub fn is_empty(&self) -> bool {
282        self.instructions.is_empty()
283    }
284
285    /// Update a jump target at the given instruction index.
286    pub fn patch_jump(&mut self, index: usize, target: usize) {
287        self.instructions[index].operand = Operand::JumpTarget(target);
288    }
289
290    /// Release the spare capacity the growable codegen buffers left behind.
291    /// Compiled scripts are immutable after codegen but are held in memory for
292    /// the whole pointer-check + write phase, so reclaiming each `Vec`'s doubling
293    /// slack (often 25-50%) meaningfully lowers the resident footprint.
294    pub fn shrink_to_fit(&mut self) {
295        self.instructions.shrink_to_fit();
296        self.param_types.shrink_to_fit();
297        self.local_table.shrink_to_fit();
298        self.strings.shrink_to_fit();
299        self.switch_tables.shrink_to_fit();
300    }
301}