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