1use stageleft::{QuotedWithContext, q};
18
19#[cfg(stageleft_runtime)]
20use super::dynamic::DynLocation;
21use super::{Location, LocationId};
22use crate::compile::builder::{ClockId, FlowState};
23use crate::compile::ir::{HydroNode, HydroSource};
24#[cfg(stageleft_runtime)]
25use crate::forward_handle::{CycleCollection, CycleCollectionWithInitial};
26use crate::forward_handle::{TickCycle, TickCycleHandle};
27#[cfg(feature = "tokio")]
28use crate::live_collections::Singleton;
29use crate::live_collections::boundedness::Bounded;
30use crate::live_collections::optional::Optional;
31use crate::live_collections::stream::{ExactlyOnce, Stream, TotalOrder};
32use crate::location::TopLevel;
33#[cfg(feature = "tokio")]
34use crate::nondet::NonDet;
35use crate::nondet::nondet;
36
37#[derive(Clone)]
48pub struct Atomic<Loc> {
49 pub(crate) tick: Tick<Loc>,
50}
51
52impl<L: DynLocation> DynLocation for Atomic<L> {
53 fn dyn_id(&self) -> LocationId {
54 LocationId::Atomic(Box::new(self.tick.dyn_id()))
55 }
56
57 fn flow_state(&self) -> &FlowState {
58 self.tick.flow_state()
59 }
60
61 fn is_top_level() -> bool {
62 L::is_top_level()
63 }
64
65 fn multiversioned(&self) -> bool {
66 self.tick.multiversioned()
67 }
68
69 fn cluster_consistency() -> Option<super::dynamic::ClusterConsistency> {
70 L::cluster_consistency()
71 }
72}
73
74impl<'a, L> Location<'a> for Atomic<L>
75where
76 L: Location<'a>,
77{
78 type Root = L::Root;
79
80 type SimHookScope = L::SimHookScope;
81
82 type DropConsistency = Atomic<L::DropConsistency>;
83
84 fn consistency() -> Option<super::dynamic::ClusterConsistency> {
85 L::consistency()
86 }
87
88 fn root(&self) -> Self::Root {
89 self.tick.root()
90 }
91
92 fn drop_consistency(&self) -> Self::DropConsistency {
93 Atomic {
94 tick: self.tick.drop_consistency(),
95 }
96 }
97
98 fn from_drop_consistency(l2: Self::DropConsistency) -> Self {
99 Atomic {
100 tick: Tick::from_drop_consistency(l2.tick),
101 }
102 }
103}
104
105pub trait DeferTick {
112 fn defer_tick(self) -> Self;
114}
115
116#[derive(Clone)]
118pub struct Tick<L> {
119 pub(crate) id: Option<ClockId>,
121 pub(crate) l: L,
123}
124
125impl<L: DynLocation> DynLocation for Tick<L> {
126 fn dyn_id(&self) -> LocationId {
127 LocationId::Tick {
128 tick: self.id,
129 parent_location: Box::new(self.l.dyn_id()),
130 }
131 }
132
133 fn flow_state(&self) -> &FlowState {
134 self.l.flow_state()
135 }
136
137 fn is_top_level() -> bool {
138 false
139 }
140
141 fn multiversioned(&self) -> bool {
142 self.l.multiversioned()
143 }
144
145 fn cluster_consistency() -> Option<super::dynamic::ClusterConsistency> {
146 L::cluster_consistency()
147 }
148}
149
150impl<'a, L> Location<'a> for Tick<L>
151where
152 L: Location<'a>,
153{
154 type Root = L::Root;
155
156 type SimHookScope = L::SimHookScope;
157
158 type DropConsistency = Tick<L::DropConsistency>;
159
160 fn consistency() -> Option<super::dynamic::ClusterConsistency> {
161 L::consistency()
162 }
163
164 fn root(&self) -> Self::Root {
165 self.l.root()
166 }
167
168 fn drop_consistency(&self) -> Self::DropConsistency {
169 Tick {
170 id: self.id,
171 l: self.l.drop_consistency(),
172 }
173 }
174
175 fn from_drop_consistency(l2: Self::DropConsistency) -> Self {
176 Tick {
177 id: l2.id,
178 l: L::from_drop_consistency(l2.l),
179 }
180 }
181}
182
183impl<'a, L> Tick<L>
184where
185 L: Location<'a>,
186{
187 pub fn parent_location(&self) -> &L {
192 &self.l
193 }
194
195 #[deprecated(note = "use `.parent_location()` instead")]
197 pub fn outer(&self) -> &L {
198 self.parent_location()
199 }
200
201 pub fn spin_batch(
207 &self,
208 batch_size: impl QuotedWithContext<
209 'a,
210 usize,
211 crate::live_collections::OperatorContext<
212 L,
213 crate::live_collections::boundedness::Unbounded,
214 >,
215 > + Copy
216 + 'a,
217 ) -> Stream<(), Self, Bounded, TotalOrder, ExactlyOnce>
218 where
219 L: TopLevel<'a>,
220 {
221 let out = self
222 .l
223 .spin()
224 .flat_map_ordered(q!(move |_| 0..batch_size))
225 .map(q!(|_| ()));
226
227 let inner = out.batch(self, nondet!());
228 Stream::new(self.clone(), inner.ir_node.replace(HydroNode::Placeholder))
229 }
230
231 pub fn none<T>(&self) -> Optional<T, Self, Bounded> {
252 let e = q!([]);
253 let e = QuotedWithContext::<'a, [(); 0], Self>::splice_typed_ctx(e, self);
254
255 let unit_optional: Optional<(), Self, Bounded> = Optional::new(
256 self.clone(),
257 HydroNode::Source {
258 source: HydroSource::Iter(e.into()),
259 metadata: self.new_node_metadata(Optional::<(), Self, Bounded>::collection_kind()),
260 },
261 );
262
263 unit_optional.map(q!(|_| unreachable!())) }
265
266 pub fn optional_first_tick<T: Clone>(
292 &self,
293 e: impl QuotedWithContext<'a, T, Tick<L>>,
294 ) -> Optional<T, Self, Bounded> {
295 let e = e.splice_untyped_ctx(self);
296
297 Optional::new(
298 self.clone(),
299 HydroNode::SingletonSource {
300 value: e.into(),
301 first_tick_only: true,
302 metadata: self.new_node_metadata(Optional::<T, Self, Bounded>::collection_kind()),
303 },
304 )
305 }
306
307 #[cfg(feature = "tokio")]
315 pub fn current_tick_instant(
316 &self,
317 _nondet: NonDet,
318 ) -> Singleton<tokio::time::Instant, Tick<L::DropConsistency>, Bounded>
319 where
320 Self: Sized,
321 {
322 self.singleton(q!(tokio::time::Instant::now()))
324 }
325
326 #[expect(
335 private_bounds,
336 reason = "only Hydro collections can implement ReceiverComplete"
337 )]
338 pub fn cycle<S, L2: Location<'a, DropConsistency = Tick<L::DropConsistency>>>(
339 &self,
340 ) -> (TickCycleHandle<'a, S>, S)
341 where
342 S: CycleCollection<'a, TickCycle, Location = L2> + DeferTick,
343 {
344 let cycle_id = self.flow_state().borrow_mut().next_cycle_id();
345 (
346 TickCycleHandle::new(cycle_id, Location::id(self)),
347 S::create_source(cycle_id, self.clone().with_consistency_of()).defer_tick(),
348 )
349 }
350
351 #[expect(
358 private_bounds,
359 reason = "only Hydro collections can implement ReceiverComplete"
360 )]
361 pub fn cycle_with_initial<S, L2: Location<'a, DropConsistency = Tick<L::DropConsistency>>>(
362 &self,
363 initial: S,
364 ) -> (TickCycleHandle<'a, S>, S)
365 where
366 S: CycleCollectionWithInitial<'a, TickCycle, Location = L2>,
367 {
368 let cycle_id = self.flow_state().borrow_mut().next_cycle_id();
369 (
370 TickCycleHandle::new(cycle_id, Location::id(self)),
371 S::create_source_with_initial(cycle_id, initial, self.clone().with_consistency_of()),
373 )
374 }
375}
376
377#[cfg(test)]
378mod tests {
379 #[cfg(feature = "sim")]
380 use stageleft::q;
381
382 #[cfg(feature = "sim")]
383 use crate::live_collections::sliced::sliced;
384 #[cfg(feature = "sim")]
385 use crate::location::Location;
386 #[cfg(feature = "sim")]
387 use crate::nondet::nondet;
388 #[cfg(feature = "sim")]
389 use crate::prelude::FlowBuilder;
390
391 #[cfg(feature = "sim")]
392 #[test]
393 fn sim_atomic_stream() {
394 let mut flow = FlowBuilder::new();
395 let node = flow.process::<()>();
396
397 let (write_send, write_req) = node.sim_input();
398 let (read_send, read_req) = node.sim_input::<(), _, _>();
399
400 let atomic_write = write_req.atomic();
401 let current_state = atomic_write.clone().fold(
402 q!(|| 0),
403 q!(|state: &mut i32, v: i32| {
404 *state += v;
405 }),
406 );
407
408 let write_ack_recv = atomic_write.end_atomic().sim_output();
409 let read_response_recv = sliced! {
410 let batch_of_req = use::batch(read_req, nondet!());
411 let latest_singleton = use::atomic(current_state, nondet!());
412 batch_of_req.cross_singleton(latest_singleton)
413 }
414 .sim_output();
415
416 let sim_compiled = flow.sim().compiled();
417 let instances = sim_compiled.exhaustive(async || {
418 write_send.send(1);
419 write_ack_recv.assert_yields([1]).await;
420 read_send.send(());
421 assert!(read_response_recv.next().await.1 >= 1);
422 });
423
424 assert_eq!(instances, 1);
425
426 let instances_read_before_write = sim_compiled.exhaustive(async || {
427 write_send.send(1);
428 read_send.send(());
429 write_ack_recv.assert_yields([1]).await;
430 let _ = read_response_recv.next().await;
431 });
432
433 assert_eq!(instances_read_before_write, 3); }
435
436 #[cfg(feature = "sim")]
437 #[test]
438 #[should_panic]
439 fn sim_non_atomic_stream() {
440 let mut flow = FlowBuilder::new();
442 let node = flow.process::<()>();
443
444 let (write_send, write_req) = node.sim_input();
445 let (read_send, read_req) = node.sim_input::<(), _, _>();
446
447 let current_state = write_req.clone().fold(
448 q!(|| 0),
449 q!(|state: &mut i32, v: i32| {
450 *state += v;
451 }),
452 );
453
454 let write_ack_recv = write_req.sim_output();
455
456 let read_response_recv = sliced! {
457 let batch_of_req = use::batch(read_req, nondet!());
458 let latest_singleton = use::snapshot(current_state, nondet!());
459 batch_of_req.cross_singleton(latest_singleton)
460 }
461 .sim_output();
462
463 flow.sim().exhaustive(async || {
464 write_send.send(1);
465 write_ack_recv.assert_yields([1]).await;
466 read_send.send(());
467
468 let ((), v) = read_response_recv.next().await;
469 assert_eq!(v, 1);
470 });
471 }
472}