|
| 1 | +use crate::{ |
| 2 | + Args, Context, FromValue, Hash, IntoTypeHash, Iterator, Stack, Unit, UnitFn, Value, Vm, |
| 3 | + VmError, VmErrorKind, |
| 4 | +}; |
| 5 | +use std::cell::Cell; |
| 6 | +use std::marker; |
| 7 | +use std::ptr; |
| 8 | +use std::sync::Arc; |
| 9 | + |
| 10 | +thread_local! { static ENV: Cell<Env> = Cell::new(Env::null()) } |
| 11 | + |
| 12 | +/// An interface which wraps a value and allows for accessing protocols. |
| 13 | +/// |
| 14 | +/// This can be used as an argument type for native functions who wants to call |
| 15 | +/// a protocol function like [INTO_ITER](crate::INTO_ITER) (see |
| 16 | +/// [into_iter][Self::into_iter]). |
| 17 | +pub struct Interface { |
| 18 | + target: Value, |
| 19 | + unit: Arc<Unit>, |
| 20 | + context: Arc<Context>, |
| 21 | +} |
| 22 | + |
| 23 | +impl Interface { |
| 24 | + /// Call the `into_iter` protocol on the value. |
| 25 | + pub fn into_iter(mut self) -> Result<Iterator, VmError> { |
| 26 | + let target = match std::mem::take(&mut self.target) { |
| 27 | + Value::Iterator(iterator) => return Ok(iterator.take()?), |
| 28 | + Value::Vec(vec) => return Ok(vec.borrow_ref()?.into_iterator()), |
| 29 | + Value::Object(object) => return Ok(object.borrow_ref()?.into_iterator()), |
| 30 | + target => target, |
| 31 | + }; |
| 32 | + |
| 33 | + let value = self.call_instance_fn(crate::INTO_ITER, target, ())?; |
| 34 | + Iterator::from_value(value) |
| 35 | + } |
| 36 | + |
| 37 | + /// Helper function to call an instance function. |
| 38 | + fn call_instance_fn<H, A>(self, hash: H, target: Value, args: A) -> Result<Value, VmError> |
| 39 | + where |
| 40 | + H: IntoTypeHash, |
| 41 | + A: Args, |
| 42 | + { |
| 43 | + let count = args.count() + 1; |
| 44 | + let hash = Hash::instance_function(target.type_of()?, hash.into_type_hash()); |
| 45 | + |
| 46 | + if let Some(UnitFn::Offset { |
| 47 | + offset, |
| 48 | + args: expected, |
| 49 | + call, |
| 50 | + }) = self.unit.lookup(hash) |
| 51 | + { |
| 52 | + let mut vm = Vm::new(self.context.clone(), self.unit.clone()); |
| 53 | + Self::check_args(count, expected)?; |
| 54 | + vm.stack.push(target); |
| 55 | + args.into_stack(&mut vm.stack)?; |
| 56 | + vm.set_ip(offset); |
| 57 | + return call.call_with_vm(vm); |
| 58 | + } |
| 59 | + |
| 60 | + let handler = match self.context.lookup(hash) { |
| 61 | + Some(handler) => handler, |
| 62 | + None => return Err(VmError::from(VmErrorKind::MissingFunction { hash })), |
| 63 | + }; |
| 64 | + |
| 65 | + let mut stack = Stack::with_capacity(count); |
| 66 | + stack.push(target); |
| 67 | + args.into_stack(&mut stack)?; |
| 68 | + handler(&mut stack, count)?; |
| 69 | + Ok(stack.pop()?) |
| 70 | + } |
| 71 | + |
| 72 | + /// Check that arguments matches expected or raise the appropriate error. |
| 73 | + fn check_args(args: usize, expected: usize) -> Result<(), VmError> { |
| 74 | + if args != expected { |
| 75 | + return Err(VmError::from(VmErrorKind::BadArgumentCount { |
| 76 | + actual: args, |
| 77 | + expected, |
| 78 | + })); |
| 79 | + } |
| 80 | + |
| 81 | + Ok(()) |
| 82 | + } |
| 83 | +} |
| 84 | + |
| 85 | +impl FromValue for Interface { |
| 86 | + fn from_value(value: Value) -> Result<Self, VmError> { |
| 87 | + let env = ENV.with(|env| env.get()); |
| 88 | + let Env { context, unit } = env; |
| 89 | + |
| 90 | + if context.is_null() || unit.is_null() { |
| 91 | + return Err(VmError::from(VmErrorKind::MissingInterfaceEnvironment)); |
| 92 | + } |
| 93 | + |
| 94 | + // Safety: context and unit can only be registered publicly through |
| 95 | + // [EnvGuard], which makes sure that they are live for the duration of |
| 96 | + // the registration. |
| 97 | + Ok(Interface { |
| 98 | + target: value, |
| 99 | + context: unsafe { (*context).clone() }, |
| 100 | + unit: unsafe { (*unit).clone() }, |
| 101 | + }) |
| 102 | + } |
| 103 | +} |
| 104 | + |
| 105 | +pub(crate) struct EnvGuard<'a> { |
| 106 | + old: Env, |
| 107 | + _marker: marker::PhantomData<&'a ()>, |
| 108 | +} |
| 109 | + |
| 110 | +impl<'a> EnvGuard<'a> { |
| 111 | + /// Construct a new environment guard with the given context and unit. |
| 112 | + pub(crate) fn new(context: &'a Arc<Context>, unit: &'a Arc<Unit>) -> EnvGuard<'a> { |
| 113 | + let old = ENV.with(|e| e.replace(Env { context, unit })); |
| 114 | + |
| 115 | + EnvGuard { |
| 116 | + old, |
| 117 | + _marker: marker::PhantomData, |
| 118 | + } |
| 119 | + } |
| 120 | +} |
| 121 | + |
| 122 | +impl Drop for EnvGuard<'_> { |
| 123 | + fn drop(&mut self) { |
| 124 | + ENV.with(|e| e.set(self.old)); |
| 125 | + } |
| 126 | +} |
| 127 | + |
| 128 | +#[derive(Debug, Clone, Copy)] |
| 129 | +struct Env { |
| 130 | + context: *const Arc<Context>, |
| 131 | + unit: *const Arc<Unit>, |
| 132 | +} |
| 133 | + |
| 134 | +impl Env { |
| 135 | + const fn null() -> Self { |
| 136 | + Self { |
| 137 | + context: ptr::null(), |
| 138 | + unit: ptr::null(), |
| 139 | + } |
| 140 | + } |
| 141 | +} |
0 commit comments