Skip to main content

bast3st_eval/spec/machine/
machine_creation.rs

1use std::borrow::Cow;
2
3use crate::spec::{
4    Entity, EntityId, PrimitiveValue, ValueReference,
5    machine::{Machine, MissingValue, Param, cast_param},
6    runtime::{
7        CheapBorrowFromAny, ClarifiedCerrMerging, CompiledRegex, NetworkRequest,
8        PossibleRuntimeValue, RuntimeAny, RuntimeValue, Selector, SpecializeFrom,
9        SpecificTaskRequest,
10    },
11};
12
13pub trait MachineConstruction<E, RuntimeT: Send>: Sized {
14    fn query_cow<R: ClarifiedCerrMerging + 'static + Send>(
15        self,
16        closure: impl for<'a> FnOnce(Cow<'a, RuntimeT>) -> Machine<R> + 'static + Send,
17    ) -> Machine<R>;
18
19    fn query<R: ClarifiedCerrMerging + 'static + Send>(
20        self,
21        closure: impl FnOnce(RuntimeT) -> Machine<R> + 'static + Send,
22    ) -> Machine<R>
23    where
24        RuntimeT: Clone,
25    {
26        self.query_cow(|cow| closure(cow.into_owned()))
27    }
28
29    fn query_ref<R: ClarifiedCerrMerging + 'static + Send>(
30        self,
31        closure: impl for<'a> FnOnce(&'a RuntimeT) -> Machine<R> + 'static + Send,
32    ) -> Machine<R>
33    where
34        RuntimeT: Clone + CheapBorrowFromAny,
35    {
36        self.query_cow(|cow| closure(&cow))
37    }
38}
39
40impl<E, RuntimeT: Send> MachineConstruction<E, RuntimeT> for EntityId<E>
41where
42    EntityId<E>: PossibleRuntimeValue<RuntimeT>,
43    RuntimeT: Clone + SpecializeFrom,
44    Entity: From<E>,
45{
46    fn query_cow<R: ClarifiedCerrMerging + 'static>(
47        self,
48        closure: impl for<'a> FnOnce(Cow<'a, RuntimeT>) -> Machine<R> + 'static + Send,
49    ) -> Machine<R> {
50        let id: EntityId<Entity> = self.cast_id();
51        let on_push =
52            move |delivered: Param<'_>| Machine::from_res(cast_param(delivered).map(closure));
53        Machine::from_pushable(id, Box::new(on_push))
54    }
55}
56
57impl<RuntimeT: Send> MachineConstruction<ValueReference, RuntimeT> for ValueReference
58where
59    ValueReference: PossibleRuntimeValue<RuntimeT>,
60    RuntimeT: Clone + SpecializeFrom + 'static,
61    EntityId<Entity>: PossibleRuntimeValue<RuntimeT>,
62{
63    fn query_cow<R: ClarifiedCerrMerging + 'static + Send>(
64        self,
65        closure: impl for<'a> FnOnce(Cow<'a, RuntimeT>) -> Machine<R> + 'static + Send,
66    ) -> Machine<R> {
67        match self {
68            Self::EntityId(id) => id.cast_id::<Entity>().query_cow(closure),
69            Self::LitString(text) => {
70                let any = RuntimeAny::Value(RuntimeValue::Prim(PrimitiveValue::Str(text.clone())));
71                let run = RuntimeT::specialize_from(Cow::Owned(any)).map(|c| c.into_owned());
72                let on_push = move |_: Param<'_>| {
73                    let converted: Cow<'_, RuntimeT> = match run {
74                        Ok(o) => Cow::Owned(o),
75                        Err(e) => return e.into(),
76                    };
77                    closure(converted)
78                };
79                Machine::from_pushable(MissingValue::NoValueNeeded, Box::new(on_push))
80            }
81        }
82    }
83}
84impl<RuntimeT: Send> MachineConstruction<ValueReference, RuntimeT> for &ValueReference
85where
86    ValueReference: PossibleRuntimeValue<RuntimeT>,
87    RuntimeT: Clone + SpecializeFrom + 'static,
88    EntityId<Entity>: PossibleRuntimeValue<RuntimeT>,
89{
90    fn query_cow<R: ClarifiedCerrMerging + 'static + Send>(
91        self,
92        closure: impl for<'a> FnOnce(Cow<'a, RuntimeT>) -> Machine<R> + 'static + Send,
93    ) -> Machine<R> {
94        self.clone().query_cow(closure)
95    }
96}
97
98impl<RuntimeT: Send> MachineConstruction<Selector, RuntimeT> for Selector
99where
100    Selector: PossibleRuntimeValue<RuntimeT>,
101    RuntimeT: SpecializeFrom,
102{
103    fn query_cow<R: ClarifiedCerrMerging + 'static + Send>(
104        self,
105        closure: impl for<'a> FnOnce(Cow<'a, RuntimeT>) -> Machine<R> + 'static + Send,
106    ) -> Machine<R> {
107        let on_push = move |param: Param<'_>| Machine::from_res(cast_param(param).map(closure));
108        Machine::from_pushable(self, Box::new(on_push))
109    }
110}
111
112/// WARNING: this always clones
113/// A solution, that involves work, could be to replace [`Cow`] in the closure signature
114/// with an associated type, but this would prevent inference.
115/// This is left open as most of the types in this project are cheap to clone
116///
117/// The problem is that a reference `&RuntimeT` can only be converted to an owned
118/// value of type `Option<&RuntimeT>` and *not* to `&Option<RuntimeT>` what would be
119/// needed for [`Cow`]. The other direction is possible using [`Option::as_ref`].
120///
121/// This direction seems to be impossible so the only solution would be a new trait with
122/// new methods specifically for `Option`.
123impl<E, T, RuntimeT: Send> MachineConstruction<E, Option<RuntimeT>> for Option<T>
124where
125    RuntimeT: Clone,
126    T: MachineConstruction<E, RuntimeT>,
127{
128    fn query_cow<R: ClarifiedCerrMerging + 'static + Send>(
129        self,
130        closure: impl for<'a> FnOnce(Cow<'a, Option<RuntimeT>>) -> Machine<R> + 'static + Send,
131    ) -> Machine<R> {
132        if let Some(val) = self {
133            val.query_cow(move |runtime| closure(Cow::Owned(Some(runtime.into_owned()))))
134        } else {
135            closure(Cow::Owned(None))
136        }
137    }
138}
139
140macro_rules! impl_task_queries {
141    ($task: ty) => {
142        impl<RuntimeT: Send> MachineConstruction<$task, RuntimeT> for $task
143        where
144            RuntimeT: SpecializeFrom<<$task as SpecificTaskRequest>::MainOutput>,
145            <$task as SpecificTaskRequest>::MainOutput: Clone,
146        {
147            fn query_cow<R: ClarifiedCerrMerging + 'static + Send>(
148                self,
149                closure: impl for<'a> FnOnce(Cow<'a, RuntimeT>) -> Machine<R> + 'static + Send,
150            ) -> Machine<R> {
151                Machine::from_task(
152                    self.clone(),
153                    Box::new(move |param| RuntimeT::specialize_from(param).map(closure).into()),
154                )
155            }
156        }
157    };
158}
159impl_task_queries!(NetworkRequest);
160impl_task_queries!(CompiledRegex);
161
162pub trait MachineConstructionN<Closure, Extra, Ret> {
163    fn query_n(self, closure: Closure) -> Machine<Ret>;
164}
165
166impl<C, E1, E2, R1, R2, Ret: ClarifiedCerrMerging + 'static + Send, T1: ToOwned, T2: ToOwned>
167    MachineConstructionN<C, (E1, E2, R1, R2), Ret> for (&T1, &T2)
168where
169    C: FnOnce(R1, R2) -> Machine<Ret> + 'static + Send,
170    R1: Clone + 'static + Send,
171    R2: Clone + 'static + Send,
172    T1::Owned: MachineConstruction<E1, R1> + 'static + Send,
173    T2::Owned: MachineConstruction<E2, R2> + 'static + Send,
174{
175    fn query_n(self, closure: C) -> Machine<Ret> {
176        let t1 = self.0.to_owned();
177        let t2 = self.1.to_owned();
178        t1.query::<Ret>(move |r1: R1| t2.query::<Ret>(move |r2: R2| closure(r1, r2)))
179    }
180}