1use std::cell::{Cell, RefCell};
29use std::sync::Arc;
30
31use serde::de::DeserializeOwned;
32use serde_json::Value;
33
34use crate::core::Nid;
35use crate::event::Ev;
36use crate::machine::Machine;
37use crate::system::{ActorRef, Context, FixedState, SystemError};
38use crate::FixedMap;
39use indexmap::IndexMap;
40
41pub(crate) type GuardFn<C, E> = Box<dyn Fn(&GuardArgs<'_, C, E>) -> Result<bool, String> + Send + Sync>;
42pub(crate) type ActionFn = crate::system::EffectExec;
43pub(crate) type DelayFn<C, E> = Box<dyn Fn(&C, &Ev<E>) -> Result<u64, String> + Send + Sync>;
44pub(crate) type ExprFn<C, E> = Arc<dyn Fn(&ExprArgs<'_, C, E>) -> Value + Send + Sync>;
45pub(crate) type ContextFn = Arc<dyn Fn(&ContextArgs<'_>) -> Value + Send + Sync>;
46
47pub(crate) type Factory<T> = Arc<dyn Fn(&Value) -> Result<T, String> + Send + Sync>;
48
49pub struct GuardArgs<'a, C, E> {
51 pub context: &'a C,
52 pub event: &'a Ev<E>,
53 pub(crate) machine: &'a Machine<C, E>,
54 pub(crate) config: &'a [Nid],
55}
56
57impl<C, E> GuardArgs<'_, C, E> {
58 pub fn in_state(&self, id: &str) -> bool {
61 let id = id.strip_prefix('#').unwrap_or(id);
62 self.machine.node_by_id(id).is_some_and(|n| self.config.contains(&n))
63 }
64}
65
66pub struct ExprArgs<'a, C, E> {
70 pub context: &'a C,
71 pub event: &'a Ev<E>,
72 pub params: Option<&'a Value>,
75 pub input: Option<&'a Value>,
78 pub(crate) machine: &'a Machine<C, E>,
79 pub(crate) config: &'a [Nid],
80 pub(crate) enq: Option<&'a Enq<'a>>,
81 pub(crate) children: &'a IndexMap<String, ActorRef, FixedState>,
82 pub(crate) cx: &'a dyn SelfRefs,
83 pub(crate) error: &'a RefCell<Option<String>>,
84}
85
86pub(crate) trait SelfRefs {
90 fn self_ref(&self) -> ActorRef;
91 fn parent_ref(&self) -> Option<ActorRef>;
92}
93
94impl SelfRefs for RefCell<&mut (dyn Context + '_)> {
95 fn self_ref(&self) -> ActorRef {
96 self.borrow().self_ref()
97 }
98
99 fn parent_ref(&self) -> Option<ActorRef> {
100 self.borrow().parent_ref()
101 }
102}
103
104impl<C: serde::Serialize, E: crate::event::EventType> ExprArgs<'_, C, E> {
105 pub fn scope_json(&self) -> Result<Value, String> {
109 let mut scope = serde_json::Map::new();
110 let context = serde_json::to_value(self.context).map_err(|e| format!("the context does not serialize: {e}"))?;
111 scope.insert("context".into(), context);
112 scope.insert("event".into(), self.event.to_json());
113 if let Some(input) = self.input {
114 scope.insert("input".into(), input.clone());
115 }
116 if let Some(params) = self.params {
117 scope.insert("params".into(), params.clone());
118 }
119 scope.insert("self".into(), self.self_ref().to_json());
120 if let Some(parent) = self.parent_ref() {
121 scope.insert("parent".into(), parent.to_json());
122 }
123 if !self.children.is_empty() {
124 let children = self.children.iter().map(|(id, r)| (id.clone(), r.to_json())).collect();
125 scope.insert("children".into(), Value::Object(children));
126 }
127 Ok(Value::Object(scope))
128 }
129}
130
131impl<C, E> ExprArgs<'_, C, E> {
132 pub fn children(&self) -> &IndexMap<String, ActorRef, FixedState> {
134 self.children
135 }
136
137 pub fn self_ref(&self) -> ActorRef {
139 self.cx.self_ref()
140 }
141
142 pub fn parent_ref(&self) -> Option<ActorRef> {
144 self.cx.parent_ref()
145 }
146
147 pub fn fail(&self, message: impl Into<String>) {
150 self.error.borrow_mut().get_or_insert_with(|| message.into());
151 }
152
153 pub fn in_state(&self, id: &str) -> bool {
156 let id = id.strip_prefix('#').unwrap_or(id);
157 self.machine.node_by_id(id).is_some_and(|n| self.config.contains(&n))
158 }
159
160 pub fn enq(&self) -> Option<&Enq<'_>> {
163 self.enq
164 }
165}
166
167#[derive(Default)]
170pub struct Enq<'a> {
171 pub(crate) ops: RefCell<Vec<EnqOp>>,
172 pub(crate) ids: Option<&'a dyn ChildIds>,
174 pub(crate) aborted: Cell<bool>,
177 pub(crate) failed: Cell<bool>,
181}
182
183pub(crate) trait ChildIds {
186 fn spawn(&self, src: &str, options: &SpawnOptions) -> Result<Spawn, SystemError>;
188 fn stop_child(&self, id: &str);
192}
193
194pub(crate) enum Spawn {
196 Created { id: String, child: ActorRef, counter: Option<(String, u64)> },
201 Predicted(String),
204 Abort,
207}
208
209#[derive(Debug, Clone, Default)]
211pub struct SpawnOptions {
212 pub id: Option<String>,
214 pub input: Option<Value>,
215 pub system_id: Option<String>,
217 pub sync_snapshot: Option<bool>,
219}
220
221#[derive(Debug, Clone)]
222pub(crate) enum EnqOp {
223 Raise {
224 event: Value,
225 delay: Option<u64>,
226 id: Option<String>,
227 },
228 Emit(Value),
229 Cancel(String),
230 Log(Vec<Value>),
231 Action {
232 name: String,
233 params: Value,
234 },
235 SendTo {
236 to: SendTarget,
237 event: Value,
238 delay: Option<u64>,
239 id: Option<String>,
240 },
241 Stop(String),
242 Spawn {
245 id: String,
246 child: ActorRef,
247 counter: Option<(String, u64)>,
248 },
249 Fail(SystemError),
251}
252
253#[derive(Debug, Clone)]
255pub(crate) enum SendTarget {
256 Child(String),
258 Ref(ActorRef),
260 Nowhere,
262 Parent,
264}
265
266impl std::fmt::Debug for Enq<'_> {
267 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
268 f.debug_struct("Enq").field("ops", &self.ops).finish_non_exhaustive()
269 }
270}
271
272impl Enq<'_> {
273 pub fn raise(&self, event: Value) {
275 self.push(EnqOp::Raise { event, delay: None, id: None });
276 }
277
278 pub fn raise_delayed(&self, event: Value, delay_ms: u64, id: Option<&str>) {
280 self.push(EnqOp::Raise { event, delay: Some(delay_ms), id: id.map(str::to_owned) });
281 }
282
283 pub fn emit(&self, event: Value) {
285 self.push(EnqOp::Emit(event));
286 }
287
288 pub fn cancel(&self, id: &str) {
290 self.push(EnqOp::Cancel(id.to_owned()));
291 }
292
293 pub fn log(&self, args: Vec<Value>) {
295 self.push(EnqOp::Log(args));
296 }
297
298 pub fn action(&self, name: &str, params: Value) {
301 self.push(EnqOp::Action { name: name.to_owned(), params });
302 }
303
304 pub fn send_to(&self, child: &str, event: Value) {
307 self.push_send(SendTarget::Child(child.to_owned()), event, None, None);
308 }
309
310 pub fn send_to_delayed(&self, child: &str, event: Value, delay_ms: u64, id: Option<&str>) {
313 self.push_send(SendTarget::Child(child.to_owned()), event, Some(delay_ms), id);
314 }
315
316 pub fn send_to_ref(&self, actor: &Value, event: Value) {
320 self.push_send(Self::target(actor), event, None, None);
321 }
322
323 pub fn send_to_ref_delayed(&self, actor: &Value, event: Value, delay_ms: u64, id: Option<&str>) {
325 self.push_send(Self::target(actor), event, Some(delay_ms), id);
326 }
327
328 fn target(actor: &Value) -> SendTarget {
329 match actor {
330 Value::String(child) => SendTarget::Child(child.clone()),
331 other => ActorRef::from_json(other).map_or(SendTarget::Nowhere, SendTarget::Ref),
332 }
333 }
334
335 pub fn send_parent(&self, event: Value) {
337 self.push_send(SendTarget::Parent, event, None, None);
338 }
339
340 pub fn send_parent_delayed(&self, event: Value, delay_ms: u64, id: Option<&str>) {
342 self.push_send(SendTarget::Parent, event, Some(delay_ms), id);
343 }
344
345 pub fn stop(&self, child: &str) {
347 if self.ended() {
348 return;
349 }
350 if let Some(ids) = self.ids {
351 ids.stop_child(child);
352 }
353 self.push(EnqOp::Stop(child.to_owned()));
354 }
355
356 fn push(&self, op: EnqOp) {
359 if !self.ended() {
360 self.ops.borrow_mut().push(op);
361 }
362 }
363
364 pub(crate) fn ended(&self) -> bool {
366 self.aborted.get() || self.failed.get()
367 }
368
369 fn push_send(&self, to: SendTarget, event: Value, delay: Option<u64>, id: Option<&str>) {
370 self.push(EnqOp::SendTo { to, event, delay, id: id.map(str::to_owned) });
371 }
372
373 pub fn spawn(&self, src: &str, options: SpawnOptions) -> String {
379 if self.ended() {
380 return options.id.unwrap_or_default();
381 }
382 let Some(ids) = self.ids else {
383 return options.id.unwrap_or_else(|| format!("{src}:0"));
384 };
385 match ids.spawn(src, &options) {
386 Ok(Spawn::Created { id, child, counter }) => {
387 self.push(EnqOp::Spawn { id: id.clone(), child, counter });
388 id
389 }
390 Ok(Spawn::Predicted(id)) => id,
391 Ok(Spawn::Abort) => {
392 self.aborted.set(true);
393 options.id.unwrap_or_default()
394 }
395 Err(e) => {
396 self.push(EnqOp::Fail(e));
397 self.failed.set(true);
398 options.id.unwrap_or_default()
399 }
400 }
401 }
402
403 pub(crate) fn take(&self) -> Vec<EnqOp> {
404 std::mem::take(&mut self.ops.borrow_mut())
405 }
406
407 pub fn call(&self, op: &str, args: &[Value]) -> Result<Option<Value>, String> {
415 if self.ended() {
416 return Ok(None);
417 }
418 let arg = |i: usize| args.get(i).cloned().unwrap_or(Value::Null);
419 let delay = |options: &Value| {
420 let ms = options.get("delay")?.as_f64()?;
421 Some(if ms > 0.0 { ms.ceil() as u64 } else { 0 })
422 };
423 match op {
424 "action" => {
425 let name = arg(0);
426 let name = name.as_str().ok_or("enq(action, params): name the action as actions.<name>")?;
427 self.action(name, arg(1));
428 }
429 "raise" => {
430 let options = arg(1);
431 match delay(&options) {
432 Some(ms) => self.raise_delayed(arg(0), ms, options.get("id").and_then(Value::as_str)),
433 None => self.raise(arg(0)),
434 }
435 }
436 "emit" => self.emit(arg(0)),
437 "cancel" => self.cancel(arg(0).as_str().unwrap_or_default()),
438 "log" => self.log(args.to_vec()),
439 "sendTo" => {
440 let target = match arg(0) {
442 Value::Object(o) if !o.contains_key("@actor") => o.get("id").cloned().unwrap_or(Value::Null),
443 Value::Object(mut o) => {
444 o.remove("id");
445 Value::Object(o)
446 }
447 other => other,
448 };
449 let options = arg(2);
450 match delay(&options) {
451 Some(ms) => {
452 self.send_to_ref_delayed(&target, arg(1), ms, options.get("id").and_then(Value::as_str))
453 }
454 None => self.send_to_ref(&target, arg(1)),
455 }
456 }
457 "stop" => {
458 let target = arg(0);
459 if let Some(id) = target.as_str().or_else(|| target.get("id").and_then(Value::as_str)) {
460 self.stop(id);
461 }
462 }
463 "spawn" => {
464 let src = arg(0);
465 let src = src.as_str().ok_or("enq.spawn: the source must be a string (actors.<name>)")?;
466 return Ok(Some(Value::String(self.spawn(src, SpawnOptions::from_json(&arg(1))))));
467 }
468 other => return Err(format!("enq.{other} is not supported")),
469 }
470 Ok(None)
471 }
472}
473
474impl SpawnOptions {
475 pub fn from_json(options: &Value) -> Self {
477 Self {
478 id: options.get("id").and_then(Value::as_str).map(str::to_owned),
479 input: options.get("input").cloned(),
480 system_id: options.get("systemId").and_then(Value::as_str).map(str::to_owned),
481 sync_snapshot: options.get("syncSnapshot").and_then(Value::as_bool),
482 }
483 }
484}
485
486#[derive(Debug, Clone, Default, PartialEq, Eq)]
491pub enum HostActions {
492 #[default]
494 None,
495 Unimplemented,
497 Named(Vec<String>),
499}
500
501impl HostActions {
502 pub fn includes(&self, name: &str, implemented: bool) -> bool {
505 match self {
506 Self::None => false,
507 Self::Unimplemented => !implemented,
508 Self::Named(names) => names.iter().any(|n| n == name),
509 }
510 }
511}
512
513pub struct Registry<C, E> {
516 pub(crate) guards: FixedMap<String, Factory<GuardFn<C, E>>>,
517 pub(crate) actions: FixedMap<String, Factory<ActionFn>>,
518 pub(crate) delays: FixedMap<String, Factory<DelayFn<C, E>>>,
519 pub(crate) actors: Vec<(String, Arc<dyn crate::system::Logic>)>,
520 pub(crate) exprs: FixedMap<String, ExprFn<C, E>>,
521 pub(crate) contexts: FixedMap<String, ContextFn>,
522 pub(crate) evaluators: FixedMap<String, Arc<dyn Evaluator<C, E>>>,
523 pub(crate) host_actions: HostActions,
524}
525
526impl<C, E> Default for Registry<C, E> {
527 fn default() -> Self {
528 Self {
529 guards: FixedMap::default(),
530 actions: FixedMap::default(),
531 delays: FixedMap::default(),
532 actors: Vec::new(),
533 exprs: FixedMap::default(),
534 contexts: FixedMap::default(),
535 evaluators: FixedMap::default(),
536 host_actions: HostActions::None,
537 }
538 }
539}
540
541fn parse_params<P: DeserializeOwned>(params: &Value) -> Result<P, String> {
542 P::deserialize(params).map_err(|e| e.to_string())
543}
544
545impl<C: 'static, E: 'static> Registry<C, E> {
546 pub fn new() -> Self {
547 Self::default()
548 }
549
550 pub fn guard(
552 &mut self,
553 name: impl Into<String>,
554 f: impl Fn(&GuardArgs<'_, C, E>) -> bool + Send + Sync + 'static,
555 ) -> &mut Self {
556 let f = Arc::new(f);
557 self.guards.insert(
558 name.into(),
559 Arc::new(move |_| {
560 let f = f.clone();
561 Ok(Box::new(move |args: &GuardArgs<'_, C, E>| Ok(f(args))) as GuardFn<C, E>)
562 }),
563 );
564 self
565 }
566
567 pub fn guard_with<P>(
570 &mut self,
571 name: impl Into<String>,
572 f: impl Fn(&GuardArgs<'_, C, E>, &P) -> bool + Send + Sync + 'static,
573 ) -> &mut Self
574 where
575 P: DeserializeOwned + Send + Sync + 'static,
576 {
577 self.try_guard_with(name, move |args: &GuardArgs<'_, C, E>, p: &P| Ok(f(args, p)))
578 }
579
580 pub fn try_guard_with<P>(
584 &mut self,
585 name: impl Into<String>,
586 f: impl Fn(&GuardArgs<'_, C, E>, &P) -> Result<bool, String> + Send + Sync + 'static,
587 ) -> &mut Self
588 where
589 P: DeserializeOwned + Send + Sync + 'static,
590 {
591 let f = Arc::new(f);
592 self.guards.insert(
593 name.into(),
594 Arc::new(move |params| {
595 let p: P = parse_params(params)?;
596 let f = f.clone();
597 Ok(Box::new(move |args: &GuardArgs<'_, C, E>| f(args, &p)) as GuardFn<C, E>)
598 }),
599 );
600 self
601 }
602
603 pub fn host_actions(&mut self, host_actions: HostActions) -> &mut Self {
607 self.host_actions = host_actions;
608 self
609 }
610
611 pub(crate) fn is_host_action(&self, name: &str) -> bool {
613 self.host_actions.includes(name, self.actions.contains_key(name))
614 }
615
616 pub fn action(&mut self, name: impl Into<String>, f: impl Fn() + Send + Sync + 'static) -> &mut Self {
619 let f = Arc::new(f);
620 self.actions.insert(
621 name.into(),
622 Arc::new(move |_| {
623 let f = f.clone();
624 Ok(Arc::new(move || {
625 f();
626 Ok(())
627 }) as ActionFn)
628 }),
629 );
630 self
631 }
632
633 pub fn action_with<P>(&mut self, name: impl Into<String>, f: impl Fn(&P) + Send + Sync + 'static) -> &mut Self
636 where
637 P: DeserializeOwned + Send + Sync + 'static,
638 {
639 self.try_action_with(name, move |p: &P| {
640 f(p);
641 Ok(())
642 })
643 }
644
645 pub fn try_action_with<P>(
652 &mut self,
653 name: impl Into<String>,
654 f: impl Fn(&P) -> Result<(), String> + Send + Sync + 'static,
655 ) -> &mut Self
656 where
657 P: DeserializeOwned + Send + Sync + 'static,
658 {
659 let f = Arc::new(f);
660 self.actions.insert(
661 name.into(),
662 Arc::new(move |params| {
663 let p: P = parse_params(params)?;
664 let f = f.clone();
665 Ok(Arc::new(move || f(&p)) as ActionFn)
666 }),
667 );
668 self
669 }
670
671 pub fn actor(&mut self, name: impl Into<String>, logic: Arc<dyn crate::system::Logic>) -> &mut Self {
675 let name = name.into();
676 match self.actors.iter_mut().find(|(n, _)| *n == name) {
677 Some(entry) => entry.1 = logic,
678 None => self.actors.push((name, logic)),
679 }
680 self
681 }
682
683 pub fn delay(
686 &mut self,
687 name: impl Into<String>,
688 f: impl Fn(&C, &Ev<E>) -> u64 + Send + Sync + 'static,
689 ) -> &mut Self {
690 self.try_delay(name, move |c: &C, e: &Ev<E>| Ok(f(c, e)))
691 }
692
693 pub fn try_delay(
697 &mut self,
698 name: impl Into<String>,
699 f: impl Fn(&C, &Ev<E>) -> Result<u64, String> + Send + Sync + 'static,
700 ) -> &mut Self {
701 let f = Arc::new(f);
702 self.delays.insert(
703 name.into(),
704 Arc::new(move |_| {
705 let f = f.clone();
706 Ok(Box::new(move |c: &C, e: &Ev<E>| f(c, e)) as DelayFn<C, E>)
707 }),
708 );
709 self
710 }
711
712 pub fn delay_ms(&mut self, name: impl Into<String>, ms: u64) -> &mut Self {
714 self.delay(name, move |_, _| ms)
715 }
716
717 pub fn expr(
724 &mut self,
725 name: impl Into<String>,
726 f: impl Fn(&ExprArgs<'_, C, E>) -> Value + Send + Sync + 'static,
727 ) -> &mut Self {
728 self.exprs.insert(name.into(), Arc::new(f));
729 self
730 }
731
732 pub fn context(
735 &mut self,
736 name: impl Into<String>,
737 f: impl Fn(Option<&Value>) -> Value + Send + Sync + 'static,
738 ) -> &mut Self {
739 self.contexts.insert(name.into(), Arc::new(move |args: &ContextArgs<'_>| f(args.input)));
740 self
741 }
742
743 pub fn context_with(
746 &mut self,
747 name: impl Into<String>,
748 f: impl Fn(&ContextArgs<'_>) -> Value + Send + Sync + 'static,
749 ) -> &mut Self {
750 self.contexts.insert(name.into(), Arc::new(f));
751 self
752 }
753
754 pub fn evaluator(&mut self, lang: impl Into<String>, evaluator: impl Evaluator<C, E> + 'static) -> &mut Self {
759 let lang = lang.into();
760 assert!(lang != crate::load::RUST_LANG, "the rust language is built in: use Registry::expr");
761 self.evaluators.insert(lang, Arc::new(evaluator));
762 self
763 }
764}
765
766pub(crate) trait Spawner {
768 fn spawn(&self, src: &str, options: SpawnOptions) -> Option<ActorRef>;
769 fn self_ref(&self) -> ActorRef;
770 fn fail(&self, message: String);
771}
772
773pub struct ContextArgs<'a> {
776 pub input: Option<&'a Value>,
777 pub(crate) spawner: Option<&'a dyn Spawner>,
778}
779
780impl ContextArgs<'_> {
781 pub fn self_ref(&self) -> Option<ActorRef> {
784 self.spawner.map(|s| s.self_ref())
785 }
786
787 pub fn fail(&self, message: impl Into<String>) {
791 if let Some(s) = self.spawner {
792 s.fail(message.into());
793 }
794 }
795
796 pub fn spawn(&self, src: &str, options: SpawnOptions) -> Value {
804 match self.spawner.and_then(|s| s.spawn(src, options)) {
805 Some(r) => r.to_json(),
806 None => Value::Null,
807 }
808 }
809}
810
811#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
814pub enum Slot {
815 Context,
817 Guard,
819 Choice,
821 TransitionContext,
823 Input,
825 Transition,
827 Action,
829 ActionParams,
831 Delay,
833 Output,
835}
836
837impl Slot {
838 pub fn as_str(self) -> &'static str {
840 match self {
841 Slot::Context => "context",
842 Slot::Guard => "guard",
843 Slot::Choice => "choice",
844 Slot::TransitionContext => "transitionContext",
845 Slot::Input => "input",
846 Slot::Transition => "transition",
847 Slot::Action => "action",
848 Slot::ActionParams => "actionParams",
849 Slot::Delay => "delay",
850 Slot::Output => "output",
851 }
852 }
853}
854
855#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
857pub enum CodeKind {
858 Code,
859 Expr,
860}
861
862impl CodeKind {
863 pub fn as_str(self) -> &'static str {
865 match self {
866 CodeKind::Code => "code",
867 CodeKind::Expr => "expr",
868 }
869 }
870}
871
872#[derive(Debug, Clone, PartialEq, Eq)]
875pub struct Code {
876 pub id: u64,
879 pub lang: String,
880 pub source: String,
881 pub kind: CodeKind,
882 pub slot: Slot,
883 pub path: String,
885}
886
887pub enum Scope<'s, 'a, C, E> {
891 Expr(&'s ExprArgs<'a, C, E>),
892 Context(&'s ContextArgs<'a>),
893}
894
895pub trait Evaluator<C, E>: Send + Sync {
899 fn eval(&self, code: &Code, scope: Scope<'_, '_, C, E>) -> Result<Value, String>;
900}
901
902impl<C, E, F> Evaluator<C, E> for F
903where
904 F: Fn(&Code, Scope<'_, '_, C, E>) -> Result<Value, String> + Send + Sync,
905{
906 fn eval(&self, code: &Code, scope: Scope<'_, '_, C, E>) -> Result<Value, String> {
907 self(code, scope)
908 }
909}
910
911impl<C, E> Evaluator<C, E> for Arc<dyn Evaluator<C, E>> {
912 fn eval(&self, code: &Code, scope: Scope<'_, '_, C, E>) -> Result<Value, String> {
913 (**self).eval(code, scope)
914 }
915}
916
917pub struct HostEvaluator<F>(pub F);
942
943impl<F> HostEvaluator<F> {
944 fn code_json(code: &Code) -> String {
945 serde_json::json!({
946 "id": code.id,
947 "lang": code.lang,
948 "source": code.source,
949 "kind": code.kind.as_str(),
950 "slot": code.slot.as_str(),
951 "path": code.path,
952 })
953 .to_string()
954 }
955}
956
957impl<C, E, F> Evaluator<C, E> for HostEvaluator<F>
958where
959 C: serde::Serialize,
960 E: crate::event::EventType,
961 F: Fn(&str, &str) -> String + Send + Sync,
962{
963 fn eval(&self, code: &Code, scope: Scope<'_, '_, C, E>) -> Result<Value, String> {
964 let (scope, enq) = match scope {
965 Scope::Expr(a) => {
966 let mut json = a.scope_json()?;
967 json["enq"] = Value::Bool(a.enq.is_some());
968 (json, a.enq)
969 }
970 Scope::Context(a) => {
971 let mut json = serde_json::Map::new();
972 if let Some(input) = a.input {
973 json.insert("input".into(), input.clone());
974 }
975 if let Some(r) = a.self_ref() {
976 json.insert("self".into(), r.to_json());
977 }
978 (Value::Object(json), None)
979 }
980 };
981 let out = (self.0)(&Self::code_json(code), &scope.to_string());
982 let out: Value = serde_json::from_str(&out).map_err(|e| format!("the evaluator's result is not JSON: {e}"))?;
983 let Value::Object(mut out) = out else {
984 return Err(format!("the evaluator's result must be an object, not {out}"));
985 };
986 let error = match out.get("error") {
987 None => None,
988 Some(Value::String(message)) => Some(message.clone()),
989 Some(other) => return Err(format!("the evaluator's error must be a message string, not {other}")),
990 };
991 match out.get("enq") {
993 None => {}
994 Some(Value::Array(calls)) => {
995 let enq = enq.filter(|_| !calls.is_empty()).ok_or("enq is not available here");
996 for call in calls {
997 let parts = call.as_array().ok_or("an enq call is [op, ...args]")?;
998 let op = parts.first().and_then(Value::as_str).ok_or("an enq call is [op, ...args]")?;
999 if op == "spawn" && !parts.get(2).and_then(|o| o.get("id")).is_some_and(Value::is_string) {
1000 return Err("enq.spawn from a host evaluator needs an explicit id: \
1001 the id this runtime would choose cannot reach the code"
1002 .into());
1003 }
1004 let enq = enq?;
1005 enq.call(op, &parts[1..])?;
1006 if enq.ended() {
1010 return Ok(Value::Null);
1011 }
1012 }
1013 }
1014 Some(other) => {
1015 return Err(format!("the evaluator's enq must be an array of [op, ...args] calls, not {other}"))
1016 }
1017 }
1018 match error {
1019 Some(message) => Err(message),
1020 None => Ok(out.remove("value").unwrap_or(Value::Null)),
1021 }
1022 }
1023}