1use std::sync::Arc;
2
3use arc_gc::gc::GC;
4
5use crate::{
6 lambda::runnable::{Runnable, RuntimeError, StepResult},
7 types::{
8 lambda::vm_instructions::opcode::get_processed_opcode,
9 object::{OnionObject, OnionObjectCell, OnionStaticObject},
10 },
11};
12
13use super::{
14 context::{Context, Frame},
15 vm_instructions::{
16 self,
17 instruction_set::{VMInstruction, VMInstructionPackage},
18 opcode::ProcessedOpcode,
19 },
20};
21
22type InstructionHandler =
23 fn(&mut OnionLambdaRunnable, &ProcessedOpcode, &mut GC<OnionObjectCell>) -> StepResult;
24
25static INSTRUCTION_TABLE: std::sync::LazyLock<Vec<InstructionHandler>> =
27 std::sync::LazyLock::new(|| {
28 let mut instruction_table: Vec<InstructionHandler> = vec![
29 |_, opcode, _| StepResult::Error(RuntimeError::DetailedError(format!("Invalid instruction: {:?}", opcode).into())); 256 ];
32
33 instruction_table[VMInstruction::LoadNull as usize] = vm_instructions::load_null;
36 instruction_table[VMInstruction::LoadInt32 as usize] = vm_instructions::load_int;
37 instruction_table[VMInstruction::LoadInt64 as usize] = vm_instructions::load_int;
38 instruction_table[VMInstruction::LoadFloat32 as usize] = vm_instructions::load_float;
39 instruction_table[VMInstruction::LoadFloat64 as usize] = vm_instructions::load_float;
40 instruction_table[VMInstruction::LoadString as usize] = vm_instructions::load_string;
41 instruction_table[VMInstruction::LoadBytes as usize] = vm_instructions::load_bytes;
42 instruction_table[VMInstruction::LoadBool as usize] = vm_instructions::load_bool;
43 instruction_table[VMInstruction::LoadLambda as usize] = vm_instructions::load_lambda;
44 instruction_table[VMInstruction::LoadUndefined as usize] = vm_instructions::load_undefined;
45
46 instruction_table[VMInstruction::BuildTuple as usize] = vm_instructions::build_tuple;
48 instruction_table[VMInstruction::BuildKeyValue as usize] = vm_instructions::build_keyval;
49 instruction_table[VMInstruction::BuildNamed as usize] = vm_instructions::build_named;
50 instruction_table[VMInstruction::BuildRange as usize] = vm_instructions::build_range;
51 instruction_table[VMInstruction::BuildSet as usize] = vm_instructions::build_set;
52 instruction_table[VMInstruction::BinaryIn as usize] = vm_instructions::is_in;
54 instruction_table[VMInstruction::BinaryIs as usize] = vm_instructions::check_is_same_object;
55
56 instruction_table[VMInstruction::BinaryAdd as usize] = vm_instructions::binary_add;
57 instruction_table[VMInstruction::BinarySub as usize] = vm_instructions::binary_subtract;
58 instruction_table[VMInstruction::BinaryMul as usize] = vm_instructions::binary_multiply;
59 instruction_table[VMInstruction::BinaryDiv as usize] = vm_instructions::binary_divide;
60 instruction_table[VMInstruction::BinaryMod as usize] = vm_instructions::binary_modulus;
61 instruction_table[VMInstruction::BinaryPow as usize] = vm_instructions::binary_power;
62 instruction_table[VMInstruction::BinaryBitAnd as usize] =
63 vm_instructions::binary_bitwise_and;
64 instruction_table[VMInstruction::BinaryBitOr as usize] = vm_instructions::binary_bitwise_or;
65 instruction_table[VMInstruction::BinaryBitXor as usize] =
66 vm_instructions::binary_bitwise_xor;
67 instruction_table[VMInstruction::BinaryShl as usize] = vm_instructions::binary_shift_left;
68 instruction_table[VMInstruction::BinaryShr as usize] = vm_instructions::binary_shift_right;
69 instruction_table[VMInstruction::BinaryEq as usize] = vm_instructions::binary_equal;
70 instruction_table[VMInstruction::BinaryNe as usize] = vm_instructions::binary_not_equal;
71 instruction_table[VMInstruction::BinaryGt as usize] = vm_instructions::binary_greater;
72 instruction_table[VMInstruction::BinaryLt as usize] = vm_instructions::binary_less;
73 instruction_table[VMInstruction::BinaryGe as usize] = vm_instructions::binary_greater_equal;
74 instruction_table[VMInstruction::BinaryLe as usize] = vm_instructions::binary_less_equal;
75 instruction_table[VMInstruction::MapTo as usize] = vm_instructions::map_to;
76
77 instruction_table[VMInstruction::UnaryBitNot as usize] = vm_instructions::unary_bitwise_not;
79 instruction_table[VMInstruction::UnaryAbs as usize] = vm_instructions::unary_plus;
80 instruction_table[VMInstruction::UnaryNeg as usize] = vm_instructions::unary_minus;
81
82 instruction_table[VMInstruction::StoreVar as usize] = vm_instructions::let_var;
84 instruction_table[VMInstruction::LoadVar as usize] = vm_instructions::get_var;
85 instruction_table[VMInstruction::SetValue as usize] = vm_instructions::set_var;
86 instruction_table[VMInstruction::GetAttr as usize] = vm_instructions::get_attr;
87 instruction_table[VMInstruction::IndexOf as usize] = vm_instructions::index_of;
88 instruction_table[VMInstruction::KeyOf as usize] = vm_instructions::key_of;
89 instruction_table[VMInstruction::ValueOf as usize] = vm_instructions::value_of;
90 instruction_table[VMInstruction::TypeOf as usize] = vm_instructions::type_of;
91 instruction_table[VMInstruction::ShallowCopy as usize] = vm_instructions::copy;
92 instruction_table[VMInstruction::Swap as usize] = vm_instructions::swap;
93 instruction_table[VMInstruction::LengthOf as usize] = vm_instructions::get_length;
94 instruction_table[VMInstruction::Mut as usize] = vm_instructions::mutablize;
95 instruction_table[VMInstruction::Const as usize] = vm_instructions::immutablize;
96 instruction_table[VMInstruction::ForkInstruction as usize] =
97 vm_instructions::fork_instruction;
98 instruction_table[VMInstruction::Launch as usize] = vm_instructions::launch_thread;
99
100 instruction_table[VMInstruction::Call as usize] = vm_instructions::call_lambda;
102 instruction_table[VMInstruction::AsyncCall as usize] = vm_instructions::async_call;
103 instruction_table[VMInstruction::SyncCall as usize] = vm_instructions::sync_call;
104 instruction_table[VMInstruction::Return as usize] = vm_instructions::return_value;
105 instruction_table[VMInstruction::Raise as usize] = vm_instructions::raise;
106 instruction_table[VMInstruction::Jump as usize] = vm_instructions::jump;
107 instruction_table[VMInstruction::JumpIfFalse as usize] = vm_instructions::jump_if_false;
108
109 instruction_table[VMInstruction::NewFrame as usize] = vm_instructions::new_frame;
111 instruction_table[VMInstruction::PopFrame as usize] = vm_instructions::pop_frame;
112 instruction_table[VMInstruction::ResetStack as usize] = vm_instructions::clear_stack;
113 instruction_table[VMInstruction::Pop as usize] = vm_instructions::discard_top;
114
115 instruction_table[VMInstruction::Import as usize] = vm_instructions::import;
117
118 instruction_table[VMInstruction::Assert as usize] = vm_instructions::assert;
119
120 instruction_table
121 });
122
123pub struct OnionLambdaRunnable {
124 pub(crate) argument: OnionStaticObject,
125 pub(crate) result: OnionStaticObject,
126 pub(crate) this_lambda: OnionStaticObject,
127 pub(crate) context: Context,
128 pub(crate) ip: isize, pub(crate) instruction: Arc<VMInstructionPackage>,
130}
131
132impl OnionLambdaRunnable {
133 pub fn new(
134 argument: OnionStaticObject,
135 self_object: &OnionObject,
136 this_lambda: &OnionStaticObject,
137 instruction: Arc<VMInstructionPackage>,
138 ip: isize,
139 ) -> Result<Self, RuntimeError> {
140 let mut new_context = Context::new();
141 Context::push_frame(
142 &mut new_context,
143 Frame {
144 variables: rustc_hash::FxHashMap::default(),
145 stack: Vec::new(),
146 },
147 );
148
149 let (index_this, index_self, index_arguments) = {
150 let string_pool = instruction.get_string_pool();
151
152 let index_this = string_pool
153 .iter()
154 .position(|s| s == "this")
155 .ok_or_else(|| {
156 RuntimeError::InvalidOperation(
157 "Missing required variable 'this' in string pool"
158 .to_string()
159 .into(),
160 )
161 })?;
162
163 let index_self = string_pool
164 .iter()
165 .position(|s| s == "self")
166 .ok_or_else(|| {
167 RuntimeError::InvalidOperation(
168 "Missing required variable 'self' in string pool"
169 .to_string()
170 .into(),
171 )
172 })?;
173
174 let index_arguments = string_pool
175 .iter()
176 .position(|s| s == "arguments")
177 .ok_or_else(|| {
178 RuntimeError::InvalidOperation(
179 "Missing required variable 'arguments' in string pool"
180 .to_string()
181 .into(),
182 )
183 })?;
184
185 (index_this, index_self, index_arguments)
186 };
187
188 new_context
190 .let_variable(index_this, this_lambda.clone())
191 .map_err(|e| {
192 RuntimeError::InvalidOperation(
193 format!("Failed to initialize 'this' variable: {}", e).into(),
194 )
195 })?;
196
197 new_context
198 .let_variable(index_self, self_object.stabilize())
199 .map_err(|e| {
200 RuntimeError::InvalidOperation(
201 format!("Failed to initialize 'self' variable: {}", e).into(),
202 )
203 })?;
204
205 new_context
206 .let_variable(index_arguments, argument.clone())
207 .map_err(|e| {
208 RuntimeError::InvalidOperation(
209 format!("Failed to initialize 'arguments' variable: {}", e).into(),
210 )
211 })?;
212
213 let pool = instruction.get_string_pool();
214
215 argument.weak().with_data(|data| {
216 if let OnionObject::Tuple(tuple) = data {
217 for item in tuple.get_elements().iter() {
218 match item {
219 OnionObject::Named(named) => {
220 named.get_key().with_data(|key| match key {
221 OnionObject::String(key_str) => {
222 match pool.iter().position(|s| s.eq(key_str.as_ref())) {
223 Some(index) => new_context
224 .let_variable(index, named.get_value().stabilize()),
225 None => {
226 Ok(())
228 }
229 }
230 }
231 _ => Ok(()),
232 })?;
233 }
234 _ => {}
235 }
236 }
237 Ok(())
238 } else {
239 Err(RuntimeError::InvalidOperation(
240 "Argument must be a tuple".to_string().into(),
241 ))
242 }
243 })?;
244
245 Ok(OnionLambdaRunnable {
246 argument,
247 this_lambda: this_lambda.clone(),
248 result: OnionStaticObject::default(),
249 context: new_context,
250 ip,
251 instruction,
252 })
253 }
254}
255
256impl Runnable for OnionLambdaRunnable {
257 fn receive(
258 &mut self,
259 step_result: &StepResult,
260 _gc: &mut GC<OnionObjectCell>,
261 ) -> Result<(), RuntimeError> {
262 if let StepResult::Return(result) = step_result {
263 self.context.push_object(result.as_ref().clone())?;
264 Ok(())
265 } else {
266 Err(RuntimeError::DetailedError(
267 "receive not implemented for cases except `Return`"
268 .to_string()
269 .into(),
270 ))
271 }
272 }
273 fn step(&mut self, gc: &mut GC<OnionObjectCell>) -> StepResult {
274 const MAX_INLINE_STEPS: usize = 1024;
275
276 let mut steps = 0;
277
278 let (code_ptr, code_len) = {
280 let code = self.instruction.get_code();
281 (code.as_ptr(), code.len())
282 };
283
284 loop {
285 if steps >= MAX_INLINE_STEPS {
286 break;
287 }
288 steps += 1;
289
290 let mut ip = self.ip as usize;
291 if ip >= code_len {
292 return StepResult::Error(RuntimeError::DetailedError(
293 "Instruction pointer out of bounds".to_string().into(),
294 ));
295 }
296
297 let code = unsafe { std::slice::from_raw_parts(code_ptr, code_len) };
299 let opcode = get_processed_opcode(code, &mut ip);
300
301 let handler = unsafe { *INSTRUCTION_TABLE.get_unchecked(opcode.instruction as usize) };
302 self.ip = ip as isize;
303
304 match handler(self, &opcode, gc) {
305 StepResult::Continue => continue,
306 v => return v,
307 }
308 }
309
310 StepResult::Continue
311 }
312 fn copy(&self) -> Box<dyn Runnable> {
313 Box::new(OnionLambdaRunnable {
314 argument: self.argument.clone(),
315 this_lambda: self.this_lambda.clone(),
316 result: self.result.clone(),
317 context: self.context.clone(),
318 ip: self.ip,
319 instruction: self.instruction.clone(),
320 })
321 }
322
323 fn format_context(&self) -> Result<serde_json::Value, RuntimeError> {
324 let mut stack_json_array = serde_json::Value::Array(vec![]);
325 for frame in &self.context.frames {
326 let frame_json = frame.format_context();
327 stack_json_array.as_array_mut().unwrap().push(frame_json);
328 }
329 Ok(serde_json::json!({
331 "type": "lambda_runnable",
332 "frames": stack_json_array,
333 "ip": self.ip,
334 "argument": self.argument.to_string(),
335 "this_lambda": self.this_lambda.to_string(),
336 "result": self.result.to_string(),
337 }))
338 }
339}
340#[cfg(test)]
341mod size_tests {
342 use super::*;
343
344 #[test]
345 fn print_sizes() {
346 println!("StepResult size: {}", std::mem::size_of::<StepResult>());
347 println!("RuntimeError size: {}", std::mem::size_of::<RuntimeError>());
348 println!("StepResult size: {}", std::mem::size_of::<StepResult>());
349 }
350}