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::{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#[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!())
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 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!())) }
180
181 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 cycle<S>(&self) -> (TickCycleHandle<'a, S>, S)
232 where
233 S: CycleCollection<'a, TickCycle, Location = Self> + DeferTick,
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 TickCycleHandle {
241 completed: false,
242 ident: ident.clone(),
243 expected_location: Location::id(self),
244 _phantom: PhantomData,
245 },
246 S::create_source(ident, self.clone()).defer_tick(),
247 )
248 }
249
250 #[expect(
251 private_bounds,
252 reason = "only Hydro collections can implement ReceiverComplete"
253 )]
254 pub fn cycle_with_initial<S>(&self, initial: S) -> (TickCycleHandle<'a, S>, S)
255 where
256 S: CycleCollectionWithInitial<'a, TickCycle, Location = Self>,
257 {
258 let next_id = self.flow_state().borrow_mut().next_cycle_id();
259 let ident = syn::Ident::new(&format!("cycle_{}", next_id), Span::call_site());
260
261 (
262 TickCycleHandle {
263 completed: false,
264 ident: ident.clone(),
265 expected_location: Location::id(self),
266 _phantom: PhantomData,
267 },
268 S::create_source_with_initial(ident, initial, self.clone()),
270 )
271 }
272}
273
274#[cfg(test)]
275mod tests {
276 #[cfg(feature = "sim")]
277 use stageleft::q;
278
279 #[cfg(feature = "sim")]
280 use crate::live_collections::sliced::sliced;
281 #[cfg(feature = "sim")]
282 use crate::location::Location;
283 #[cfg(feature = "sim")]
284 use crate::nondet::nondet;
285 #[cfg(feature = "sim")]
286 use crate::prelude::FlowBuilder;
287
288 #[cfg(feature = "sim")]
289 #[test]
290 fn sim_atomic_stream() {
291 let flow = FlowBuilder::new();
292 let node = flow.process::<()>();
293
294 let (write_send, write_req) = node.sim_input();
295 let (read_send, read_req) = node.sim_input::<(), _, _>();
296
297 let tick = node.tick();
298 let atomic_write = write_req.atomic(&tick);
299 let current_state = atomic_write.clone().fold(
300 q!(|| 0),
301 q!(|state: &mut i32, v: i32| {
302 *state += v;
303 }),
304 );
305
306 let write_ack_recv = atomic_write.end_atomic().sim_output();
307 let read_response_recv = sliced! {
308 let batch_of_req = use(read_req, nondet!());
309 let latest_singleton = use::atomic(current_state, nondet!());
310 batch_of_req.cross_singleton(latest_singleton)
311 }
312 .sim_output();
313
314 let sim_compiled = flow.sim().compiled();
315 let instances = sim_compiled.exhaustive(async || {
316 write_send.send(1);
317 write_ack_recv.assert_yields([1]).await;
318 read_send.send(());
319 assert!(read_response_recv.next().await.is_some_and(|(_, v)| v >= 1));
320 });
321
322 assert_eq!(instances, 1);
323
324 let instances_read_before_write = sim_compiled.exhaustive(async || {
325 write_send.send(1);
326 read_send.send(());
327 write_ack_recv.assert_yields([1]).await;
328 let _ = read_response_recv.next().await;
329 });
330
331 assert_eq!(instances_read_before_write, 3); }
333
334 #[cfg(feature = "sim")]
335 #[test]
336 #[should_panic]
337 fn sim_non_atomic_stream() {
338 let flow = FlowBuilder::new();
340 let node = flow.process::<()>();
341
342 let (write_send, write_req) = node.sim_input();
343 let (read_send, read_req) = node.sim_input::<(), _, _>();
344
345 let current_state = write_req.clone().fold(
346 q!(|| 0),
347 q!(|state: &mut i32, v: i32| {
348 *state += v;
349 }),
350 );
351
352 let write_ack_recv = write_req.sim_output();
353
354 let read_response_recv = sliced! {
355 let batch_of_req = use(read_req, nondet!());
356 let latest_singleton = use(current_state, nondet!());
357 batch_of_req.cross_singleton(latest_singleton)
358 }
359 .sim_output();
360
361 flow.sim().exhaustive(async || {
362 write_send.send(1);
363 write_ack_recv.assert_yields([1]).await;
364 read_send.send(());
365
366 if let Some((_, v)) = read_response_recv.next().await {
367 assert_eq!(v, 1);
368 }
369 });
370 }
371}