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