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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
//! Run compiled bytecode.
use crate::{bytecode::*, BinaryOperator, UnaryOperator, Value};
use std::{any::TypeId, borrow::Cow};
use thiserror::Error;
mod function;
pub use function::*;
mod value;
pub use value::*;
mod ty;
pub use ty::*;
/// Interprets bytecode.
pub struct VirtualMachine<'code, 'func, 'data> {
program: Cow<'code, ProgramBytecode>,
#[allow(clippy::type_complexity)]
host_functions: hashbrown::HashMap<
(Option<(TypeId, Option<Type>)>, Cow<'func, str>),
ErasedFunction<'data, 'func>,
>,
max_instructions: Option<u32>,
max_stack_depth: Option<u8>,
#[cfg(feature = "f32_type")]
error_on_nan: bool,
// max_string_length: Option<u32>,
stack: Vec<RuntimeValue<'data>>,
call_stack: Vec<CallFrame>,
}
/// An error generated by executing bytecode at runtime.
#[derive(Debug, Error)]
#[allow(missing_docs)]
pub enum RuntimeError {
#[error("type mismatch ({expected} expected {actual} actual)")]
TypeMismatch { expected: Type, actual: Type },
#[error("undefined function ({name})")]
UndefinedFunction { name: String },
#[error("undefined variable (index {index})")]
UndefinedVariable { index: u16 },
#[error("invalid operand ({actual})")]
InvalidOperand { actual: Type },
#[error("invalid argument (expected {expected:?}, actual {actual})")]
InvalidArgument {
expected: Option<Type>,
actual: Type,
},
#[error("wrong number of arguments (expected {expected}, actual {actual})")]
WrongNumberOfArguments { expected: u16, actual: u16 },
#[error("integer division by zero")]
IntegerDivisionByZero,
#[error("integer overflow")]
IntegerOverflow,
/// This indicates a bug in Ratón.
#[error("stack underflow (bug in Ratón)")]
StackUnderflow,
#[error("stack overflow")]
StackOverflow,
#[error("instruction budget exceeded")]
MaxInstructionsExceeded,
#[error("illegal instruction")]
IllegalInstruction,
#[error("bytecode ended abruptly")]
BytecodeEndedAbruptly,
#[cfg(feature = "f32_type")]
#[error("a floating point operation produced an illegal NaN")]
ProducedNan,
}
macro_rules! call_n {
($n:literal, $name:ident, $($a:ident: $A:ident),*) => {
#[doc = concat!("Like [`Self::call`] but passes ", stringify!($n), " argument(s).")]
#[allow(clippy::too_many_arguments)]
pub fn $name<$($A),*>(
&mut self,
func_name: &str,
$($a: $A),*
) -> Result<RuntimeValue<'data>, RuntimeError>
where
$($A: ToRuntimeValue<'data>),*
{
self.stack.clear();
self.stack.reserve($n);
$(
self.stack.push($a.to_value());
)*
self.call_with_stack(func_name)
}
};
}
impl<'code, 'func, 'data> VirtualMachine<'code, 'func, 'data> {
/// Create a configurable virtual machine for executing bytecode.
///
/// Each virtual machine has a growable heap-allocated stack that
/// is reused between function calls.
pub fn new(program: &'code ProgramBytecode) -> Self {
Self::new_impl(Cow::Borrowed(program))
}
/// Like [`Self::new`] but takes ownership over [`ProgramBytecode`]. This
/// can allow the `'code` lifetime to be `'static`.
pub fn new_with_owned(program: ProgramBytecode) -> Self {
Self::new_impl(Cow::Owned(program))
}
fn new_impl(program: Cow<'code, ProgramBytecode>) -> Self {
Self {
program,
host_functions: hashbrown::HashMap::default(),
max_instructions: Some(100_000_000),
max_stack_depth: Some(50),
stack: Vec::new(),
call_stack: Vec::new(),
#[cfg(feature = "f32_type")]
error_on_nan: false,
}
}
/// Return a [`RuntimeError::MaxInstructionsExceeded`] from [`Self::call`] if would
/// execute more than this many instructions.
///
/// Default: 100 million
pub fn with_max_instructions<T: Into<Option<u32>>>(mut self, max: T) -> Self {
self.max_instructions = max.into();
self
}
/// Return a [`RuntimeError::StackOverflow`] from [`Self::call`] if more than this
/// many nested functions are on the call stack. A host function is tracked as a
/// single function.
///
/// Note: the virtual machine's stack is heap-allocated and growable, so the
/// host's call stack isn't as much of a factor.
///
/// Default: 50
pub fn with_max_stack_depth<T: Into<Option<u8>>>(mut self, max: T) -> Self {
self.max_stack_depth = max.into();
self
}
/// If `true`, all floating point computation in the script will produce an
/// error result during evalutation if it produces [`f32::NAN`] that did not
/// previously exist. It is your responsibility to prevent [`f32::NAN`] in
/// values passed to scripts as arguments or host function return values.
///
/// This can be useful for cross-platform determinism, because NAN generally
/// have a platform-dependent bit pattern but whether a NAN is produced is
/// generally defined by IEEE-754.
///
/// Default: false
#[cfg(feature = "f32_type")]
pub fn with_error_on_nan(mut self, error: bool) -> Self {
self.error_on_nan = error;
self
}
/// Registers a function for all types, except unit, to cast a value to that type.
pub fn with_type_casting(#[allow(unused_mut)] mut self) -> Self {
#[cfg(feature = "bool_type")]
{
self = self.with_host_function("bool", |value: Value| {
Ok(match value {
Value::Bool(b) => b,
#[cfg(feature = "i32_type")]
Value::I32(i) => i != 0,
#[cfg(feature = "f32_type")]
Value::F32(f) => f != 0.0,
#[cfg(feature = "string_type")]
Value::String(s) => !s.is_empty(),
Value::Null => false,
#[allow(unreachable_patterns)]
v => {
return Err(RuntimeError::InvalidArgument {
expected: None,
actual: v.type_of(),
})
}
})
});
}
#[cfg(feature = "i32_type")]
{
self = self.with_host_function("i32", |value: Value| {
Ok(Value::I32(match value {
Value::I32(i) => i,
#[cfg(feature = "bool_type")]
Value::Bool(b) => {
if b {
1
} else {
0
}
}
#[cfg(feature = "f32_type")]
Value::F32(f) => f as i32,
#[cfg(feature = "string_type")]
Value::String(s) => {
return Ok(s.parse::<i32>().map(Value::I32).unwrap_or(Value::Null));
}
v => {
return Err(RuntimeError::InvalidArgument {
expected: None,
actual: v.type_of(),
})
}
}))
});
}
#[cfg(feature = "f32_type")]
{
self = self.with_host_function("f32", |value: Value| {
Ok(Value::F32(match value {
Value::F32(f) => f,
#[cfg(feature = "i32_type")]
Value::I32(i) => i as f32,
#[cfg(feature = "bool_type")]
Value::Bool(b) => {
if b {
1.0
} else {
0.0
}
}
#[cfg(feature = "string_type")]
Value::String(s) => {
return Ok(s.parse::<f32>().map(Value::F32).unwrap_or(Value::Null))
}
v => {
return Err(RuntimeError::InvalidArgument {
expected: None,
actual: v.type_of(),
})
}
}))
});
}
#[cfg(feature = "string_type")]
{
self = self.with_host_function("string", |value: Value| Ok(value.to_string()));
}
self
}
/// Add a Rust function, callable by the bytecode program.
///
/// This performs a heap allocation, unless your function does not capture
/// state from its environment. This is true for all function items, all
/// function pointers, and some closures.
pub fn with_host_function<A, R, N: Into<Cow<'func, str>>, F: Function<'data, A, R> + 'func>(
mut self,
name: N,
func: F,
) -> Self {
self.host_functions.insert(
(F::receiver_type_id_extern_type(), name.into()),
ErasedFunction::new(func),
);
self
}
/// Execute a named bytecode function with arguments, returning the return value. The
/// virtual machine is not re-entrant.
///
/// You must pass the correct number of arguments. Most arguments will be cloned out
/// of `args`, but [`ExternMut`] will be taken and replaced with [`Value::Null`].
pub fn call(
&mut self,
func_name: &str,
args: &mut [RuntimeValue<'data>],
) -> Result<RuntimeValue<'data>, RuntimeError> {
self.stack.clear();
self.stack.reserve(args.len());
for arg in args {
self.stack.push(arg.clone_or_take());
}
self.call_with_stack(func_name)
}
call_n!(0, call0,);
call_n!(1, call1, arg1: A1);
call_n!(2, call2, arg1: A1, arg2: A2);
call_n!(3, call3, arg1: A1, arg2: A2, arg3: A3);
call_n!(4, call4, arg1: A1, arg2: A2, arg3: A3, arg4: A4);
call_n!(5, call5, arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5);
call_n!(6, call6, arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, arg6: A6);
call_n!(7, call7, arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, arg6: A6, arg7: A7);
call_n!(8, call8, arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, arg6: A6, arg7: A7, arg8: A8);
call_n!(9, call9, arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, arg6: A6, arg7: A7, arg8: A8, arg9: A9);
call_n!(10, call10, arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, arg6: A6, arg7: A7, arg8: A8, arg9: A9, arg10: A10);
fn call_with_stack(&mut self, func_name: &str) -> Result<RuntimeValue<'data>, RuntimeError> {
let func = self
.program
.public_functions
.get(func_name)
.ok_or_else(|| RuntimeError::UndefinedFunction {
name: func_name.to_owned(),
})?;
if self.stack.len() != func.arguments as usize {
return Err(RuntimeError::WrongNumberOfArguments {
expected: func.arguments,
actual: self.stack.len() as u16,
});
}
self.call_stack.clear();
let mut pc = func.address;
let mut instruction_budget = self.max_instructions;
while let Some(instruction) = self.program.instructions.get(pc as usize) {
if let Some(instruction_budget) = &mut instruction_budget {
if let Some(next) = instruction_budget.checked_sub(1) {
*instruction_budget = next;
} else {
return Err(RuntimeError::MaxInstructionsExceeded);
}
}
match instruction {
Instruction::AllocVariables(n) => {
let relative_exlusive_index = self
.call_stack
.last_mut()
.map(|f| f.first_variable)
.unwrap_or(0) as usize
+ *n as usize;
if let Some(n) = relative_exlusive_index.checked_sub(self.stack.len()) {
self.stack
.extend((0..n).map(|_| RuntimeValue::Value(Value::Null)));
}
pc += 1;
}
Instruction::LoadConstant(val) => {
self.stack.push(RuntimeValue::Value(val.clone()));
pc += 1;
}
&Instruction::LoadVariable(index) => {
let relative_index = self
.call_stack
.last_mut()
.map(|f| f.first_variable)
.unwrap_or(0) as usize
+ index as usize;
let val = self
.stack
.get_mut(relative_index)
.ok_or(RuntimeError::UndefinedVariable { index })?;
let loaded = val.clone_or_take();
self.stack.push(loaded);
pc += 1;
}
&Instruction::StoreVariable(index) => {
let val = self.stack.pop().ok_or(RuntimeError::StackUnderflow)?;
let relative_index = self
.call_stack
.last_mut()
.map(|f| f.first_variable)
.unwrap_or(0) as usize
+ index as usize;
*self
.stack
.get_mut(relative_index)
.ok_or(RuntimeError::UndefinedVariable { index })? = val;
pc += 1;
}
Instruction::UnaryOperator(op) => {
let operand = self.stack.pop().ok_or(RuntimeError::StackUnderflow)?;
let _result = match op {
#[cfg(feature = "bool_type")]
UnaryOperator::Not => {
let b = operand.as_bool()?;
RuntimeValue::Value(Value::Bool(!b))
}
UnaryOperator::Negate => match operand {
#[cfg(feature = "i32_type")]
RuntimeValue::Value(Value::I32(i)) => RuntimeValue::Value(Value::I32(
i.checked_neg().ok_or(RuntimeError::IntegerOverflow)?,
)),
#[cfg(feature = "f32_type")]
RuntimeValue::Value(Value::F32(f)) => {
// Omit `f32::NAN` check because this never produces
// a new `f32::NAN`.
RuntimeValue::Value(Value::F32(-f))
}
_ => {
return Err(RuntimeError::InvalidOperand {
actual: operand.type_of(),
});
}
},
};
#[allow(unreachable_code)]
self.stack.push(_result);
pc += 1;
}
Instruction::BinaryOperator(op) => {
let right = self.stack.pop().ok_or(RuntimeError::StackUnderflow)?;
let left = self.stack.pop().ok_or(RuntimeError::StackUnderflow)?;
let _result = match op {
BinaryOperator::Add => match (&left, &right) {
#[cfg(feature = "i32_type")]
(
&RuntimeValue::Value(Value::I32(l)),
&RuntimeValue::Value(Value::I32(r)),
) => RuntimeValue::Value(Value::I32(
l.checked_add(r).ok_or(RuntimeError::IntegerOverflow)?,
)),
#[cfg(feature = "f32_type")]
(
&RuntimeValue::Value(Value::F32(l)),
&RuntimeValue::Value(Value::F32(r)),
) => RuntimeValue::Value(Value::F32(nan_check(
l + r,
self.error_on_nan,
)?)),
#[cfg(feature = "string_type")]
(
RuntimeValue::Value(Value::String(l)),
RuntimeValue::Value(Value::String(r)),
) => RuntimeValue::Value(Value::String(format!("{l}{r}"))),
_ => {
return Err(RuntimeError::TypeMismatch {
expected: left.type_of(),
actual: right.type_of(),
});
}
},
BinaryOperator::Subtract => match (&left, &right) {
#[cfg(feature = "i32_type")]
(
&RuntimeValue::Value(Value::I32(l)),
&RuntimeValue::Value(Value::I32(r)),
) => RuntimeValue::Value(Value::I32(
l.checked_sub(r).ok_or(RuntimeError::IntegerOverflow)?,
)),
#[cfg(feature = "f32_type")]
(
&RuntimeValue::Value(Value::F32(l)),
&RuntimeValue::Value(Value::F32(r)),
) => RuntimeValue::Value(Value::F32(nan_check(
l - r,
self.error_on_nan,
)?)),
_ => {
return Err(RuntimeError::TypeMismatch {
expected: left.type_of(),
actual: right.type_of(),
});
}
},
BinaryOperator::Multiply => match (&left, &right) {
#[cfg(feature = "i32_type")]
(
&RuntimeValue::Value(Value::I32(l)),
&RuntimeValue::Value(Value::I32(r)),
) => RuntimeValue::Value(Value::I32(
l.checked_mul(r).ok_or(RuntimeError::IntegerOverflow)?,
)),
#[cfg(feature = "f32_type")]
(
&RuntimeValue::Value(Value::F32(l)),
&RuntimeValue::Value(Value::F32(r)),
) => RuntimeValue::Value(Value::F32(nan_check(
l * r,
self.error_on_nan,
)?)),
_ => {
return Err(RuntimeError::TypeMismatch {
expected: left.type_of(),
actual: right.type_of(),
});
}
},
BinaryOperator::Divide => match (&left, &right) {
#[cfg(feature = "i32_type")]
(
&RuntimeValue::Value(Value::I32(l)),
&RuntimeValue::Value(Value::I32(r)),
) => {
if r == 0 {
return Err(RuntimeError::IntegerDivisionByZero);
}
RuntimeValue::Value(Value::I32(
l.checked_div(r).ok_or(RuntimeError::IntegerOverflow)?,
))
}
#[cfg(feature = "f32_type")]
(
&RuntimeValue::Value(Value::F32(l)),
&RuntimeValue::Value(Value::F32(r)),
) => RuntimeValue::Value(Value::F32(nan_check(
l / r,
self.error_on_nan,
)?)),
_ => {
return Err(RuntimeError::TypeMismatch {
expected: left.type_of(),
actual: right.type_of(),
});
}
},
BinaryOperator::Modulo => match (&left, &right) {
#[cfg(feature = "i32_type")]
(
&RuntimeValue::Value(Value::I32(l)),
&RuntimeValue::Value(Value::I32(r)),
) => {
if r == 0 {
return Err(RuntimeError::IntegerDivisionByZero);
}
RuntimeValue::Value(Value::I32(l % r))
}
#[cfg(feature = "f32_type")]
(
&RuntimeValue::Value(Value::F32(l)),
&RuntimeValue::Value(Value::F32(r)),
) => RuntimeValue::Value(Value::F32(nan_check(
l % r,
self.error_on_nan,
)?)),
_ => {
return Err(RuntimeError::TypeMismatch {
expected: left.type_of(),
actual: right.type_of(),
});
}
},
#[cfg(feature = "bool_type")]
BinaryOperator::Equal => RuntimeValue::Value(Value::Bool(left == right)),
#[cfg(feature = "bool_type")]
BinaryOperator::NotEqual => RuntimeValue::Value(Value::Bool(left != right)),
#[cfg(feature = "bool_type")]
BinaryOperator::LessThan => {
RuntimeValue::Value(Value::Bool(match (&left, &right) {
#[cfg(feature = "i32_type")]
(
&RuntimeValue::Value(Value::I32(l)),
&RuntimeValue::Value(Value::I32(r)),
) => l < r,
#[cfg(feature = "f32_type")]
(
&RuntimeValue::Value(Value::F32(l)),
&RuntimeValue::Value(Value::F32(r)),
) => l < r,
_ => {
return Err(RuntimeError::TypeMismatch {
expected: left.type_of(),
actual: right.type_of(),
});
}
}))
}
#[cfg(feature = "bool_type")]
BinaryOperator::LessThanOrEqual => {
RuntimeValue::Value(Value::Bool(match (&left, &right) {
#[cfg(feature = "i32_type")]
(
&RuntimeValue::Value(Value::I32(l)),
&RuntimeValue::Value(Value::I32(r)),
) => l <= r,
#[cfg(feature = "f32_type")]
(
&RuntimeValue::Value(Value::F32(l)),
&RuntimeValue::Value(Value::F32(r)),
) => l <= r,
_ => {
return Err(RuntimeError::TypeMismatch {
expected: left.type_of(),
actual: right.type_of(),
});
}
}))
}
#[cfg(feature = "bool_type")]
BinaryOperator::GreaterThan => {
RuntimeValue::Value(Value::Bool(match (&left, &right) {
#[cfg(feature = "i32_type")]
(
&RuntimeValue::Value(Value::I32(l)),
&RuntimeValue::Value(Value::I32(r)),
) => l > r,
#[cfg(feature = "f32_type")]
(
&RuntimeValue::Value(Value::F32(l)),
&RuntimeValue::Value(Value::F32(r)),
) => l > r,
_ => {
return Err(RuntimeError::TypeMismatch {
expected: left.type_of(),
actual: right.type_of(),
});
}
}))
}
#[cfg(feature = "bool_type")]
BinaryOperator::GreaterThanOrEqual => {
RuntimeValue::Value(Value::Bool(match (&left, &right) {
#[cfg(feature = "i32_type")]
(
&RuntimeValue::Value(Value::I32(l)),
&RuntimeValue::Value(Value::I32(r)),
) => l >= r,
#[cfg(feature = "f32_type")]
(
&RuntimeValue::Value(Value::F32(l)),
&RuntimeValue::Value(Value::F32(r)),
) => l >= r,
_ => {
return Err(RuntimeError::TypeMismatch {
expected: left.type_of(),
actual: right.type_of(),
});
}
}))
}
#[cfg(feature = "bool_type")]
BinaryOperator::And | BinaryOperator::Or => {
return Err(RuntimeError::IllegalInstruction);
}
};
#[allow(unreachable_code)]
self.stack.push(_result);
pc += 1;
}
Instruction::Jump(target) => {
pc = *target;
}
#[cfg(feature = "bool_type")]
Instruction::JumpIfFalse(target) => {
let cond = self.stack.last().ok_or(RuntimeError::StackUnderflow)?;
let cond_val = cond.as_bool()?;
if !cond_val {
pc = *target;
} else {
pc += 1;
}
}
Instruction::CallByName(receiver_location, name, arg_count) => {
if self.max_stack_depth == Some(self.call_stack.len() as u8) {
return Err(RuntimeError::StackOverflow);
}
let first_variable =
if let Some(fv) = self.stack.len().checked_sub(*arg_count as usize) {
fv
} else {
return Err(RuntimeError::StackUnderflow);
};
let args =
&mut self.stack[first_variable..first_variable + *arg_count as usize];
let receiver_type_id_extern_type =
if matches!(receiver_location, ReceiverLocation::None) {
None
} else {
args.first().map(|a| a.receiver_type_id_extern_type())
};
// Circumvent lifetime requirements using `raw_entry_mut` API.
let key = (receiver_type_id_extern_type, Cow::Borrowed(name.as_str()));
fn compute_hash<K: std::hash::Hash + ?Sized, S: std::hash::BuildHasher>(
hash_builder: &S,
key: &K,
) -> u64 {
use core::hash::Hasher;
let mut state = hash_builder.build_hasher();
key.hash(&mut state);
state.finish()
}
let hash = compute_hash(self.host_functions.hasher(), &key);
let result = if let hashbrown::hash_map::RawEntryMut::Occupied(host_fn) = self
.host_functions
.raw_entry_mut()
.from_hash(hash, |k| k == &key)
{
host_fn.into_mut().call(args)?
} else {
return Err(RuntimeError::UndefinedFunction {
name: name.to_string(),
});
};
if let &ReceiverLocation::Variable(index) = receiver_location {
let relative_index = self
.call_stack
.last_mut()
.map(|f| f.first_variable)
.unwrap_or(0) as usize
+ index as usize;
let taken = std::mem::take(&mut args[0]);
let val = self
.stack
.get_mut(relative_index)
.ok_or(RuntimeError::UndefinedVariable { index })?;
*val = taken;
}
self.stack.truncate(first_variable);
self.stack.push(result);
pc += 1;
}
Instruction::CallByAddress(ip, arg_count) => {
if self.max_stack_depth == Some(self.call_stack.len() as u8) {
return Err(RuntimeError::StackOverflow);
}
let first_variable =
if let Some(fv) = self.stack.len().checked_sub(*arg_count as usize) {
fv
} else {
return Err(RuntimeError::StackUnderflow);
};
self.call_stack.push(CallFrame {
first_variable: first_variable as u32,
return_address: pc + 1,
});
pc = *ip;
}
Instruction::Return => {
if let Some(CallFrame {
return_address,
first_variable,
}) = self.call_stack.pop()
{
if (first_variable as usize) < self.stack.len() {
self.stack.swap_remove(first_variable as usize);
self.stack.truncate(first_variable as usize + 1);
}
pc = return_address;
} else {
return self.stack.pop().ok_or(RuntimeError::StackUnderflow);
}
}
Instruction::Pop => {
self.stack.pop().ok_or(RuntimeError::StackUnderflow)?;
pc += 1;
}
}
}
Err(RuntimeError::BytecodeEndedAbruptly)
}
}
struct CallFrame {
first_variable: u32,
return_address: u32,
}
#[cfg(feature = "f32_type")]
fn nan_check(v: f32, error_on_nan: bool) -> Result<f32, RuntimeError> {
if error_on_nan && v.is_nan() {
Err(RuntimeError::ProducedNan)
} else {
Ok(v)
}
}