Skip to main content

runec/
bytecode.rs

1use crate::opcodes;
2
3/// RS2 opcodes matching the actual wire format.
4/// These values correspond to the opcodes used by the RuneScape 2 script engine.
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
6#[repr(u16)]
7pub enum Opcode {
8    PushConstantInt = opcodes::PUSH_CONSTANT_INT,
9    PushVarp = opcodes::PUSH_VARP,
10    PopVarp = opcodes::POP_VARP,
11    PushConstantString = opcodes::PUSH_CONSTANT_STRING,
12    PushVarn = opcodes::PUSH_VARN,
13    PopVarn = opcodes::POP_VARN,
14    Branch = opcodes::BRANCH,
15    BranchNot = opcodes::BRANCH_NOT,
16    BranchEquals = opcodes::BRANCH_EQUALS,
17    BranchLessThan = opcodes::BRANCH_LESS_THAN,
18    BranchGreaterThan = opcodes::BRANCH_GREATER_THAN,
19    PushVars = opcodes::PUSH_VARS,
20    PopVars = opcodes::POP_VARS,
21    Return = opcodes::RETURN,
22    Gosub = opcodes::GOSUB,
23    Jump = opcodes::JUMP,
24    Switch = opcodes::SWITCH,
25    PushVarpBit = opcodes::PUSH_VARPBIT,
26    PopVarpBit = opcodes::POP_VARPBIT,
27    BranchLessThanOrEquals = opcodes::BRANCH_LESS_THAN_OR_EQUALS,
28    BranchGreaterThanOrEquals = opcodes::BRANCH_GREATER_THAN_OR_EQUALS,
29    PushIntLocal = opcodes::PUSH_INT_LOCAL,
30    PopIntLocal = opcodes::POP_INT_LOCAL,
31    PushStringLocal = opcodes::PUSH_STRING_LOCAL,
32    PopStringLocal = opcodes::POP_STRING_LOCAL,
33    JoinString = opcodes::JOIN_STRING,
34    PopIntDiscard = opcodes::POP_INT_DISCARD,
35    PopStringDiscard = opcodes::POP_STRING_DISCARD,
36    GosubWithParams = opcodes::GOSUB_WITH_PARAMS,
37    JumpWithParams = opcodes::JUMP_WITH_PARAMS,
38    PushVarcInt = opcodes::PUSH_VARC_INT,
39    PopVarcInt = opcodes::POP_VARC_INT,
40    DefineArray = opcodes::DEFINE_ARRAY,
41    PushArrayInt = opcodes::PUSH_ARRAY_INT,
42    PopArrayInt = opcodes::POP_ARRAY_INT,
43    PushVarcString = opcodes::PUSH_VARC_STRING,
44    PopVarcString = opcodes::POP_VARC_STRING,
45    PushConstantLong = opcodes::PUSH_CONSTANT_LONG,
46    PushLongLocal = opcodes::PUSH_LONG_LOCAL,
47    PopLongLocal = opcodes::POP_LONG_LOCAL,
48    PopLongDiscard = opcodes::POP_LONG_DISCARD,
49    // Long branch operations
50    LongBranchNot = opcodes::LONG_BRANCH_NOT,
51    LongBranchEquals = opcodes::LONG_BRANCH_EQUALS,
52    LongBranchLessThan = opcodes::LONG_BRANCH_LESS_THAN,
53    LongBranchGreaterThan = opcodes::LONG_BRANCH_GREATER_THAN,
54    LongBranchLessThanOrEquals = opcodes::LONG_BRANCH_LESS_THAN_OR_EQUALS,
55    LongBranchGreaterThanOrEquals = opcodes::LONG_BRANCH_GREATER_THAN_OR_EQUALS,
56    // Server-only vars, in a range the client leaves unused
57    PushVarClan = opcodes::PUSH_VARCLAN,
58    PopVarClan = opcodes::POP_VARCLAN,
59    PushVarObj = opcodes::PUSH_VAROBJ,
60    PopVarObj = opcodes::POP_VAROBJ,
61    PushVarnBit = opcodes::PUSH_VARNBIT,
62    PopVarnBit = opcodes::POP_VARNBIT,
63    PushVarCon = opcodes::PUSH_VARCON,
64    PopVarCon = opcodes::POP_VARCON,
65    PopClanSettingInt = opcodes::POP_CLANSETTING_INT,
66    PopClanSettingVarbit = opcodes::POP_CLANSETTING_VARBIT,
67    PopClanSettingLong = opcodes::POP_CLANSETTING_LONG,
68    PopClanSettingString = opcodes::POP_CLANSETTING_STRING,
69    // Object/string branch operations
70    ObjBranchEquals = opcodes::OBJ_BRANCH_EQUALS,
71    ObjBranchNot = opcodes::OBJ_BRANCH_NOT,
72    PushVarConBit = opcodes::PUSH_VARCONBIT,
73    PopVarConBit = opcodes::POP_VARCONBIT,
74    // Client vars from 742
75    PushVarClanBit = opcodes::PUSH_VARCLAN_BIT,
76    PushVarClanLong = opcodes::PUSH_VARCLAN_LONG,
77    PushVarClanString = opcodes::PUSH_VARCLAN_STRING,
78    PushVarPlayer = opcodes::PUSH_VARPLAYER,
79    PushVarPlayerBit = opcodes::PUSH_VARPLAYER_BIT,
80    PushVarNpc = opcodes::PUSH_VARNPC,
81    PushVarNpcBit = opcodes::PUSH_VARNPC_BIT,
82    PushClanSettingInt = opcodes::PUSH_CLANSETTING_INT,
83    PushClanSettingVarbit = opcodes::PUSH_CLANSETTING_VARBIT,
84    PushClanSettingLong = opcodes::PUSH_CLANSETTING_LONG,
85    PushClanSettingString = opcodes::PUSH_CLANSETTING_STRING,
86    // Arithmetic operations (4600+ range — engine commands)
87    Add = opcodes::ADD,
88    Sub = opcodes::SUB,
89    Multiply = opcodes::MULTIPLY,
90    Divide = opcodes::DIVIDE,
91    Random = opcodes::RANDOM,
92    RandomInc = opcodes::RANDOMINC,
93    Interpolate = opcodes::INTERPOLATE,
94    AddPercent = opcodes::ADDPERCENT,
95    SetBit = opcodes::SETBIT,
96    ClearBit = opcodes::CLEARBIT,
97    TestBit = opcodes::TESTBIT,
98    Modulo = opcodes::MODULO,
99    Pow = opcodes::POW,
100    InvPow = opcodes::INVPOW,
101    And = opcodes::AND,
102    Or = opcodes::OR,
103    Min = opcodes::MIN,
104    Max = opcodes::MAX,
105    Scale = opcodes::SCALE,
106    BitCount = opcodes::BITCOUNT,
107    ToggleBit = opcodes::TOGGLEBIT,
108    SetBitRange = opcodes::SETBIT_RANGE,
109    ClearBitRange = opcodes::CLEARBIT_RANGE,
110    GetBitRange = opcodes::GETBIT_RANGE,
111    SetBitRangeToVal = opcodes::SETBIT_RANGE_TOINT,
112    SinDeg = opcodes::SIN_DEG,
113    CosDeg = opcodes::COS_DEG,
114    Atan2Deg = opcodes::ATAN2_DEG,
115    Abs = opcodes::ABS,
116    // String operations (4200+ range)
117    // Command is used for engine commands - opcode is looked up dynamically
118    Command = 65535,
119    Raw = 65533,
120    BranchIfTrue = 65532,
121    BranchIfFalse = 65531,
122    // Line number metadata (not a real opcode, used for debugging)
123    LineNumber = 65534,
124}
125
126impl Opcode {
127    /// The opcode that reads a game var of `category`.
128    pub fn push_var(category: &str) -> Self {
129        match category {
130            "varn" => Self::PushVarn,
131            "vars" => Self::PushVars,
132            "varpbit" => Self::PushVarpBit,
133            "varc" => Self::PushVarcInt,
134            "varcstr" => Self::PushVarcString,
135            "varclan" => Self::PushVarClan,
136            "varclan_bit" => Self::PushVarClanBit,
137            "varclan_long" => Self::PushVarClanLong,
138            "varclan_string" => Self::PushVarClanString,
139            "varobj" => Self::PushVarObj,
140            "varnbit" => Self::PushVarnBit,
141            "varcon" => Self::PushVarCon,
142            "varconbit" => Self::PushVarConBit,
143            "clansetting_int" => Self::PushClanSettingInt,
144            "clansetting_varbit" => Self::PushClanSettingVarbit,
145            "clansetting_long" => Self::PushClanSettingLong,
146            "clansetting_string" => Self::PushClanSettingString,
147            _ => Self::PushVarp,
148        }
149    }
150
151    /// The opcode that writes a game var of `category`.
152    pub fn pop_var(category: &str) -> Self {
153        match category {
154            "varn" => Self::PopVarn,
155            "vars" => Self::PopVars,
156            "varpbit" => Self::PopVarpBit,
157            "varc" => Self::PopVarcInt,
158            "varcstr" => Self::PopVarcString,
159            "varclan" => Self::PopVarClan,
160            "varobj" => Self::PopVarObj,
161            "varnbit" => Self::PopVarnBit,
162            "varcon" => Self::PopVarCon,
163            "varconbit" => Self::PopVarConBit,
164            "clansetting_int" => Self::PopClanSettingInt,
165            "clansetting_varbit" => Self::PopClanSettingVarbit,
166            "clansetting_long" => Self::PopClanSettingLong,
167            "clansetting_string" => Self::PopClanSettingString,
168            _ => Self::PopVarp,
169        }
170    }
171
172    pub fn core(name: &str) -> Option<Self> {
173        match name {
174            "PushConstantInt" => Some(Self::PushConstantInt),
175            "PushConstantString" => Some(Self::PushConstantString),
176            "PushConstantLong" => Some(Self::PushConstantLong),
177            "PushVarp" => Some(Self::PushVarp),
178            "PopVarp" => Some(Self::PopVarp),
179            "PushVarn" => Some(Self::PushVarn),
180            "PopVarn" => Some(Self::PopVarn),
181            "PushVars" => Some(Self::PushVars),
182            "PopVars" => Some(Self::PopVars),
183            "PushVarpBit" => Some(Self::PushVarpBit),
184            "PopVarpBit" => Some(Self::PopVarpBit),
185            "PushVarcInt" => Some(Self::PushVarcInt),
186            "PopVarcInt" => Some(Self::PopVarcInt),
187            "PushVarcString" => Some(Self::PushVarcString),
188            "PopVarcString" => Some(Self::PopVarcString),
189            "PushClanSettingInt" => Some(Self::PushClanSettingInt),
190            "PushClanSettingVarbit" => Some(Self::PushClanSettingVarbit),
191            "PushClanSettingLong" => Some(Self::PushClanSettingLong),
192            "PushClanSettingString" => Some(Self::PushClanSettingString),
193            "PushVarClan" => Some(Self::PushVarClan),
194            "PushVarClanBit" => Some(Self::PushVarClanBit),
195            "PushVarClanLong" => Some(Self::PushVarClanLong),
196            "PushVarClanString" => Some(Self::PushVarClanString),
197            "PushVarPlayer" => Some(Self::PushVarPlayer),
198            "PushVarPlayerBit" => Some(Self::PushVarPlayerBit),
199            "PushVarNpc" => Some(Self::PushVarNpc),
200            "PushVarNpcBit" => Some(Self::PushVarNpcBit),
201            "Branch" => Some(Self::Branch),
202            "BranchNot" => Some(Self::BranchNot),
203            "BranchEquals" => Some(Self::BranchEquals),
204            "BranchLessThan" => Some(Self::BranchLessThan),
205            "BranchGreaterThan" => Some(Self::BranchGreaterThan),
206            "BranchLessThanOrEquals" => Some(Self::BranchLessThanOrEquals),
207            "BranchGreaterThanOrEquals" => Some(Self::BranchGreaterThanOrEquals),
208            "LongBranchNot" => Some(Self::LongBranchNot),
209            "LongBranchEquals" => Some(Self::LongBranchEquals),
210            "LongBranchLessThan" => Some(Self::LongBranchLessThan),
211            "LongBranchGreaterThan" => Some(Self::LongBranchGreaterThan),
212            "LongBranchLessThanOrEquals" => Some(Self::LongBranchLessThanOrEquals),
213            "LongBranchGreaterThanOrEquals" => Some(Self::LongBranchGreaterThanOrEquals),
214            "BranchIfTrue" => Some(Self::BranchIfTrue),
215            "BranchIfFalse" => Some(Self::BranchIfFalse),
216            "ObjBranchEquals" => Some(Self::ObjBranchEquals),
217            "ObjBranchNot" => Some(Self::ObjBranchNot),
218            "Return" => Some(Self::Return),
219            "Gosub" => Some(Self::Gosub),
220            "GosubWithParams" => Some(Self::GosubWithParams),
221            "Jump" => Some(Self::Jump),
222            "JumpWithParams" => Some(Self::JumpWithParams),
223            "Switch" => Some(Self::Switch),
224            "PushIntLocal" => Some(Self::PushIntLocal),
225            "PopIntLocal" => Some(Self::PopIntLocal),
226            "PushStringLocal" => Some(Self::PushStringLocal),
227            "PopStringLocal" => Some(Self::PopStringLocal),
228            "PushLongLocal" => Some(Self::PushLongLocal),
229            "PopLongLocal" => Some(Self::PopLongLocal),
230            "PopIntDiscard" => Some(Self::PopIntDiscard),
231            "PopStringDiscard" => Some(Self::PopStringDiscard),
232            "PopLongDiscard" => Some(Self::PopLongDiscard),
233            "JoinString" => Some(Self::JoinString),
234            "DefineArray" => Some(Self::DefineArray),
235            "PushArrayInt" => Some(Self::PushArrayInt),
236            "PopArrayInt" => Some(Self::PopArrayInt),
237            _ => None,
238        }
239    }
240}
241
242/// A single instruction in the compiled bytecode.
243#[derive(Debug, Clone)]
244pub struct Instruction {
245    pub opcode: Opcode,
246    pub operand: Operand,
247}
248
249/// The operand (data) associated with an instruction.
250///
251/// Kept as small as possible (each script holds a `Vec<Instruction>`, and the
252/// corpus runs to ~half a million instructions): the two heap-backed payloads —
253/// string literals and switch tables — live in side pools on the owning
254/// `CompiledScript`, and the operand stores only a `u32` index into them. That
255/// keeps every variant ≤ 8 B, so `Operand` is 16 B and `Instruction` is 24 B
256/// (vs 24/32 when the payloads were inline `Box<str>`/`Box<[_]>`).
257#[derive(Debug, Clone)]
258pub enum Operand {
259    None,
260    Int(i32),
261    Long(i64),
262    Str(u32),
263    JumpTarget(usize),
264    SwitchTable(u32),
265    StringCount(u32),
266    ArrayDef(i32, u8),
267}
268
269impl Instruction {
270    pub fn new(opcode: Opcode, operand: Operand) -> Self {
271        Instruction { opcode, operand }
272    }
273
274    pub fn simple(opcode: Opcode) -> Self {
275        Instruction {
276            opcode,
277            operand: Operand::None,
278        }
279    }
280
281    pub fn push_int(value: i32) -> Self {
282        Instruction::new(Opcode::PushConstantInt, Operand::Int(value))
283    }
284
285    pub fn push_long(value: i64) -> Self {
286        Instruction::new(Opcode::PushConstantLong, Operand::Long(value))
287    }
288
289    pub fn jump(target: usize) -> Self {
290        Instruction::new(Opcode::Branch, Operand::JumpTarget(target))
291    }
292
293    pub fn branch_not(target: usize) -> Self {
294        Instruction::new(Opcode::BranchNot, Operand::JumpTarget(target))
295    }
296
297    pub fn branch_equals(target: usize) -> Self {
298        Instruction::new(Opcode::BranchEquals, Operand::JumpTarget(target))
299    }
300
301    pub fn branch_less_than(target: usize) -> Self {
302        Instruction::new(Opcode::BranchLessThan, Operand::JumpTarget(target))
303    }
304
305    pub fn branch_greater_than(target: usize) -> Self {
306        Instruction::new(Opcode::BranchGreaterThan, Operand::JumpTarget(target))
307    }
308
309    pub fn branch_less_than_or_equals(target: usize) -> Self {
310        Instruction::new(Opcode::BranchLessThanOrEquals, Operand::JumpTarget(target))
311    }
312
313    pub fn branch_greater_than_or_equals(target: usize) -> Self {
314        Instruction::new(
315            Opcode::BranchGreaterThanOrEquals,
316            Operand::JumpTarget(target),
317        )
318    }
319
320    pub fn gosub(script_id: i32) -> Self {
321        Instruction::new(Opcode::Gosub, Operand::Int(script_id))
322    }
323
324    pub fn gosub_with_params(script_id: i32) -> Self {
325        Instruction::new(Opcode::GosubWithParams, Operand::Int(script_id))
326    }
327
328    pub fn push_int_local(var_id: i32) -> Self {
329        Instruction::new(Opcode::PushIntLocal, Operand::Int(var_id))
330    }
331
332    pub fn pop_int_local(var_id: i32) -> Self {
333        Instruction::new(Opcode::PopIntLocal, Operand::Int(var_id))
334    }
335
336    pub fn push_string_local(var_id: i32) -> Self {
337        Instruction::new(Opcode::PushStringLocal, Operand::Int(var_id))
338    }
339
340    pub fn pop_string_local(var_id: i32) -> Self {
341        Instruction::new(Opcode::PopStringLocal, Operand::Int(var_id))
342    }
343
344    pub fn push_long_local(var_id: i32) -> Self {
345        Instruction::new(Opcode::PushLongLocal, Operand::Int(var_id))
346    }
347
348    pub fn pop_long_local(var_id: i32) -> Self {
349        Instruction::new(Opcode::PopLongLocal, Operand::Int(var_id))
350    }
351
352    pub fn join_string(count: u32) -> Self {
353        Instruction::new(Opcode::JoinString, Operand::StringCount(count))
354    }
355}
356
357/// Compiled bytecode for a single script.
358#[derive(Debug, Clone)]
359pub struct CompiledScript {
360    pub name: String,
361    pub id: i32,
362    pub trigger: String,
363    pub source_path: String,
364    pub lookup_key: i32,
365    pub param_types: Vec<crate::types::Type>,
366    pub instructions: Vec<Instruction>,
367    pub local_table: crate::symbol::LocalTable,
368    pub int_local_count: u16,
369    pub string_local_count: u16,
370    pub long_local_count: u16,
371    pub int_arg_count: u16,
372    pub string_arg_count: u16,
373    pub long_arg_count: u16,
374    pub strings: Vec<Box<str>>,
375    pub switch_tables: Vec<Box<[(i32, usize)]>>,
376}
377
378impl CompiledScript {
379    pub fn new(name: String, id: i32) -> Self {
380        Self {
381            name,
382            id,
383            trigger: String::new(),
384            source_path: String::new(),
385            lookup_key: -1,
386            param_types: Vec::new(),
387            instructions: Vec::new(),
388            local_table: crate::symbol::LocalTable::new(),
389            int_local_count: 0,
390            string_local_count: 0,
391            long_local_count: 0,
392            int_arg_count: 0,
393            string_arg_count: 0,
394            long_arg_count: 0,
395            strings: Vec::new(),
396            switch_tables: Vec::new(),
397        }
398    }
399
400    pub fn push(&mut self, instruction: Instruction) {
401        self.instructions.push(instruction);
402    }
403
404    /// Add a string payload to the pool and return its `Operand::Str` index.
405    pub fn intern_str(&mut self, value: String) -> u32 {
406        let idx = self.strings.len() as u32;
407        self.strings.push(value.into_boxed_str());
408        idx
409    }
410
411    /// Emit a `PushConstantString` whose literal is interned into the pool.
412    pub fn push_string(&mut self, value: String) {
413        let idx = self.intern_str(value);
414        self.instructions.push(Instruction::new(
415            Opcode::PushConstantString,
416            Operand::Str(idx),
417        ));
418    }
419
420    pub fn len(&self) -> usize {
421        self.instructions.len()
422    }
423
424    pub fn is_empty(&self) -> bool {
425        self.instructions.is_empty()
426    }
427
428    /// Update a jump target at the given instruction index.
429    pub fn patch_jump(&mut self, index: usize, target: usize) {
430        self.instructions[index].operand = Operand::JumpTarget(target);
431    }
432
433    /// Release the spare capacity the growable codegen buffers left behind.
434    /// Compiled scripts are immutable after codegen but are held in memory for
435    /// the whole pointer-check + write phase, so reclaiming each `Vec`'s doubling
436    /// slack (often 25-50%) meaningfully lowers the resident footprint.
437    pub fn shrink_to_fit(&mut self) {
438        self.instructions.shrink_to_fit();
439        self.param_types.shrink_to_fit();
440        self.local_table.shrink_to_fit();
441        self.strings.shrink_to_fit();
442        self.switch_tables.shrink_to_fit();
443    }
444}