File tree Expand file tree Collapse file tree 2 files changed +46
-0
lines changed Expand file tree Collapse file tree 2 files changed +46
-0
lines changed Original file line number Diff line number Diff 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+
262287impl < B : AsMut < Hugr > + AsRef < Hugr > , T > Container for DFGWrapper < B , T > {
263288 #[ inline]
264289 fn container_node ( & self ) -> Node {
Original file line number Diff line number Diff line change @@ -51,6 +51,12 @@ impl HugrBuilder for ModuleBuilder<Hugr> {
5151}
5252
5353impl < 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}
You can’t perform that action at this time.
0 commit comments