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