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)]
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    DefineArray = 44,
36    PushArrayInt = 45,
37    PopArrayInt = 46,
38    PushConstantLong = 54,
39    PushLongLocal = 55,
40    PopLongLocal = 56,
41    PopLongDiscard = 57,
42    // Long branch operations
43    LongBranchNot = 68,
44    LongBranchEquals = 69,
45    LongBranchLessThan = 70,
46    LongBranchGreaterThan = 71,
47    LongBranchLessThanOrEquals = 72,
48    LongBranchGreaterThanOrEquals = 73,
49    // Object/string branch operations
50    ObjBranchEquals = 86,
51    ObjBranchNot = 87,
52    // Arithmetic operations (4600+ range — engine commands)
53    Add = 4600,
54    Sub = 4601,
55    Multiply = 4602,
56    Divide = 4603,
57    Random = 4604,
58    RandomInc = 4605,
59    Interpolate = 4606,
60    AddPercent = 4607,
61    SetBit = 4608,
62    ClearBit = 4609,
63    TestBit = 4610,
64    Modulo = 4611,
65    Pow = 4612,
66    InvPow = 4613,
67    And = 4614,
68    Or = 4615,
69    Min = 4616,
70    Max = 4617,
71    Scale = 4618,
72    BitCount = 4619,
73    ToggleBit = 4620,
74    SetBitRange = 4621,
75    ClearBitRange = 4622,
76    GetBitRange = 4623,
77    SetBitRangeToVal = 4624,
78    SinDeg = 4625,
79    CosDeg = 4626,
80    Atan2Deg = 4627,
81    Abs = 4628,
82    // String operations (4200+ range)
83    // Command is used for engine commands - opcode is looked up dynamically
84    Command = 65535,
85    // Line number metadata (not a real opcode, used for debugging)
86    LineNumber = 65534,
87}
88
89/// A single instruction in the compiled bytecode.
90#[derive(Debug, Clone)]
91pub struct Instruction {
92    pub opcode: Opcode,
93    pub operand: Operand,
94    pub line: Option<u32>,
95}
96
97/// The operand (data) associated with an instruction.
98#[derive(Debug, Clone)]
99pub enum Operand {
100    None,
101    Int(i32),
102    Long(i64),
103    Str(String),
104    /// Jump target as instruction index within the script
105    JumpTarget(usize),
106    /// Switch table: list of (case_value, jump_target) pairs
107    SwitchTable(Vec<(i32, usize)>),
108    /// String join with N parts
109    StringCount(u32),
110    /// Array definition: (var_id, element_type_char)
111    ArrayDef(i32, u8),
112}
113
114impl Instruction {
115    pub fn new(opcode: Opcode, operand: Operand) -> Self {
116        Instruction {
117            opcode,
118            operand,
119            line: None,
120        }
121    }
122
123    pub fn with_line(opcode: Opcode, operand: Operand, line: u32) -> Self {
124        Instruction {
125            opcode,
126            operand,
127            line: Some(line),
128        }
129    }
130
131    pub fn simple(opcode: Opcode) -> Self {
132        Instruction {
133            opcode,
134            operand: Operand::None,
135            line: None,
136        }
137    }
138
139    pub fn push_int(value: i32) -> Self {
140        Instruction::new(Opcode::PushConstantInt, Operand::Int(value))
141    }
142
143    pub fn push_string(value: String) -> Self {
144        Instruction::new(Opcode::PushConstantString, Operand::Str(value))
145    }
146
147    pub fn push_long(value: i64) -> Self {
148        Instruction::new(Opcode::PushConstantLong, Operand::Long(value))
149    }
150
151    pub fn jump(target: usize) -> Self {
152        Instruction::new(Opcode::Branch, Operand::JumpTarget(target))
153    }
154
155    pub fn branch_not(target: usize) -> Self {
156        Instruction::new(Opcode::BranchNot, Operand::JumpTarget(target))
157    }
158
159    pub fn branch_equals(target: usize) -> Self {
160        Instruction::new(Opcode::BranchEquals, Operand::JumpTarget(target))
161    }
162
163    pub fn branch_less_than(target: usize) -> Self {
164        Instruction::new(Opcode::BranchLessThan, Operand::JumpTarget(target))
165    }
166
167    pub fn branch_greater_than(target: usize) -> Self {
168        Instruction::new(Opcode::BranchGreaterThan, Operand::JumpTarget(target))
169    }
170
171    pub fn branch_less_than_or_equals(target: usize) -> Self {
172        Instruction::new(Opcode::BranchLessThanOrEquals, Operand::JumpTarget(target))
173    }
174
175    pub fn branch_greater_than_or_equals(target: usize) -> Self {
176        Instruction::new(
177            Opcode::BranchGreaterThanOrEquals,
178            Operand::JumpTarget(target),
179        )
180    }
181
182    pub fn gosub(script_id: i32) -> Self {
183        Instruction::new(Opcode::Gosub, Operand::Int(script_id))
184    }
185
186    pub fn gosub_with_params(script_id: i32) -> Self {
187        Instruction::new(Opcode::GosubWithParams, Operand::Int(script_id))
188    }
189
190    pub fn push_int_local(var_id: i32) -> Self {
191        Instruction::new(Opcode::PushIntLocal, Operand::Int(var_id))
192    }
193
194    pub fn pop_int_local(var_id: i32) -> Self {
195        Instruction::new(Opcode::PopIntLocal, Operand::Int(var_id))
196    }
197
198    pub fn push_string_local(var_id: i32) -> Self {
199        Instruction::new(Opcode::PushStringLocal, Operand::Int(var_id))
200    }
201
202    pub fn pop_string_local(var_id: i32) -> Self {
203        Instruction::new(Opcode::PopStringLocal, Operand::Int(var_id))
204    }
205
206    pub fn push_long_local(var_id: i32) -> Self {
207        Instruction::new(Opcode::PushLongLocal, Operand::Int(var_id))
208    }
209
210    pub fn pop_long_local(var_id: i32) -> Self {
211        Instruction::new(Opcode::PopLongLocal, Operand::Int(var_id))
212    }
213
214    pub fn join_string(count: u32) -> Self {
215        Instruction::new(Opcode::JoinString, Operand::StringCount(count))
216    }
217}
218
219/// Compiled bytecode for a single script.
220#[derive(Debug, Clone)]
221pub struct CompiledScript {
222    pub name: String,
223    pub id: i32,
224    pub trigger: String,
225    pub source_path: String,
226    /// Lookup key for fast engine dispatch (-1 if not applicable).
227    pub lookup_key: i32,
228    pub param_types: Vec<crate::types::Type>,
229    pub instructions: Vec<Instruction>,
230    pub local_table: crate::symbol::LocalTable,
231    pub int_local_count: u16,
232    pub string_local_count: u16,
233    pub long_local_count: u16,
234    pub int_arg_count: u16,
235    pub string_arg_count: u16,
236    pub long_arg_count: u16,
237    pub switch_tables: Vec<Vec<(i32, usize)>>,
238}
239
240impl CompiledScript {
241    pub fn new(name: String, id: i32) -> Self {
242        Self {
243            name,
244            id,
245            trigger: String::new(),
246            source_path: String::new(),
247            lookup_key: -1,
248            param_types: Vec::new(),
249            instructions: Vec::new(),
250            local_table: crate::symbol::LocalTable::new(),
251            int_local_count: 0,
252            string_local_count: 0,
253            long_local_count: 0,
254            int_arg_count: 0,
255            string_arg_count: 0,
256            long_arg_count: 0,
257            switch_tables: Vec::new(),
258        }
259    }
260
261    pub fn push(&mut self, instruction: Instruction) {
262        self.instructions.push(instruction);
263    }
264
265    pub fn len(&self) -> usize {
266        self.instructions.len()
267    }
268
269    pub fn is_empty(&self) -> bool {
270        self.instructions.is_empty()
271    }
272
273    /// Update a jump target at the given instruction index.
274    pub fn patch_jump(&mut self, index: usize, target: usize) {
275        self.instructions[index].operand = Operand::JumpTarget(target);
276    }
277}