hydro_lang/location/
tick.rs

1use std::marker::PhantomData;
2
3use proc_macro2::Span;
4use sealed::sealed;
5use stageleft::{QuotedWithContext, q};
6
7#[cfg(stageleft_runtime)]
8use super::dynamic::DynLocation;
9use super::{Cluster, Location, LocationId, Process};
10use crate::compile::builder::FlowState;
11use crate::compile::ir::{HydroNode, HydroSource};
12#[cfg(stageleft_runtime)]
13use crate::forward_handle::{CycleCollection, CycleCollectionWithInitial};
14use crate::forward_handle::{ForwardHandle, ForwardRef, TickCycle, TickCycleHandle};
15use crate::live_collections::boundedness::{Bounded, Unbounded};
16use crate::live_collections::optional::Optional;
17use crate::live_collections::singleton::Singleton;
18use crate::live_collections::stream::{ExactlyOnce, Stream, TotalOrder};
19use crate::nondet::nondet;
20
21#[sealed]
22pub trait NoTick {}
23#[sealed]
24impl<T> NoTick for Process<'_, T> {}
25#[sealed]
26impl<T> NoTick for Cluster<'_, T> {}
27
28#[sealed]
29pub trait NoAtomic {}
30#[sealed]
31impl<T> NoAtomic for Process<'_, T> {}
32#[sealed]
33impl<T> NoAtomic for Cluster<'_, T> {}
34#[sealed]
35impl<'a, L> NoAtomic for Tick<L> where L: Location<'a> {}
36
37#[derive(Clone)]
38pub struct Atomic<Loc> {
39    pub(crate) tick: Tick<Loc>,
40}
41
42impl<L: DynLocation> DynLocation for Atomic<L> {
43    fn id(&self) -> LocationId {
44        LocationId::Atomic(Box::new(self.tick.id()))
45    }
46
47    fn flow_state(&self) -> &FlowState {
48        self.tick.flow_state()
49    }
50
51    fn is_top_level() -> bool {
52        L::is_top_level()
53    }
54}
55
56impl<'a, L> Location<'a> for Atomic<L>
57where
58    L: Location<'a>,
59{
60    type Root = L::Root;
61
62    fn root(&self) -> Self::Root {
63        self.tick.root()
64    }
65}
66
67#[sealed]
68impl<L> NoTick for Atomic<L> {}
69
70pub trait DeferTick {
71    fn defer_tick(self) -> Self;
72}
73
74/// Marks the stream as being inside the single global clock domain.
75#[derive(Clone)]
76pub struct Tick<L> {
77    pub(crate) id: usize,
78    pub(crate) l: L,
79}
80
81impl<L: DynLocation> DynLocation for Tick<L> {
82    fn id(&self) -> LocationId {
83        LocationId::Tick(self.id, Box::new(self.l.id()))
84    }
85
86    fn flow_state(&self) -> &FlowState {
87        self.l.flow_state()
88    }
89
90    fn is_top_level() -> bool {
91        false
92    }
93}
94
95impl<'a, L> Location<'a> for Tick<L>
96where
97    L: Location<'a>,
98{
99    type Root = L::Root;
100
101    fn root(&self) -> Self::Root {
102        self.l.root()
103    }
104}
105
106impl<'a, L> Tick<L>
107where
108    L: Location<'a>,
109{
110    pub fn outer(&self) -> &L {
111        &self.l
112    }
113
114    pub fn spin_batch(
115        &self,
116        batch_size: impl QuotedWithContext<'a, usize, L> + Copy + 'a,
117    ) -> Stream<(), Self, Bounded, TotalOrder, ExactlyOnce>
118    where
119        L: NoTick,
120    {
121        let out = self
122            .l
123            .spin()
124            .flat_map_ordered(q!(move |_| 0..batch_size))
125            .map(q!(|_| ()));
126
127        out.batch(self, nondet!(/** at runtime, `spin` produces a single value per tick, so each batch is guaranteed to be the same size. */))
128    }
129
130    pub fn singleton<T>(
131        &self,
132        e: impl QuotedWithContext<'a, T, Tick<L>>,
133    ) -> Singleton<T, Self, Bounded>
134    where
135        T: Clone,
136    {
137        let e = e.splice_untyped_ctx(self);
138
139        Singleton::new(
140            self.clone(),
141            HydroNode::SingletonSource {
142                value: e.into(),
143                metadata: self.new_node_metadata(Singleton::<T, Self, Bounded>::collection_kind()),
144            },
145        )
146    }
147
148    /// Creates an [`Optional`] which has a null value on every tick.
149    ///
150    /// # Example
151    /// ```rust
152    /// # #[cfg(feature = "deploy")] {
153    /// # use hydro_lang::prelude::*;
154    /// # use futures::StreamExt;
155    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
156    /// let tick = process.tick();
157    /// let optional = tick.none::<i32>();
158    /// optional.unwrap_or(tick.singleton(q!(123)))
159    /// # .all_ticks()
160    /// # }, |mut stream| async move {
161    /// // 123
162    /// # assert_eq!(stream.next().await.unwrap(), 123);
163    /// # }));
164    /// # }
165    /// ```
166    pub fn none<T>(&self) -> Optional<T, Self, Bounded> {
167        let e = q!([]);
168        let e = QuotedWithContext::<'a, [(); 0], Self>::splice_typed_ctx(e, self);
169
170        let unit_optional: Optional<(), Self, Bounded> = Optional::new(
171            self.clone(),
172            HydroNode::Source {
173                source: HydroSource::Iter(e.into()),
174                metadata: self.new_node_metadata(Optional::<(), Self, Bounded>::collection_kind()),
175            },
176        );
177
178        unit_optional.map(q!(|_| unreachable!())) // always empty
179    }
180
181    /// Creates an [`Optional`] which will have the provided static value on the first tick, and be
182    /// null on all subsequent ticks.
183    ///
184    /// This is useful for bootstrapping stateful computations which need an initial value.
185    ///
186    /// # Example
187    /// ```rust
188    /// # #[cfg(feature = "deploy")] {
189    /// # use hydro_lang::prelude::*;
190    /// # use futures::StreamExt;
191    /// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
192    /// let tick = process.tick();
193    /// // ticks are lazy by default, forces the second tick to run
194    /// tick.spin_batch(q!(1)).all_ticks().for_each(q!(|_| {}));
195    /// let optional = tick.optional_first_tick(q!(5));
196    /// optional.unwrap_or(tick.singleton(q!(123))).all_ticks()
197    /// # }, |mut stream| async move {
198    /// // 5, 123, 123, 123, ...
199    /// # assert_eq!(stream.next().await.unwrap(), 5);
200    /// # assert_eq!(stream.next().await.unwrap(), 123);
201    /// # assert_eq!(stream.next().await.unwrap(), 123);
202    /// # assert_eq!(stream.next().await.unwrap(), 123);
203    /// # }));
204    /// # }
205    /// ```
206    pub fn optional_first_tick<T: Clone>(
207        &self,
208        e: impl QuotedWithContext<'a, T, Tick<L>>,
209    ) -> Optional<T, Self, Bounded> {
210        let e_arr = q!([e]);
211        let e = e_arr.splice_untyped_ctx(self);
212
213        Optional::new(
214            self.clone(),
215            HydroNode::Batch {
216                inner: Box::new(HydroNode::Source {
217                    source: HydroSource::Iter(e.into()),
218                    metadata: self
219                        .outer()
220                        .new_node_metadata(Optional::<T, L, Unbounded>::collection_kind()),
221                }),
222                metadata: self.new_node_metadata(Optional::<T, Self, Bounded>::collection_kind()),
223            },
224        )
225    }
226
227    #[expect(
228        private_bounds,
229        reason = "only Hydro collections can implement ReceiverComplete"
230    )]
231    pub fn forward_ref<S>(&self) -> (ForwardHandle<'a, S>, S)
232    where
233        S: CycleCollection<'a, ForwardRef, Location = Self>,
234        L: NoTick,
235    {
236        let next_id = self.flow_state().borrow_mut().next_cycle_id();
237        let ident = syn::Ident::new(&format!("cycle_{}", next_id), Span::call_site());
238
239        (
240            ForwardHandle {
241                completed: false,
242                ident: ident.clone(),
243                expected_location: Location::id(self),
244                _phantom: PhantomData,
245            },
246            S::create_source(ident, self.clone()),
247        )
248    }
249
250    #[expect(
251        private_bounds,
252        reason = "only Hydro collections can implement ReceiverComplete"
253    )]
254    pub fn cycle<S>(&self) -> (TickCycleHandle<'a, S>, S)
255    where
256        S: CycleCollection<'a, TickCycle, Location = Self> + DeferTick,
257        L: NoTick,
258    {
259        let next_id = self.flow_state().borrow_mut().next_cycle_id();
260        let ident = syn::Ident::new(&format!("cycle_{}", next_id), Span::call_site());
261
262        (
263            TickCycleHandle {
264                completed: false,
265                ident: ident.clone(),
266                expected_location: Location::id(self),
267                _phantom: PhantomData,
268            },
269            S::create_source(ident, self.clone()).defer_tick(),
270        )
271    }
272
273    #[expect(
274        private_bounds,
275        reason = "only Hydro collections can implement ReceiverComplete"
276    )]
277    pub fn cycle_with_initial<S>(&self, initial: S) -> (TickCycleHandle<'a, S>, S)
278    where
279        S: CycleCollectionWithInitial<'a, TickCycle, Location = Self>,
280    {
281        let next_id = self.flow_state().borrow_mut().next_cycle_id();
282        let ident = syn::Ident::new(&format!("cycle_{}", next_id), Span::call_site());
283
284        (
285            TickCycleHandle {
286                completed: false,
287                ident: ident.clone(),
288                expected_location: Location::id(self),
289                _phantom: PhantomData,
290            },
291            // no need to defer_tick, create_source_with_initial does it for us
292            S::create_source_with_initial(ident, initial, self.clone()),
293        )
294    }
295}
296
297#[cfg(test)]
298mod tests {
299    #[cfg(feature = "sim")]
300    use stageleft::q;
301
302    #[cfg(feature = "sim")]
303    use crate::live_collections::sliced::sliced;
304    #[cfg(feature = "sim")]
305    use crate::location::Location;
306    #[cfg(feature = "sim")]
307    use crate::nondet::nondet;
308    #[cfg(feature = "sim")]
309    use crate::prelude::FlowBuilder;
310
311    #[cfg(feature = "sim")]
312    #[test]
313    fn sim_atomic_stream() {
314        let flow = FlowBuilder::new();
315        let node = flow.process::<()>();
316
317        let (write_send, write_req) = node.sim_input();
318        let (read_send, read_req) = node.sim_input::<(), _, _>();
319
320        let tick = node.tick();
321        let atomic_write = write_req.atomic(&tick);
322        let current_state = atomic_write.clone().fold(
323            q!(|| 0),
324            q!(|state: &mut i32, v: i32| {
325                *state += v;
326            }),
327        );
328
329        let write_ack_recv = atomic_write.end_atomic().sim_output();
330        let read_response_recv = sliced! {
331            let batch_of_req = use(read_req, nondet!(/** test */));
332            let latest_singleton = use::atomic(current_state, nondet!(/** test */));
333            batch_of_req.cross_singleton(latest_singleton)
334        }
335        .sim_output();
336
337        let sim_compiled = flow.sim().compiled();
338        let instances = sim_compiled.exhaustive(async || {
339            write_send.send(1);
340            write_ack_recv.assert_yields([1]).await;
341            read_send.send(());
342            assert!(read_response_recv.next().await.is_some_and(|(_, v)| v >= 1));
343        });
344
345        assert_eq!(instances, 1);
346
347        let instances_read_before_write = sim_compiled.exhaustive(async || {
348            write_send.send(1);
349            read_send.send(());
350            write_ack_recv.assert_yields([1]).await;
351            let _ = read_response_recv.next().await;
352        });
353
354        assert_eq!(instances_read_before_write, 3); // read before write, write before read, both in same tick
355    }
356
357    #[cfg(feature = "sim")]
358    #[test]
359    #[should_panic]
360    fn sim_non_atomic_stream() {
361        // shows that atomic is necessary
362        let flow = FlowBuilder::new();
363        let node = flow.process::<()>();
364
365        let (write_send, write_req) = node.sim_input();
366        let (read_send, read_req) = node.sim_input::<(), _, _>();
367
368        let current_state = write_req.clone().fold(
369            q!(|| 0),
370            q!(|state: &mut i32, v: i32| {
371                *state += v;
372            }),
373        );
374
375        let write_ack_recv = write_req.sim_output();
376
377        let read_response_recv = sliced! {
378            let batch_of_req = use(read_req, nondet!(/** test */));
379            let latest_singleton = use(current_state, nondet!(/** test */));
380            batch_of_req.cross_singleton(latest_singleton)
381        }
382        .sim_output();
383
384        flow.sim().exhaustive(async || {
385            write_send.send(1);
386            write_ack_recv.assert_yields([1]).await;
387            read_send.send(());
388
389            if let Some((_, v)) = read_response_recv.next().await {
390                assert_eq!(v, 1);
391            }
392        });
393    }
394}