1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
use crate::program::{Function, SymbolEntry, Instruction, Program, CallTarget};
use crate::variant::Variant;
use log::{debug, trace};
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use std::time::Duration;
macro_rules! runtime_error {
($($arg:tt)*) => {
Err(VmError::RuntimeError {
message: format!($($arg)*)
})
};
}
macro_rules! stack_pop {
($stack:expr) => {
$stack.pop().expect("Operand stack should not be empty")
};
}
#[derive(Clone, Default, Debug, PartialEq)]
pub struct VmExecutionResult {
pub result: Option<Variant>,
pub run_time: Duration,
}
#[derive(Clone, Debug, PartialEq)]
pub enum VmError {
RuntimeError {
message: String,
},
RuntimeWarning {
message: String,
}
}
#[derive(Clone, Default, Debug, PartialEq)]
struct StackFrame {
function_index: usize,
pc: usize,
stack_base_pointer: usize,
}
#[derive(Clone, Default, Debug, PartialEq)]
pub struct Vm {
functions: Vec<Function>,
symbols: HashMap<String, SymbolEntry>,
native_functions: HashMap<String, fn(Vec<Variant>) -> Option<Variant>>
}
impl Vm {
pub fn register_native_function(&mut self, name: String, arity: usize, function: fn(Vec<Variant>) -> Option<Variant>) {
self.native_functions.insert(name.clone(), function);
self.symbols.insert(name.clone(), SymbolEntry::NativeFunction {
arity
});
}
pub fn load_program(&mut self, program: Program) {
debug!("Loaded program");
trace!("Globals: {:?}", program.symbol_table);
trace!("Functions: {:?}", program.functions);
self.functions.extend(program.functions);
self.symbols.extend(program.symbol_table.into_iter());
}
/// Executes the program with the given entry point and parameters.
/// If no entry point is provided, it defaults to "main".
pub fn run(&mut self, entry_point: Option<String>, _parameters: Option<Vec<Variant>>) -> Result<VmExecutionResult, VmError> {
let timer = std::time::Instant::now();
// frames
let frames = &mut Vec::with_capacity(32);
// stack
let mut stack = Vec::with_capacity(1024);
// use entry point or default to main
let entry_point = entry_point.unwrap_or_else(|| String::from("main"));
// Get the function to execute
let mut function_index = match self.symbols.get(entry_point.as_str()) {
Some(SymbolEntry::UserDefinedFunction { index, .. }) => {
match self.functions.get(*index) {
Some(_) => *index,
None => return runtime_error!("Function not found: {}", entry_point)
}
},
Some(SymbolEntry::NativeFunction { .. }) => {
return runtime_error!("Cannot execute native function as entry point: {}", entry_point);
},
_ => return runtime_error!("Entry point not found: {}", entry_point)
};
// Initialize the function's local variables
stack.resize(self.functions[function_index].local_count, Variant::Null);
// Initialize the stack frame
let mut pc = 0;
let mut stack_base_pointer = 0;
debug!("Starting execution of function: {}", self.functions[function_index].name);
let mut result = None;
loop {
// trace!("========================================");
// trace!("Frame[{}]: Stack: {:?}", frames.len(), stack);
// trace!("Frame[{}]: Base pointer: {}", frames.len(), stack_base_pointer);
// trace!("Frame[{}]: Local Count: {}", frames.len(), self.functions[function_index].local_count);
// trace!("Frame[{}]: Locals: {:?}", frames.len(), &stack[stack_base_pointer .. stack_base_pointer + self.functions[function_index].local_count]);
// trace!("Frame[{}]: Operands: {:?}", frames.len(), &stack[stack_base_pointer + self.functions[function_index].local_count..]);
let Some(instruction) = self.functions[function_index].instructions.get(pc) else {
// debug!("Frame[{}]: Instructions {:?}", frames.len(), self.functions[function_index].instructions);
return runtime_error!("Program counter out of bounds: {} >= {}", pc, self.functions[function_index].instructions.len());
};
// trace!("Frame[{}]: Executing instruction[{}]: {:?}", frames.len(), pc, instruction);
match instruction {
// Operands
Instruction::Push(value) => {
stack.push(value.clone());
pc += 1;
},
// Local variables
Instruction::SetLocal(index) => {
let value = stack_pop!(stack);
let variable_index = stack_base_pointer + *index;
let stack_len = stack.len();
stack.get_mut(variable_index)
.expect(format!("Local variable index out of bounds: {} >= {}", variable_index, stack_len).as_str())
.clone_from(&value);
pc += 1;
},
Instruction::GetLocal(index) => {
let value = stack[stack_base_pointer + *index].clone();
stack.push(value);
pc += 1;
},
// Jump instructions
Instruction::Jump(address) => {
pc = *address;
},
Instruction::JumpIfFalse(address) => {
let condition = stack_pop!(stack);
if condition.is_false() {
pc = *address;
} else {
pc += 1;
}
},
// Binary Operations
Instruction::Add => {
let b = stack_pop!(stack);
let a = stack_pop!(stack);
stack.push(a + b);
pc += 1;
},
Instruction::Sub => {
let b = stack_pop!(stack);
let a = stack_pop!(stack);
stack.push(a - b);
pc += 1;
},
Instruction::Mul => {
let b = stack_pop!(stack);
let a = stack_pop!(stack);
stack.push(a * b);
pc += 1;
},
Instruction::Div => {
let b = stack_pop!(stack);
let a = stack_pop!(stack);
stack.push(a / b);
pc += 1;
},
Instruction::Mod => {
let b = stack_pop!(stack);
let a = stack_pop!(stack);
stack.push(a % b);
pc += 1;
},
Instruction::Pow => {
let b = stack_pop!(stack);
let a = stack_pop!(stack);
stack.push(a.pow(&b));
pc += 1;
},
// Unary Operations
Instruction::Equal => {
let b = stack_pop!(stack);
let a = stack_pop!(stack);
stack.push(Variant::Boolean(a == b));
pc += 1;
},
Instruction::GreaterThan => {
let b = stack_pop!(stack);
let a = stack_pop!(stack);
stack.push(Variant::Boolean(a > b));
pc += 1;
}
Instruction::LessThan => {
let b = stack_pop!(stack);
let a = stack_pop!(stack);
stack.push(Variant::Boolean(a < b));
pc += 1;
},
Instruction::LessEqual => {
let b = stack_pop!(stack);
let a = stack_pop!(stack);
stack.push(Variant::Boolean(a <= b));
pc += 1;
},
Instruction::GreaterEqual => {
let b = stack_pop!(stack);
let a = stack_pop!(stack);
stack.push(Variant::Boolean(a >= b));
pc += 1;
},
Instruction::NotEqual => {
let b = stack_pop!(stack);
let a = stack_pop!(stack);
stack.push(Variant::Boolean(a != b));
pc += 1;
},
Instruction::Or => {
let b = stack_pop!(stack).into();
let a = stack_pop!(stack).into();
stack.push(Variant::Boolean(a || b));
pc += 1;
},
Instruction::And => {
let b = stack_pop!(stack).into();
let a = stack_pop!(stack).into();
stack.push(Variant::Boolean(a && b));
pc += 1;
},
Instruction::Not => {
let a = stack_pop!(stack);
stack.push(!a);
pc += 1;
},
Instruction::Negate => {
let a = stack_pop!(stack);
stack.push(-a);
pc += 1;
},
// Arrays
Instruction::CreateArray(size) => {
let mut array = Vec::with_capacity(*size);
for _ in 0..*size {
array.push(stack_pop!(stack));
}
array.reverse();
stack.push(Variant::Array(Rc::new(RefCell::new(array))));
pc += 1;
},
Instruction::GetArrayItem => {
let index = match stack_pop!(stack) {
Variant::Index(index) => index,
v => return runtime_error!("Expected an index but got {:?}", v)
};
let array = stack_pop!(stack);
let value = match array {
Variant::Array(array) => {
let array = array.borrow();
let index: usize = index;
match array.get(index) {
Some(value) => value.clone(),
None => return runtime_error!("Array index out of bounds: {} >= {}", index, array.len())
}
},
_ => return runtime_error!("Expected an array but got {:?}", array)
};
stack.push(value);
pc += 1;
}
Instruction::SetArrayItem => {
let value = stack_pop!(stack);
let index = match stack_pop!(stack) {
Variant::Index(index) => index,
v => return runtime_error!("Expected an index but got {:?}", v)
};
let varray = stack_pop!(stack);
match varray {
Variant::Array(ref array) => {
let mut array = array.borrow_mut();
let index: usize = index;
array[index] = value;
stack.push(varray.clone());
},
_ => return runtime_error!("Expected an array but got {:?}", varray)
}
pc += 1;
},
Instruction::GetArrayLength => {
let array = stack_pop!(stack);
let length = match array {
Variant::Array(array) => {
let array = array.borrow();
array.len()
},
_ => return runtime_error!("Expected an array but got {:?}", array)
};
stack.push(Variant::Integer(length as i64));
pc += 1;
},
// Dictionaries
Instruction::CreateDictionary(size) => {
let mut table = HashMap::new();
for _ in 0..*size {
let value = stack_pop!(stack);
let key = stack_pop!(stack);
table.insert(key, value);
}
stack.push(Variant::Dictionary(Rc::new(RefCell::new(table))));
pc += 1;
},
Instruction::GetDictionaryItem => {
let key = stack_pop!(stack);
let table = stack_pop!(stack);
let value = match table {
Variant::Dictionary(table) => {
let table = table.borrow();
match table.get(&key) {
Some(value) => value.clone(),
None => return runtime_error!("Dictionary key not found: {:?}", key)
}
},
_ => return runtime_error!("Expected an dictionary but got {:?}", table)
};
stack.push(value);
pc += 1;
}
Instruction::SetDictionaryItem => {
let value = stack_pop!(stack);
let key = stack_pop!(stack);
let table = stack_pop!(stack);
match table {
Variant::Dictionary(table) => {
let mut table = table.borrow_mut();
table.insert(key, value);
},
_ => return runtime_error!("Expected an dictionary but got {:?}", table)
}
pc += 1;
},
Instruction::GetDictionaryKeys => {
let table = stack_pop!(stack);
let keys = match table {
Variant::Dictionary(table) => {
let table = table.borrow();
table.keys().cloned().collect::<Vec<Variant>>()
},
_ => return runtime_error!("Expected an dictionary but got {:?}", table)
};
stack.push(Variant::Array(Rc::new(RefCell::new(keys))));
pc += 1;
},
Instruction::Pop => {
stack_pop!(stack);
pc += 1;
},
// Function calls
Instruction::FunctionCall(target) => {
let next_function_index = match target {
CallTarget::Index(index) => *index,
CallTarget::Name(name) if self.native_functions.contains_key(name) => {
let arity = match self.symbols.get(name.as_str()) {
Some(SymbolEntry::NativeFunction { arity }) => *arity,
_ => return runtime_error!("Native function not found: {}", name)
};
let func = match self.native_functions.get(name.as_str()) {
Some(func) => func,
None => return runtime_error!("Native function not found: {}", name)
};
let args = stack.drain(stack.len() - arity..).collect::<Vec<_>>();
if let Some(value) = func(args) {
stack.push(value);
}
pc += 1;
continue;
}
CallTarget::Name(name) => {
// User defined function
match self.symbols.get(name.as_str()) {
Some(SymbolEntry::UserDefinedFunction { index, .. }) => *index,
_ => return runtime_error!("Function not found: {}", name)
}
},
};
// Remember the current function frame
frames.push(StackFrame {
function_index,
pc: pc + 1,
stack_base_pointer
});
// Create a new stack frame for the function call
pc = 0;
// Set the stack base pointer to the current stack length and include the function's arity
stack_base_pointer = stack.len() - self.functions[next_function_index].arity;
// Extend the stack with the arguments
stack.resize(stack_base_pointer + self.functions[next_function_index].local_count, Variant::Null);
// Update the current function to the next function
function_index = next_function_index;
},
Instruction::Return => {
let Some(returning_value) = stack.pop() else {
return runtime_error!("Return instruction without value");
};
if let Some(parent_frame) = frames.pop() {
stack.resize(stack_base_pointer, Variant::Null);
pc = parent_frame.pc;
stack_base_pointer = parent_frame.stack_base_pointer;
stack.push(returning_value);
function_index = parent_frame.function_index;
} else {
result = Some(returning_value);
break;
}
}
Instruction::EndFunction => {
if let Some(parent_frame) = frames.pop() {
debug!("Returning from function {}", self.functions[function_index].name);
stack.resize(stack_base_pointer, Variant::Null);
pc = parent_frame.pc;
stack_base_pointer = parent_frame.stack_base_pointer;
function_index = parent_frame.function_index;
} else {
break;
}
}
// Output
Instruction::Print => {
let value = stack_pop!(stack);
println!("{}", value);
pc += 1;
},
Instruction::Halt => {
break;
},
Instruction::Panic => {
let value = stack_pop!(stack);
return runtime_error!("Panic: {}", value);
},
}
};
Ok(VmExecutionResult {
result,
run_time: timer.elapsed()
})
}
}