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