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#[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_arr = q!([e]);
138 let e = e_arr.splice_untyped_ctx(self);
139
140 Singleton::new(
141 self.clone(),
142 HydroNode::Source {
143 source: HydroSource::Iter(e.into()),
144 metadata: self.new_node_metadata(Singleton::<T, Self, Bounded>::collection_kind()),
145 },
146 )
147 }
148
149 pub fn none<T>(&self) -> Optional<T, Self, Bounded> {
166 let e = q!([]);
167 let e = QuotedWithContext::<'a, [(); 0], Self>::splice_typed_ctx(e, self);
168
169 let unit_optional: Optional<(), Self, Bounded> = Optional::new(
170 self.clone(),
171 HydroNode::Source {
172 source: HydroSource::Iter(e.into()),
173 metadata: self.new_node_metadata(Optional::<(), Self, Bounded>::collection_kind()),
174 },
175 );
176
177 unit_optional.map(q!(|_| unreachable!())) }
179
180 pub fn optional_first_tick<T: Clone>(
204 &self,
205 e: impl QuotedWithContext<'a, T, Tick<L>>,
206 ) -> Optional<T, Self, Bounded> {
207 let e_arr = q!([e]);
208 let e = e_arr.splice_untyped_ctx(self);
209
210 Optional::new(
211 self.clone(),
212 HydroNode::Batch {
213 inner: Box::new(HydroNode::Source {
214 source: HydroSource::Iter(e.into()),
215 metadata: self
216 .outer()
217 .new_node_metadata(Optional::<T, L, Unbounded>::collection_kind()),
218 }),
219 metadata: self.new_node_metadata(Optional::<T, Self, Bounded>::collection_kind()),
220 },
221 )
222 }
223
224 #[expect(
225 private_bounds,
226 reason = "only Hydro collections can implement ReceiverComplete"
227 )]
228 pub fn forward_ref<S>(&self) -> (ForwardHandle<'a, S>, S)
229 where
230 S: CycleCollection<'a, ForwardRef, Location = Self>,
231 L: NoTick,
232 {
233 let next_id = self.flow_state().borrow_mut().next_cycle_id();
234 let ident = syn::Ident::new(&format!("cycle_{}", next_id), Span::call_site());
235
236 (
237 ForwardHandle {
238 completed: false,
239 ident: ident.clone(),
240 expected_location: Location::id(self),
241 _phantom: PhantomData,
242 },
243 S::create_source(ident, self.clone()),
244 )
245 }
246
247 #[expect(
248 private_bounds,
249 reason = "only Hydro collections can implement ReceiverComplete"
250 )]
251 pub fn cycle<S>(&self) -> (TickCycleHandle<'a, S>, S)
252 where
253 S: CycleCollection<'a, TickCycle, Location = Self> + DeferTick,
254 L: NoTick,
255 {
256 let next_id = self.flow_state().borrow_mut().next_cycle_id();
257 let ident = syn::Ident::new(&format!("cycle_{}", next_id), Span::call_site());
258
259 (
260 TickCycleHandle {
261 completed: false,
262 ident: ident.clone(),
263 expected_location: Location::id(self),
264 _phantom: PhantomData,
265 },
266 S::create_source(ident, self.clone()).defer_tick(),
267 )
268 }
269
270 #[expect(
271 private_bounds,
272 reason = "only Hydro collections can implement ReceiverComplete"
273 )]
274 pub fn cycle_with_initial<S>(&self, initial: S) -> (TickCycleHandle<'a, S>, S)
275 where
276 S: CycleCollectionWithInitial<'a, TickCycle, Location = Self>,
277 {
278 let next_id = self.flow_state().borrow_mut().next_cycle_id();
279 let ident = syn::Ident::new(&format!("cycle_{}", next_id), Span::call_site());
280
281 (
282 TickCycleHandle {
283 completed: false,
284 ident: ident.clone(),
285 expected_location: Location::id(self),
286 _phantom: PhantomData,
287 },
288 S::create_source_with_initial(ident, initial, self.clone()),
290 )
291 }
292}