1use crate::live_value::Value as LiveValue;
2use crate::serde_value::from_live;
3use crate::value::{
4 embed_to_vm_error, load_owned_arguments, load_owned_value, snapshot_value, FromRustia,
5 FromRustiaMulti, IntoRustia, IntoRustiaMulti, OwnedValue,
6};
7use crate::{Error, HostSchema, Invocation, Result, Rustia};
8use rustia_vm::{HostFunctionOp, OpCapability, RetainedValue, Value as RawValue, ValueKind, Vm};
9use std::any::type_name;
10use std::sync::Arc;
11
12#[derive(Clone, Debug)]
30pub struct Function {
31 value: LiveValue,
32 decision_epoch: u64,
33}
34
35impl Function {
36 pub(crate) fn new(value: RetainedValue, decision_epoch: u64) -> Self {
37 Self {
38 value: LiveValue::new(value, decision_epoch),
39 decision_epoch,
40 }
41 }
42
43 pub(crate) fn from_value(value: LiveValue) -> Self {
44 Self {
45 decision_epoch: value.decision_epoch(),
46 value,
47 }
48 }
49
50 pub fn as_value(&self) -> LiveValue {
52 self.value.clone()
53 }
54
55 pub fn decision_epoch(&self) -> u64 {
57 self.decision_epoch
58 }
59
60 pub fn call<Args, Return>(&self, rustia: &mut Rustia, args: Args) -> Result<Return>
68 where
69 Args: IntoRustiaMulti,
70 Return: FromRustiaMulti,
71 {
72 let function = self.value.raw(rustia.vm(), "function handle")?;
73 let args = args.into_rustia_multi()?;
74 let (raw_args, _argument_roots) = load_owned_arguments(rustia.vm_mut(), &args)?;
75 let raw_results = rustia
76 .vm_mut()
77 .call_retained_function(function, &raw_args)
78 .map_err(Error::from_engine)?;
79 let results = raw_results
80 .into_iter()
81 .map(|value| snapshot_value(rustia.vm_mut(), value))
82 .collect::<Result<Vec<_>>>()?;
83 Return::from_rustia_multi(results)
84 }
85
86 pub fn call_values(&self, rustia: &mut Rustia, args: &[LiveValue]) -> Result<Vec<LiveValue>> {
90 let function = self.value.raw(rustia.vm(), "function handle")?;
91 let raw_args = args
92 .iter()
93 .map(|value| value.raw(rustia.vm(), "function argument handle"))
94 .collect::<Result<Vec<_>>>()?;
95 let results = rustia
96 .vm_mut()
97 .call_retained_function(function, &raw_args)
98 .map_err(Error::from_engine)?;
99 LiveValue::retain_many(rustia.vm_mut(), &results)
100 }
101
102 pub fn call_in<C, Args, Return>(
110 &self,
111 invocation: &mut Invocation<'_, C>,
112 args: Args,
113 ) -> Result<Return>
114 where
115 C: HostSchema,
116 Args: IntoRustiaMulti,
117 Return: FromRustiaMulti,
118 {
119 let function = self.value.raw(invocation.vm, "function handle")?;
120 invocation.convert_call(function, args)
121 }
122
123 pub fn call_values_in<C>(
125 &self,
126 invocation: &mut Invocation<'_, C>,
127 args: &[LiveValue],
128 ) -> Result<Vec<LiveValue>>
129 where
130 C: HostSchema,
131 {
132 invocation.scoped(|invocation| {
133 let function = self.value.raw(invocation.vm, "function handle")?;
134 let raw_args = args
135 .iter()
136 .map(|value| value.raw(invocation.vm, "function argument handle"))
137 .collect::<Result<Vec<_>>>()?;
138 let results = invocation.call_retained_raw(function, &raw_args)?;
139 LiveValue::retain_many(invocation.vm, &results)
140 })
141 }
142}
143
144#[derive(Clone, Debug)]
152pub struct Exports {
153 value: LiveValue,
154 decision_epoch: u64,
155}
156
157impl Exports {
158 pub(crate) fn new(value: RetainedValue, decision_epoch: u64) -> Self {
159 Self {
160 value: LiveValue::new(value, decision_epoch),
161 decision_epoch,
162 }
163 }
164
165 pub fn as_value(&self) -> LiveValue {
167 self.value.clone()
168 }
169
170 pub fn as_table<C>(&self, rustia: &Rustia<C>) -> Result<Option<crate::Table>>
172 where
173 C: HostSchema,
174 {
175 self.value.as_table(rustia)
176 }
177
178 pub fn decision_epoch(&self) -> u64 {
180 self.decision_epoch
181 }
182
183 pub fn value(&self, rustia: &mut Rustia) -> Result<OwnedValue> {
188 let value = self.value.raw(rustia.vm(), "exports handle")?;
189 snapshot_value(rustia.vm_mut(), value)
190 }
191
192 pub fn value_in<C>(&self, invocation: &mut Invocation<'_, C>) -> Result<OwnedValue>
194 where
195 C: HostSchema,
196 {
197 invocation.scoped(|invocation| {
198 let value = self.value.raw(invocation.vm, "exports handle")?;
199 snapshot_value(invocation.vm, value)
200 })
201 }
202
203 pub fn deserialize<T>(&self, rustia: &mut Rustia<impl HostSchema>) -> Result<T>
205 where
206 T: serde::de::DeserializeOwned,
207 {
208 let value = self.value.raw(rustia.vm(), "exports handle")?;
209 from_live(rustia.vm_mut(), value)
210 }
211
212 pub fn get<T>(&self, rustia: &mut Rustia, name: &str) -> Result<T>
216 where
217 T: FromRustia,
218 {
219 let value = self.raw_get(rustia, name)?;
220 let value = snapshot_value(rustia.vm_mut(), value)?;
221 T::from_rustia(value)
222 }
223
224 pub fn get_live(&self, rustia: &mut Rustia, name: &str) -> Result<LiveValue> {
226 let value = self.raw_get(rustia, name)?;
227 LiveValue::retain(rustia.vm_mut(), value)
228 }
229
230 pub fn get_in<C, T>(&self, invocation: &mut Invocation<'_, C>, name: &str) -> Result<T>
232 where
233 C: HostSchema,
234 T: FromRustia,
235 {
236 invocation.scoped(|invocation| {
237 let value = self.raw_get_in(invocation, name)?;
238 let value = snapshot_value(invocation.vm, value)?;
239 T::from_rustia(value)
240 })
241 }
242
243 pub fn get_live_in<C>(
245 &self,
246 invocation: &mut Invocation<'_, C>,
247 name: &str,
248 ) -> Result<LiveValue>
249 where
250 C: HostSchema,
251 {
252 invocation.scoped(|invocation| {
253 let value = self.raw_get_in(invocation, name)?;
254 LiveValue::retain(invocation.vm, value)
255 })
256 }
257
258 pub fn function(&self, rustia: &mut Rustia, name: &str) -> Result<Function> {
262 let value = self.raw_get(rustia, name)?;
263 if value.kind() != ValueKind::Function {
264 return Err(Error::embed(format!("export `{name}` is not a function")));
265 }
266 let value = rustia
267 .vm_mut()
268 .retain_value(value)
269 .map_err(Error::from_engine)?;
270 Ok(Function::new(value, self.decision_epoch))
271 }
272
273 pub fn function_in<C>(&self, invocation: &mut Invocation<'_, C>, name: &str) -> Result<Function>
275 where
276 C: HostSchema,
277 {
278 invocation.scoped(|invocation| {
279 let value = self.raw_get_in(invocation, name)?;
280 if value.kind() != ValueKind::Function {
281 return Err(Error::embed(format!("export `{name}` is not a function")));
282 }
283 let value = invocation
284 .vm
285 .retain_value(value)
286 .map_err(Error::from_engine)?;
287 Ok(Function::new(value, self.decision_epoch))
288 })
289 }
290
291 fn raw_get(&self, rustia: &mut Rustia, name: &str) -> Result<RawValue> {
292 let table = self.value.raw(rustia.vm(), "exports handle")?;
293 let key = rustia.vm_mut().string(name);
294 rustia
295 .vm_mut()
296 .raw_table_get_value(table, key)
297 .map_err(Error::from_engine)
298 }
299
300 fn raw_get_in<C>(&self, invocation: &mut Invocation<'_, C>, name: &str) -> Result<RawValue>
301 where
302 C: HostSchema,
303 {
304 let table = self.value.raw(invocation.vm, "exports handle")?;
305 let key = invocation.vm.string(name);
306 invocation
307 .vm
308 .raw_table_get_value(table, key)
309 .map_err(Error::from_engine)
310 }
311}
312
313pub(crate) mod adapter {
316 use super::*;
317
318 pub(crate) struct Token;
319
320 pub(crate) trait Function<Args, Return>: Send + Sync + 'static {
321 fn into_host_function(
322 self,
323 token: Token,
324 name: String,
325 fuel_cost: u32,
326 capability: OpCapability,
327 ) -> HostFunctionOp;
328 }
329
330 pub(crate) trait Value {
331 fn into_host_value(self, token: Token) -> Result<HostReturnValue>;
332 }
333
334 pub(crate) trait Argument: Sized {
335 fn from_host_argument(token: Token, vm: &mut Vm, value: RawValue) -> Result<Self>;
336 }
337
338 pub(crate) trait Return {
339 fn into_host_return(self, token: Token) -> Result<Vec<HostReturnValue>>;
340
341 fn rustia_type_names(token: Token) -> Vec<&'static str>
342 where
343 Self: Sized;
344
345 fn is_fallible(_token: Token) -> bool
346 where
347 Self: Sized,
348 {
349 false
350 }
351 }
352}
353
354use adapter::Value as _;
355
356#[allow(private_bounds)]
368pub trait IntoHostFunction<Args, Return>:
369 adapter::Function<Args, Return> + Send + Sync + 'static
370{
371}
372
373impl<T, Args, Return> IntoHostFunction<Args, Return> for T where T: adapter::Function<Args, Return> {}
374
375pub(crate) enum HostReturnValue {
376 Owned(OwnedValue),
377 Live(LiveValue),
378 NewObject {
379 rust_type_id: std::any::TypeId,
380 rust_type_name: &'static str,
381 value: Box<rustia_vm::HostObjectPayload>,
382 },
383}
384
385#[allow(private_bounds)]
390pub trait IntoHostValue: adapter::Value {}
391
392impl<T: adapter::Value> IntoHostValue for T {}
393
394impl<T: IntoRustia> adapter::Value for T {
395 fn into_host_value(self, _token: adapter::Token) -> Result<HostReturnValue> {
396 self.into_rustia().map(HostReturnValue::Owned)
397 }
398}
399
400impl adapter::Value for LiveValue {
401 fn into_host_value(self, _token: adapter::Token) -> Result<HostReturnValue> {
402 Ok(HostReturnValue::Live(self))
403 }
404}
405
406impl adapter::Value for crate::Table {
407 fn into_host_value(self, token: adapter::Token) -> Result<HostReturnValue> {
408 self.as_value().into_host_value(token)
409 }
410}
411
412impl adapter::Value for Function {
413 fn into_host_value(self, token: adapter::Token) -> Result<HostReturnValue> {
414 self.as_value().into_host_value(token)
415 }
416}
417
418#[allow(private_bounds)]
429pub trait FromHostArgument: adapter::Argument + Sized {}
430
431impl<T: adapter::Argument> FromHostArgument for T {}
432
433impl<T: FromRustia> adapter::Argument for T {
434 fn from_host_argument(_token: adapter::Token, vm: &mut Vm, value: RawValue) -> Result<Self> {
435 T::from_rustia(snapshot_value(vm, value)?)
436 }
437}
438
439impl adapter::Argument for LiveValue {
440 fn from_host_argument(_token: adapter::Token, vm: &mut Vm, value: RawValue) -> Result<Self> {
441 LiveValue::retain(vm, value)
442 }
443}
444
445impl adapter::Argument for crate::Table {
446 fn from_host_argument(_token: adapter::Token, vm: &mut Vm, value: RawValue) -> Result<Self> {
447 if value.kind() != ValueKind::Table {
448 return Err(Error::embed("expected table".to_owned()));
449 }
450 Ok(Self::new(LiveValue::retain(vm, value)?))
451 }
452}
453
454impl adapter::Argument for Function {
455 fn from_host_argument(_token: adapter::Token, vm: &mut Vm, value: RawValue) -> Result<Self> {
456 if value.kind() != ValueKind::Function {
457 return Err(Error::embed("expected function".to_owned()));
458 }
459 Ok(Self::from_value(LiveValue::retain(vm, value)?))
460 }
461}
462
463#[allow(private_bounds)]
476pub trait IntoHostReturn: adapter::Return {}
477
478impl<T: adapter::Return> IntoHostReturn for T {}
479
480macro_rules! impl_single_host_return {
481 ($($ty:ty),+ $(,)?) => {$(
482 impl adapter::Return for $ty {
483 fn into_host_return(self, _token: adapter::Token) -> Result<Vec<HostReturnValue>> {
484 Ok(vec![self.into_host_value(adapter::Token)?])
485 }
486 fn rustia_type_names(_token: adapter::Token) -> Vec<&'static str> {
487 vec![type_name::<Self>()]
488 }
489 }
490 )+};
491}
492
493impl_single_host_return!(
494 OwnedValue,
495 crate::OwnedTable,
496 bool,
497 f64,
498 f32,
499 i8,
500 i16,
501 i32,
502 i64,
503 isize,
504 u8,
505 u16,
506 u32,
507 u64,
508 usize,
509 String,
510 &str,
511 LiveValue,
512 crate::Table,
513 Function
514);
515
516macro_rules! impl_owned_container_host_return {
517 ($ty:ty) => {
518 impl<T: IntoRustia> adapter::Return for $ty {
519 fn into_host_return(self, _token: adapter::Token) -> Result<Vec<HostReturnValue>> {
520 Ok(vec![self.into_host_value(adapter::Token)?])
521 }
522 fn rustia_type_names(_token: adapter::Token) -> Vec<&'static str> {
523 vec![type_name::<Self>()]
524 }
525 }
526 };
527}
528
529impl_owned_container_host_return!(Option<T>);
530impl_owned_container_host_return!(Vec<T>);
531impl_owned_container_host_return!(std::collections::BTreeMap<String, T>);
532
533impl adapter::Return for () {
534 fn into_host_return(self, _token: adapter::Token) -> Result<Vec<HostReturnValue>> {
535 Ok(Vec::new())
536 }
537 fn rustia_type_names(_token: adapter::Token) -> Vec<&'static str> {
538 Vec::new()
539 }
540}
541
542macro_rules! impl_tuple_host_return {
543 ($($name:ident),+ $(,)?) => {
544 impl<$($name: IntoHostValue),+> adapter::Return for ($($name,)+) {
545 #[allow(non_snake_case)]
546 fn into_host_return(self, _token: adapter::Token) -> Result<Vec<HostReturnValue>> {
547 let ($($name,)+) = self;
548 Ok(vec![$($name.into_host_value(adapter::Token)?,)+])
549 }
550 fn rustia_type_names(_token: adapter::Token) -> Vec<&'static str> {
551 vec![$(type_name::<$name>()),+]
552 }
553 }
554 };
555}
556
557impl_tuple_host_return!(A);
558impl_tuple_host_return!(A, B);
559impl_tuple_host_return!(A, B, C);
560impl_tuple_host_return!(A, B, C, D);
561impl_tuple_host_return!(A, B, C, D, E);
562impl_tuple_host_return!(A, B, C, D, E, F);
563impl_tuple_host_return!(A, B, C, D, E, F, G);
564impl_tuple_host_return!(A, B, C, D, E, F, G, H);
565
566impl<T: IntoHostReturn> adapter::Return for Result<T> {
567 fn into_host_return(self, _token: adapter::Token) -> Result<Vec<HostReturnValue>> {
568 self.and_then(|value| value.into_host_return(adapter::Token))
569 }
570 fn rustia_type_names(_token: adapter::Token) -> Vec<&'static str> {
571 T::rustia_type_names(adapter::Token)
572 }
573 fn is_fallible(_token: adapter::Token) -> bool {
574 true
575 }
576}
577
578impl<F, Return> adapter::Function<(), Return> for F
579where
580 F: Fn() -> Return + Send + Sync + 'static,
581 Return: IntoHostReturn,
582{
583 fn into_host_function(
584 self,
585 _token: adapter::Token,
586 name: String,
587 fuel_cost: u32,
588 capability: OpCapability,
589 ) -> HostFunctionOp {
590 let diagnostic_name = name.clone();
591 HostFunctionOp::new(
592 name,
593 fuel_cost,
594 capability,
595 Arc::new(move |vm, _args| host_return_to_raw(vm, &diagnostic_name, self())),
596 )
597 .with_signature(
598 0,
599 Vec::new(),
600 Return::rustia_type_names(adapter::Token),
601 Return::is_fallible(adapter::Token),
602 )
603 }
604}
605
606macro_rules! impl_host_function {
607 ($parameter_count:expr; $($name:ident),+ $(,)?) => {
608 impl<Func, Return, $($name),+> adapter::Function<($($name,)+), Return> for Func
609 where
610 Func: Fn($($name),+) -> Return + Send + Sync + 'static,
611 Return: IntoHostReturn,
612 $($name: FromHostArgument,)+
613 {
614 #[allow(non_snake_case)]
615 fn into_host_function(
616 self,
617 _token: adapter::Token,
618 name: String,
619 fuel_cost: u32,
620 capability: OpCapability,
621 ) -> HostFunctionOp {
622 let diagnostic_name = name.clone();
623 HostFunctionOp::new(
624 name,
625 fuel_cost,
626 capability,
627 Arc::new(move |vm, args| {
628 let mut index = 0usize;
629 $(
630 let $name = host_arg_from_raw(vm, args, index, &diagnostic_name)?;
631 index += 1;
632 )+
633 let _ = index;
634 host_return_to_raw(vm, &diagnostic_name, self($($name),+))
635 }),
636 )
637 .with_signature(
638 $parameter_count,
639 vec![$(type_name::<$name>()),+],
640 Return::rustia_type_names(adapter::Token),
641 Return::is_fallible(adapter::Token),
642 )
643 }
644 }
645 };
646}
647
648impl_host_function!(1; A);
649impl_host_function!(2; A, B);
650impl_host_function!(3; A, B, C);
651impl_host_function!(4; A, B, C, D);
652impl_host_function!(5; A, B, C, D, E);
653impl_host_function!(6; A, B, C, D, E, F);
654impl_host_function!(7; A, B, C, D, E, F, G);
655impl_host_function!(8; A, B, C, D, E, F, G, H);
656
657pub(crate) fn host_arg_from_raw<T>(
658 vm: &mut Vm,
659 args: &[RawValue],
660 index: usize,
661 function_name: &str,
662) -> rustia_vm::Result<T>
663where
664 T: FromHostArgument,
665{
666 let value = args.get(index).copied().unwrap_or_else(RawValue::nil);
667 T::from_host_argument(adapter::Token, vm, value)
668 .map_err(|error| host_embed_error(function_name, format!("argument {}", index + 1), error))
669}
670
671pub(crate) fn host_return_to_raw<Return>(
672 vm: &mut Vm,
673 function_name: &str,
674 value: Return,
675) -> rustia_vm::Result<Vec<RawValue>>
676where
677 Return: IntoHostReturn,
678{
679 let values = value
680 .into_host_return(adapter::Token)
681 .map_err(|error| host_embed_error(function_name, "return value", error))?;
682 let mut live_roots = Vec::new();
685 for value in &values {
686 match value {
687 HostReturnValue::Live(value) => {
688 value
689 .raw(vm, "host function result")
690 .map_err(embed_to_vm_error)?;
691 live_roots.push(value.clone());
692 }
693 HostReturnValue::NewObject { rust_type_id, .. } => {
694 vm.validate_host_object_creation(*rust_type_id)?;
695 }
696 HostReturnValue::Owned(_) => {}
697 }
698 }
699 let mut roots = Vec::new();
700 let mut results = Vec::with_capacity(values.len());
701 let count = values.len();
702 for (index, value) in values.into_iter().enumerate() {
703 let raw = match value {
704 HostReturnValue::Owned(value) => {
705 let raw = load_owned_value(vm, &value).map_err(|error| {
706 host_embed_error(function_name, format!("return value {}", index + 1), error)
707 })?;
708 if index + 1 < count
709 && !matches!(
710 raw.kind(),
711 ValueKind::Nil | ValueKind::Boolean | ValueKind::Number
712 )
713 {
714 roots.push(vm.retain_value(raw)?);
715 }
716 raw
717 }
718 HostReturnValue::Live(value) => value
719 .raw(vm, "host function result")
720 .map_err(embed_to_vm_error)?,
721 HostReturnValue::NewObject {
722 rust_type_id,
723 rust_type_name,
724 value,
725 } => {
726 let raw = vm.create_host_object(rust_type_id, rust_type_name, value)?;
727 if index + 1 < count {
728 roots.push(vm.retain_value(raw)?);
729 }
730 raw
731 }
732 };
733 results.push(raw);
734 }
735 Ok(results)
736}
737
738pub(crate) fn host_embed_error(
739 function_name: &str,
740 slot: impl AsRef<str>,
741 error: Error,
742) -> rustia_vm::Error {
743 match error {
744 Error {
745 kind: crate::ErrorKind::Vm(error),
746 ..
747 } => (*error).into_core(),
748 error => embed_to_vm_error(
749 error.with_context(format!("host function `{function_name}` {}", slot.as_ref())),
750 ),
751 }
752}