1use std::any::type_name;
2use std::cell::RefCell;
3use std::collections::HashSet;
4use std::marker::PhantomData;
5use std::rc::{Rc, Weak};
6
7use slotmap::{SecondaryMap, SlotMap};
8
9#[cfg(feature = "build")]
10use super::compiled::CompiledFlow;
11#[cfg(feature = "build")]
12use super::deploy::{DeployFlow, DeployResult};
13#[cfg(feature = "build")]
14use super::deploy_provider::{
15 ClusterSpec, Deploy, ExternalSpec, IntoProcessSpec, SupportsMemberId,
16};
17#[cfg(feature = "build")]
18use super::ir::HydroIrOpMetadata;
19use super::ir::{HydroNode, HydroRoot};
20use crate::location::{Cluster, External, LocationKey, LocationType, Process};
21
22pub enum Sidecar {
25 Simple {
27 location_key: LocationKey,
28 future_expr: Box<syn::Expr>,
29 },
30 Bidi {
34 location_key: LocationKey,
35 sidecar_id: SidecarId,
36 sidecar_closure: Box<syn::Expr>,
37 },
38}
39#[cfg(feature = "sim")]
40#[cfg(stageleft_runtime)]
41use crate::sim::flow::SimFlow;
42use crate::staging_util::Invariant;
43
44#[stageleft::export(ExternalPortId, CycleId, ClockId, SidecarId, StmtId, HandoffId)]
45crate::newtype_counter! {
46 pub struct ExternalPortId(usize);
48
49 pub struct CycleId(usize);
51
52 pub struct ClockId(usize);
54
55 pub struct SidecarId(usize);
57
58 pub struct StmtId(usize);
60
61 pub struct HandoffId(usize);
63}
64
65impl CycleId {
66 #[cfg(feature = "build")]
67 pub(crate) fn as_ident(&self) -> syn::Ident {
68 syn::Ident::new(&format!("cycle_{}", self), proc_macro2::Span::call_site())
69 }
70}
71
72impl SidecarId {
73 pub fn idents(&self) -> (syn::Ident, syn::Ident) {
75 let span = proc_macro2::Span::call_site();
76 (
77 syn::Ident::new(&format!("__hydro_sidecar_{}_stream", self), span),
78 syn::Ident::new(&format!("__hydro_sidecar_{}_sink", self), span),
79 )
80 }
81}
82
83pub(crate) type FlowState = Rc<RefCell<FlowStateInner>>;
84
85pub(crate) struct FlowStateInner {
86 roots: Option<Vec<HydroRoot>>,
90
91 next_external_port: crate::Counter<ExternalPortId>,
93
94 next_cycle_id: crate::Counter<CycleId>,
96
97 next_clock_id: crate::Counter<ClockId>,
99
100 next_sidecar_id: crate::Counter<SidecarId>,
102
103 next_sim_hook_id: usize,
106
107 pub sidecars: Vec<Sidecar>,
110
111 pub(crate) live_collection_nodes: Vec<Weak<RefCell<HydroNode>>>,
117
118 pub(crate) clusters_reading_self_id: HashSet<LocationKey>,
120}
121
122impl FlowStateInner {
123 pub fn next_external_port(&mut self) -> ExternalPortId {
124 self.next_external_port.get_and_increment()
125 }
126
127 pub fn next_cycle_id(&mut self) -> CycleId {
128 self.next_cycle_id.get_and_increment()
129 }
130
131 pub fn next_clock_id(&mut self) -> ClockId {
132 self.next_clock_id.get_and_increment()
133 }
134
135 pub fn next_sidecar_id(&mut self) -> SidecarId {
136 self.next_sidecar_id.get_and_increment()
137 }
138
139 pub fn next_sim_hook_id(&mut self) -> usize {
140 let id = self.next_sim_hook_id;
141 self.next_sim_hook_id += 1;
142 id
143 }
144
145 pub fn push_root(&mut self, root: HydroRoot) {
146 self.roots
147 .as_mut()
148 .expect("Attempted to add a root to a flow that has already been finalized. No roots can be added after the flow has been compiled.")
149 .push(root);
150 }
151
152 pub fn try_push_root(&mut self, root: HydroRoot) {
153 if let Some(roots) = self.roots.as_mut() {
154 roots.push(root);
155 }
156 }
157}
158
159pub struct FlowBuilder<'a> {
160 flow_state: FlowState,
162
163 locations: SlotMap<LocationKey, LocationType>,
165 location_names: SecondaryMap<LocationKey, String>,
167 cluster_id_types: SecondaryMap<LocationKey, syn::Type>,
170 #[cfg(feature = "sim")]
173 location_version: SecondaryMap<LocationKey, u32>,
174 #[cfg(feature = "sim")]
178 location_version_group_root: SecondaryMap<LocationKey, LocationKey>,
179
180 #[cfg_attr(
182 not(feature = "build"),
183 expect(dead_code, reason = "unused without build")
184 )]
185 flow_name: String,
186
187 finalized: bool,
190
191 _phantom: Invariant<'a>,
196}
197
198impl Drop for FlowBuilder<'_> {
199 fn drop(&mut self) {
200 assert!(
201 self.finalized || std::thread::panicking(),
202 "Dropped FlowBuilder without finalizing, you may have forgotten to call `with_default_optimize`, `optimize_with`, or `finalize`."
203 );
204 }
205}
206
207#[expect(missing_docs, reason = "TODO")]
208impl<'a> FlowBuilder<'a> {
209 #[expect(
211 clippy::new_without_default,
212 reason = "call `new` explicitly, not `default`"
213 )]
214 pub fn new() -> Self {
215 let mut name = std::env::var("CARGO_PKG_NAME").unwrap_or_else(|_| "unknown".to_owned());
216 if let Ok(bin_path) = std::env::current_exe()
217 && let Some(bin_name) = bin_path.file_stem()
218 {
219 name = format!("{}/{}", name, bin_name.display());
220 }
221 Self::with_name(name)
222 }
223
224 pub fn with_name(name: impl Into<String>) -> Self {
226 Self {
227 flow_state: Rc::new(RefCell::new(FlowStateInner {
228 roots: Some(vec![]),
229 next_external_port: crate::Counter::default(),
230 next_cycle_id: crate::Counter::default(),
231 next_clock_id: crate::Counter::default(),
232 next_sidecar_id: crate::Counter::default(),
233 next_sim_hook_id: 0,
234 sidecars: Vec::new(),
235 live_collection_nodes: Vec::new(),
236 clusters_reading_self_id: Default::default(),
237 })),
238 locations: SlotMap::with_key(),
239 location_names: SecondaryMap::new(),
240 cluster_id_types: SecondaryMap::new(),
241 #[cfg(feature = "sim")]
242 location_version: SecondaryMap::new(),
243 #[cfg(feature = "sim")]
244 location_version_group_root: SecondaryMap::new(),
245 flow_name: name.into(),
246 finalized: false,
247 _phantom: PhantomData,
248 }
249 }
250
251 pub(crate) fn flow_state(&self) -> &FlowState {
252 &self.flow_state
253 }
254
255 fn insert_location(&mut self, ty: LocationType, name: String) -> LocationKey {
256 let key = self.locations.insert(ty);
257 self.location_names.insert(key, name);
258 #[cfg(feature = "sim")]
259 {
260 self.location_version.insert(key, 0);
261 self.location_version_group_root.insert(key, key);
262 }
263 key
264 }
265
266 pub fn process<P>(&mut self) -> Process<'a, P> {
267 let key = self.insert_location(LocationType::Process, type_name::<P>().to_owned());
268 Process {
269 key,
270 flow_state: self.flow_state().clone(),
271 _phantom: PhantomData,
272 }
273 }
274
275 pub fn cluster<C, Id>(&mut self) -> Cluster<'a, C, Id> {
276 let key = self.insert_location(LocationType::Cluster, type_name::<C>().to_owned());
277 self.cluster_id_types
278 .insert(key, stageleft::quote_type::<Id>());
279 Cluster {
280 key,
281 flow_state: self.flow_state().clone(),
282 _phantom: PhantomData,
283 }
284 }
285
286 pub fn external<E>(&mut self) -> External<'a, E> {
287 let key = self.insert_location(LocationType::External, type_name::<E>().to_owned());
288 External {
289 key,
290 flow_state: self.flow_state().clone(),
291 _phantom: PhantomData,
292 }
293 }
294
295 pub fn sim_hook<B: crate::sim_hooks::SimHook>(&mut self) -> B {
308 let flow_state = self.flow_state.clone();
309 B::create(&mut move || flow_state.borrow_mut().next_sim_hook_id())
310 }
311
312 #[cfg(feature = "sim")]
313 pub fn next_version<C>(&mut self, cluster: &Cluster<'a, C>) -> Cluster<'a, C> {
314 let group_root = self.location_version_group_root[cluster.key];
315 let version = self
316 .location_version_group_root
317 .values()
318 .filter(|&&r| r == group_root)
319 .count() as u32;
320 let key = self.insert_location(LocationType::Cluster, type_name::<C>().to_owned());
321 self.cluster_id_types
322 .insert(key, stageleft::quote_type::<u32>());
323 self.location_version.insert(key, version);
324 self.location_version_group_root.insert(key, group_root);
325 Cluster {
326 key,
327 flow_state: self.flow_state().clone(),
328 _phantom: PhantomData,
329 }
330 }
331}
332
333#[cfg(feature = "build")]
334#[cfg_attr(docsrs, doc(cfg(feature = "build")))]
335#[expect(missing_docs, reason = "TODO")]
336impl<'a> FlowBuilder<'a> {
337 pub fn finalize(mut self) -> super::built::BuiltFlow<'a> {
338 self.finalized = true;
339
340 let mut flow_state = self.flow_state.borrow_mut();
341
342 let live_collection_nodes = std::mem::take(&mut flow_state.live_collection_nodes);
346 for node_cell in live_collection_nodes {
347 if let Some(node_cell) = node_cell.upgrade() {
348 let ir_node = node_cell.replace(HydroNode::Placeholder);
349 if !matches!(ir_node, HydroNode::Placeholder) && !ir_node.is_shared_with_others() {
350 flow_state.push_root(HydroRoot::Null {
351 input: Box::new(ir_node),
352 op_metadata: HydroIrOpMetadata::new(),
353 });
354 }
355 }
356 }
357
358 let mut ir = flow_state.roots.take().unwrap();
359 let sidecars = std::mem::take(&mut flow_state.sidecars);
360 let clusters_reading_self_id = std::mem::take(&mut flow_state.clusters_reading_self_id);
361 drop(flow_state);
362
363 super::ir::unify_atomic_ticks(&mut ir);
364
365 super::built::BuiltFlow {
366 ir,
367 locations: std::mem::take(&mut self.locations),
368 location_names: std::mem::take(&mut self.location_names),
369 cluster_id_types: std::mem::take(&mut self.cluster_id_types),
370 sidecars,
371 clusters_reading_self_id,
372 flow_name: std::mem::take(&mut self.flow_name),
373 #[cfg(feature = "sim")]
374 location_version: std::mem::take(&mut self.location_version),
375 #[cfg(feature = "sim")]
376 location_version_group_root: std::mem::take(&mut self.location_version_group_root),
377 _phantom: PhantomData,
378 }
379 }
380
381 pub fn with_default_optimize<D: Deploy<'a>>(self) -> DeployFlow<'a, D> {
382 self.finalize().with_default_optimize()
383 }
384
385 pub fn optimize_with(self, f: impl FnOnce(&mut [HydroRoot])) -> super::built::BuiltFlow<'a> {
386 self.finalize().optimize_with(f)
387 }
388
389 pub fn with_process<P, D: Deploy<'a>>(
390 self,
391 process: &Process<'_, P>,
392 spec: impl IntoProcessSpec<'a, D>,
393 ) -> DeployFlow<'a, D> {
394 self.with_default_optimize().with_process(process, spec)
395 }
396
397 pub fn with_remaining_processes<D: Deploy<'a>, S: IntoProcessSpec<'a, D> + 'a>(
398 self,
399 spec: impl Fn() -> S,
400 ) -> DeployFlow<'a, D> {
401 self.with_default_optimize().with_remaining_processes(spec)
402 }
403
404 pub fn with_external<P, D: Deploy<'a>>(
405 self,
406 process: &External<'_, P>,
407 spec: impl ExternalSpec<'a, D>,
408 ) -> DeployFlow<'a, D> {
409 self.with_default_optimize().with_external(process, spec)
410 }
411
412 pub fn with_remaining_externals<D: Deploy<'a>, S: ExternalSpec<'a, D> + 'a>(
413 self,
414 spec: impl Fn() -> S,
415 ) -> DeployFlow<'a, D> {
416 self.with_default_optimize().with_remaining_externals(spec)
417 }
418
419 pub fn with_cluster<C, Id, D: Deploy<'a> + SupportsMemberId<Id>>(
420 self,
421 cluster: &Cluster<'_, C, Id>,
422 spec: impl ClusterSpec<'a, D>,
423 ) -> DeployFlow<'a, D> {
424 self.with_default_optimize().with_cluster(cluster, spec)
425 }
426
427 pub fn with_remaining_clusters<D: Deploy<'a>, S: ClusterSpec<'a, D> + 'a>(
428 self,
429 spec: impl Fn() -> S,
430 ) -> DeployFlow<'a, D> {
431 self.with_default_optimize().with_remaining_clusters(spec)
432 }
433
434 pub fn compile<D: Deploy<'a, InstantiateEnv = ()>>(self) -> CompiledFlow<'a> {
435 self.with_default_optimize::<D>().compile()
436 }
437
438 pub fn deploy<D: Deploy<'a>>(self, env: &mut D::InstantiateEnv) -> DeployResult<'a, D> {
439 self.with_default_optimize().deploy(env)
440 }
441
442 #[cfg(feature = "sim")]
443 pub fn sim(self) -> SimFlow<'a> {
446 self.finalize().sim()
447 }
448
449 pub fn from_built<'b>(built: &super::built::BuiltFlow<'_>) -> FlowBuilder<'b> {
450 FlowBuilder {
451 flow_state: Rc::new(RefCell::new(FlowStateInner {
452 roots: None,
453 next_external_port: crate::Counter::default(),
454 next_cycle_id: crate::Counter::default(),
455 next_clock_id: crate::Counter::default(),
456 next_sidecar_id: crate::Counter::default(),
457 next_sim_hook_id: 0,
458 sidecars: Vec::new(),
459 live_collection_nodes: Vec::new(),
460 clusters_reading_self_id: Default::default(),
461 })),
462 locations: built.locations.clone(),
463 location_names: built.location_names.clone(),
464 cluster_id_types: built.cluster_id_types.clone(),
465 #[cfg(feature = "sim")]
466 location_version: built.location_version.clone(),
467 #[cfg(feature = "sim")]
468 location_version_group_root: built.location_version_group_root.clone(),
469 flow_name: built.flow_name.clone(),
470 finalized: false,
471 _phantom: PhantomData,
472 }
473 }
474
475 #[doc(hidden)] pub fn replace_ir(&mut self, roots: Vec<HydroRoot>) {
477 self.flow_state.borrow_mut().roots = Some(roots);
478 }
479
480 #[doc(hidden)] pub fn next_clock_id(&mut self) -> ClockId {
482 self.flow_state.borrow_mut().next_clock_id()
483 }
484
485 #[doc(hidden)] pub fn next_cycle_id(&mut self) -> CycleId {
487 self.flow_state.borrow_mut().next_cycle_id()
488 }
489}