Skip to main content

hydro_lang/compile/
built.rs

1use std::collections::HashSet;
2use std::marker::PhantomData;
3
4use dfir_lang::graph::{
5    DfirGraph, FlatGraphBuilderOutput, PartitionError, eliminate_extra_unions_tees, partition_graph,
6};
7use slotmap::{SecondaryMap, SlotMap};
8
9use super::compiled::CompiledFlow;
10use super::deploy::{DeployFlow, DeployResult};
11use super::deploy_provider::{
12    ClusterSpec, Deploy, ExternalSpec, IntoProcessSpec, SupportsMemberId,
13};
14use super::ir::{HydroRoot, emit};
15use crate::location::{Cluster, External, LocationKey, LocationType, Process};
16#[cfg(stageleft_runtime)]
17#[cfg(feature = "sim")]
18use crate::sim::{flow::SimFlow, graph::SimNode};
19use crate::staging_util::Invariant;
20#[cfg(stageleft_runtime)]
21#[cfg(feature = "viz")]
22use crate::viz::api::GraphApi;
23
24pub struct BuiltFlow<'a> {
25    pub(super) ir: Vec<HydroRoot>,
26    pub(super) locations: SlotMap<LocationKey, LocationType>,
27    pub(super) location_names: SecondaryMap<LocationKey, String>,
28    pub(super) cluster_id_types: SecondaryMap<LocationKey, syn::Type>,
29
30    /// Compile-time sidecar directives extracted from the flow state.
31    pub(super) sidecars: Vec<super::builder::Sidecar>,
32
33    /// Clusters whose code reads their own member ID.
34    pub(super) clusters_reading_self_id: HashSet<LocationKey>,
35
36    /// Application name used in telemetry.
37    pub(super) flow_name: String,
38
39    /// The program version each location belongs to (every location has an entry; 0 unless it is a
40    /// `next_version` successor).
41    #[cfg(feature = "sim")]
42    pub(super) location_version: SecondaryMap<LocationKey, u32>,
43
44    /// Maps from a given location to Version 0 of that location (or itself it is already v0).
45    /// [`Cluster::next_version`](crate::location::Cluster::next_version)).
46    #[cfg(feature = "sim")]
47    pub(super) location_version_group_root: SecondaryMap<LocationKey, LocationKey>,
48
49    pub(super) _phantom: Invariant<'a>,
50}
51
52/// Builds the DFIR graph for each location.
53///
54/// Each location's graph is partitioned into subgraphs. Partitioning can fail (e.g. an
55/// intra-tick cycle), so the result is stored per-location as a [`Result`]:
56/// - `Ok(partitioned_graph)` on success.
57/// - `Err(PartitionError)` on failure, which still carries the (renderable) flat graph
58///   plus the diagnostic. This lets callers such as [`preview_compile`] obtain a meta
59///   graph to *diagnose* the failure instead of panicking with the information discarded.
60///
61/// [`preview_compile`]: super::deploy::DeployFlow::preview_compile
62pub(crate) fn build_inner(
63    ir: &mut Vec<HydroRoot>,
64) -> SecondaryMap<LocationKey, Result<DfirGraph, PartitionError>> {
65    emit(ir)
66        .into_iter()
67        .map(|(k, v)| {
68            let FlatGraphBuilderOutput { mut flat_graph, .. } =
69                v.build().expect("Failed to build DFIR flat graph.");
70            eliminate_extra_unions_tees(&mut flat_graph);
71            (k, partition_graph(flat_graph))
72        })
73        .collect()
74}
75
76impl<'a> BuiltFlow<'a> {
77    /// Returns all [`HydroRoot`]s in the IR.
78    pub fn ir(&self) -> &[HydroRoot] {
79        &self.ir
80    }
81
82    /// Serialize the IR as JSON.
83    #[cfg(feature = "viz")]
84    pub fn ir_json(&self) -> Result<String, serde_json::Error> {
85        super::ir::serialize_dedup_shared(|| serde_json::to_string_pretty(&self.ir))
86    }
87
88    /// Returns all raw location ID -> location name mappings.
89    pub fn location_names(&self) -> &SecondaryMap<LocationKey, String> {
90        &self.location_names
91    }
92
93    /// Get a `GraphApi` instance for this built flow
94    #[cfg(stageleft_runtime)]
95    #[cfg(feature = "viz")]
96    pub fn graph_api(&self) -> GraphApi<'_> {
97        GraphApi::new(&self.ir, self.location_names())
98    }
99
100    /// Render graph to string in the given format.
101    #[cfg(feature = "viz")]
102    pub fn render_graph(
103        &self,
104        format: crate::viz::config::GraphType,
105        use_short_labels: bool,
106        show_metadata: bool,
107    ) -> String {
108        self.graph_api()
109            .render(format, use_short_labels, show_metadata)
110    }
111
112    /// Write graph to file.
113    #[cfg(feature = "viz")]
114    pub fn write_graph_to_file(
115        &self,
116        format: crate::viz::config::GraphType,
117        filename: &str,
118        use_short_labels: bool,
119        show_metadata: bool,
120    ) -> Result<(), Box<dyn std::error::Error>> {
121        self.graph_api()
122            .write_to_file(format, filename, use_short_labels, show_metadata)
123    }
124
125    /// Generate graph based on CLI config. Returns Some(path) if written.
126    #[cfg(feature = "viz")]
127    pub fn generate_graph(
128        &self,
129        config: &crate::viz::config::GraphConfig,
130    ) -> Result<Option<String>, Box<dyn std::error::Error>> {
131        self.graph_api().generate_graph(config)
132    }
133
134    pub fn optimize_with(mut self, f: impl FnOnce(&mut [HydroRoot])) -> Self {
135        f(&mut self.ir);
136        self
137    }
138
139    pub fn with_default_optimize<D: Deploy<'a>>(self) -> DeployFlow<'a, D> {
140        self.into_deploy()
141    }
142
143    #[cfg(feature = "sim")]
144    /// Creates a simulation for this builder, which can be used to run deterministic simulations
145    /// of the Hydro program.
146    pub fn sim(self) -> SimFlow<'a> {
147        use std::cell::RefCell;
148        use std::rc::Rc;
149
150        use slotmap::SparseSecondaryMap;
151
152        use crate::sim::graph::SimNodePort;
153
154        let shared_port_counter = Rc::new(RefCell::new(crate::Counter::<SimNodePort>::default()));
155
156        let mut processes = SparseSecondaryMap::new();
157        let mut clusters = SparseSecondaryMap::new();
158        let externals = SparseSecondaryMap::new();
159
160        for (key, loc) in self.locations.iter() {
161            match loc {
162                LocationType::Process => {
163                    processes.insert(
164                        key,
165                        SimNode {
166                            shared_port_counter: shared_port_counter.clone(),
167                        },
168                    );
169                }
170                LocationType::Cluster => {
171                    clusters.insert(
172                        key,
173                        SimNode {
174                            shared_port_counter: shared_port_counter.clone(),
175                        },
176                    );
177                }
178                LocationType::External => {
179                    panic!("Sim cannot have externals");
180                }
181            }
182        }
183
184        SimFlow {
185            ir: self.ir,
186            processes,
187            clusters,
188            externals,
189            cluster_max_sizes: SparseSecondaryMap::new(),
190            externals_port_registry: Default::default(),
191            location_version: self.location_version,
192            location_version_group_root: self.location_version_group_root,
193            test_safety_only: false,
194            skip_consistency_assertions: false,
195            unit_test_fuzz_iterations: crate::sim::flow::DEFAULT_UNIT_FUZZ_ITERATIONS,
196            fuzz_max_len: crate::sim::flow::DEFAULT_FUZZ_MAX_LEN,
197            retries_depth: None,
198            _phantom: PhantomData,
199        }
200    }
201
202    pub fn into_deploy<D: Deploy<'a>>(self) -> DeployFlow<'a, D> {
203        let (processes, clusters, externals) = Default::default();
204        DeployFlow {
205            ir: self.ir,
206            locations: self.locations,
207            location_names: self.location_names,
208            cluster_id_types: self.cluster_id_types,
209            processes,
210            clusters,
211            externals,
212            sidecars: self.sidecars,
213            clusters_reading_self_id: self.clusters_reading_self_id,
214            as_code_options: Default::default(),
215            flow_name: self.flow_name,
216            _phantom: PhantomData,
217        }
218    }
219
220    pub fn with_process<P, D: Deploy<'a>>(
221        self,
222        process: &Process<'_, P>,
223        spec: impl IntoProcessSpec<'a, D>,
224    ) -> DeployFlow<'a, D> {
225        self.into_deploy().with_process(process, spec)
226    }
227
228    pub fn with_remaining_processes<D: Deploy<'a>, S: IntoProcessSpec<'a, D> + 'a>(
229        self,
230        spec: impl Fn() -> S,
231    ) -> DeployFlow<'a, D> {
232        self.into_deploy().with_remaining_processes(spec)
233    }
234
235    pub fn with_external<P, D: Deploy<'a>>(
236        self,
237        process: &External<'_, P>,
238        spec: impl ExternalSpec<'a, D>,
239    ) -> DeployFlow<'a, D> {
240        self.into_deploy().with_external(process, spec)
241    }
242
243    pub fn with_remaining_externals<D: Deploy<'a>, S: ExternalSpec<'a, D> + 'a>(
244        self,
245        spec: impl Fn() -> S,
246    ) -> DeployFlow<'a, D> {
247        self.into_deploy().with_remaining_externals(spec)
248    }
249
250    pub fn with_cluster<C, Id, D: Deploy<'a> + SupportsMemberId<Id>>(
251        self,
252        cluster: &Cluster<'_, C, Id>,
253        spec: impl ClusterSpec<'a, D>,
254    ) -> DeployFlow<'a, D> {
255        self.into_deploy().with_cluster(cluster, spec)
256    }
257
258    pub fn with_remaining_clusters<D: Deploy<'a>, S: ClusterSpec<'a, D> + 'a>(
259        self,
260        spec: impl Fn() -> S,
261    ) -> DeployFlow<'a, D> {
262        self.into_deploy().with_remaining_clusters(spec)
263    }
264
265    pub fn compile<D: Deploy<'a, InstantiateEnv = ()>>(self) -> CompiledFlow<'a> {
266        self.into_deploy::<D>().compile()
267    }
268
269    pub fn deploy<D: Deploy<'a>>(self, env: &mut D::InstantiateEnv) -> DeployResult<'a, D> {
270        self.into_deploy::<D>().deploy(env)
271    }
272}