Skip to content

Commit d5a7dae

Browse files
authored
feat: Create Module/FunctionBuilders from existing Hugrs (#2359)
So we can use the builder machinery to make new definitions on an existing hugr.
1 parent 9a89dd4 commit d5a7dae

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

hugr-core/src/builder/dataflow.rs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -259,6 +259,31 @@ impl FunctionBuilder<Hugr> {
259259
}
260260
}
261261

262+
impl<B: AsMut<Hugr> + AsRef<Hugr>> FunctionBuilder<B> {
263+
/// Initialize a new function definition on the root module of an existing HUGR.
264+
///
265+
/// The HUGR's entrypoint will **not** be modified.
266+
///
267+
/// # Errors
268+
///
269+
/// Error in adding DFG child nodes.
270+
pub fn with_hugr(
271+
mut hugr: B,
272+
name: impl Into<String>,
273+
signature: impl Into<PolyFuncType>,
274+
) -> Result<Self, BuildError> {
275+
let signature: PolyFuncType = signature.into();
276+
let body = signature.body().clone();
277+
let op = ops::FuncDefn::new(name, signature);
278+
279+
let module = hugr.as_ref().module_root();
280+
let func = hugr.as_mut().add_node_with_parent(module, op);
281+
282+
let db = DFGBuilder::create_with_io(hugr, func, body)?;
283+
Ok(Self::from_dfg_builder(db))
284+
}
285+
}
286+
262287
impl<B: AsMut<Hugr> + AsRef<Hugr>, T> Container for DFGWrapper<B, T> {
263288
#[inline]
264289
fn container_node(&self) -> Node {

hugr-core/src/builder/module.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,12 @@ impl HugrBuilder for ModuleBuilder<Hugr> {
5151
}
5252

5353
impl<T: AsMut<Hugr> + AsRef<Hugr>> ModuleBuilder<T> {
54+
/// Continue building a module from an existing hugr.
55+
#[must_use]
56+
pub fn with_hugr(hugr: T) -> Self {
57+
ModuleBuilder(hugr)
58+
}
59+
5460
/// Replace a [`ops::FuncDecl`] with [`ops::FuncDefn`] and return a builder for
5561
/// the defining graph.
5662
///
@@ -229,4 +235,19 @@ mod test {
229235
assert_matches!(build_result, Ok(_));
230236
Ok(())
231237
}
238+
239+
#[test]
240+
fn builder_from_existing() -> Result<(), BuildError> {
241+
let hugr = Hugr::new();
242+
243+
let fn_builder = FunctionBuilder::with_hugr(hugr, "main", Signature::new_endo(vec![]))?;
244+
let mut hugr = fn_builder.finish_hugr()?;
245+
246+
let mut module_builder = ModuleBuilder::with_hugr(&mut hugr);
247+
module_builder.declare("other", Signature::new_endo(vec![]).into())?;
248+
249+
hugr.validate()?;
250+
251+
Ok(())
252+
}
232253
}

0 commit comments

Comments
 (0)