1use std::cell::RefCell;
4use std::collections::{HashMap, HashSet};
5use std::panic::RefUnwindSafe;
6use std::rc::Rc;
7
8use dfir_lang::graph::{DfirGraph, FlatGraphBuilder, FlatGraphBuilderOutput};
9use libloading::Library;
10use slotmap::SparseSecondaryMap;
11
12use super::builder::SimBuilder;
13use super::compiled::{CompiledSim, CompiledSimInstance};
14use super::graph::{SimDeploy, SimExternal, SimNode, compile_sim, create_sim_graph_trybuild};
15use crate::compile::ir::HydroRoot;
16use crate::location::LocationKey;
17use crate::location::dynamic::LocationId;
18use crate::prelude::Cluster;
19use crate::sim::graph::SimExternalPortRegistry;
20use crate::staging_util::Invariant;
21
22pub struct SimFlow<'a> {
24 pub(crate) ir: Vec<HydroRoot>,
25
26 pub(crate) processes: SparseSecondaryMap<LocationKey, SimNode>,
28 pub(crate) clusters: SparseSecondaryMap<LocationKey, SimNode>,
30 pub(crate) externals: SparseSecondaryMap<LocationKey, SimExternal>,
32
33 pub(crate) cluster_max_sizes: SparseSecondaryMap<LocationKey, usize>,
35 pub(crate) externals_port_registry: Rc<RefCell<SimExternalPortRegistry>>,
37
38 pub(crate) test_safety_only: bool,
40
41 pub(crate) _phantom: Invariant<'a>,
42}
43
44impl<'a> SimFlow<'a> {
45 pub fn with_cluster_size<C>(mut self, cluster: &Cluster<'a, C>, max_size: usize) -> Self {
47 self.cluster_max_sizes.insert(cluster.key, max_size);
48 self
49 }
50
51 pub fn test_safety_only(mut self) -> Self {
60 self.test_safety_only = true;
61 self
62 }
63
64 pub fn with_instance<T>(self, thunk: impl FnOnce(CompiledSimInstance) -> T) -> T {
66 self.compiled().with_instance(thunk)
67 }
68
69 pub fn fuzz(self, thunk: impl AsyncFn() + RefUnwindSafe) {
80 self.compiled().fuzz(thunk)
81 }
82
83 pub fn exhaustive(self, thunk: impl AsyncFnMut() + RefUnwindSafe) -> usize {
94 self.compiled().exhaustive(thunk)
95 }
96
97 pub fn compiled(mut self) -> CompiledSim {
99 use std::collections::BTreeMap;
100
101 use dfir_lang::graph::{eliminate_extra_unions_tees, partition_graph};
102
103 let mut sim_emit = SimBuilder {
104 process_graphs: BTreeMap::new(),
105 cluster_graphs: BTreeMap::new(),
106 process_tick_dfirs: BTreeMap::new(),
107 cluster_tick_dfirs: BTreeMap::new(),
108 extra_stmts_global: vec![],
109 extra_stmts_cluster: BTreeMap::new(),
110 next_hoff_id: 0,
111 test_safety_only: self.test_safety_only,
112 };
113
114 self.externals.insert(
116 LocationKey::FIRST,
117 SimExternal {
118 shared_inner: self.externals_port_registry.clone(),
119 },
120 );
121
122 let mut seen_tees_instantiate: HashMap<_, _> = HashMap::new();
123 let mut seen_cluster_members = HashSet::new();
124 self.ir.iter_mut().for_each(|leaf| {
125 leaf.compile_network::<SimDeploy>(
126 &mut SparseSecondaryMap::new(),
127 &mut seen_tees_instantiate,
128 &mut seen_cluster_members,
129 &self.processes,
130 &self.clusters,
131 &self.externals,
132 &mut (),
133 );
134 });
135
136 let mut seen_tees = HashMap::new();
137 let mut built_tees = HashMap::new();
138 let mut next_stmt_id = 0;
139 for leaf in &mut self.ir {
140 leaf.emit(
141 &mut sim_emit,
142 &mut seen_tees,
143 &mut built_tees,
144 &mut next_stmt_id,
145 );
146 }
147
148 fn build_graphs(
149 graphs: BTreeMap<LocationId, FlatGraphBuilder>,
150 ) -> BTreeMap<LocationId, DfirGraph> {
151 graphs
152 .into_iter()
153 .map(|(l, g)| {
154 let FlatGraphBuilderOutput { mut flat_graph, .. } =
155 g.build().expect("Failed to build DFIR flat graph.");
156 eliminate_extra_unions_tees(&mut flat_graph);
157 (
158 l,
159 partition_graph(flat_graph).expect("Failed to partition (cycle detected)."),
160 )
161 })
162 .collect()
163 }
164
165 let process_graphs = build_graphs(sim_emit.process_graphs);
166 let cluster_graphs = build_graphs(sim_emit.cluster_graphs);
167 let process_tick_graphs = build_graphs(sim_emit.process_tick_dfirs);
168 let cluster_tick_graphs = build_graphs(sim_emit.cluster_tick_dfirs);
169
170 #[expect(
171 clippy::disallowed_methods,
172 reason = "nondeterministic iteration order, fine for checks"
173 )]
174 for c in self.clusters.keys() {
175 assert!(
176 self.cluster_max_sizes.contains_key(c),
177 "Cluster {:?} missing max size; call with_cluster_size() before compiled()",
178 c
179 );
180 }
181
182 let (bin, trybuild) = create_sim_graph_trybuild(
183 process_graphs,
184 cluster_graphs,
185 self.cluster_max_sizes,
186 process_tick_graphs,
187 cluster_tick_graphs,
188 sim_emit.extra_stmts_global,
189 sim_emit.extra_stmts_cluster,
190 );
191
192 let out = compile_sim(bin, trybuild).unwrap();
193 let lib = unsafe { Library::new(&out).unwrap() };
194
195 CompiledSim {
196 _path: out,
197 lib,
198 externals_port_registry: self.externals_port_registry.take(),
199 }
200 }
201}