hugr_core/builder/
build_traits.rs

1use crate::extension::prelude::MakeTuple;
2use crate::hugr::hugrmut::InsertionResult;
3use crate::hugr::views::HugrView;
4use crate::hugr::{NodeMetadata, ValidationError};
5use crate::ops::{self, OpTag, OpTrait, OpType, Tag, TailLoop};
6use crate::utils::collect_array;
7use crate::{Extension, IncomingPort, Node, OutgoingPort};
8
9use std::iter;
10use std::sync::Arc;
11
12use super::{
13    handle::{BuildHandle, Outputs},
14    CircuitBuilder,
15};
16use super::{BuilderWiringError, FunctionBuilder};
17
18use crate::{
19    ops::handle::{ConstID, DataflowOpID, FuncID, NodeHandle},
20    types::EdgeKind,
21};
22
23use crate::extension::ExtensionRegistry;
24use crate::types::{PolyFuncType, Signature, Type, TypeArg, TypeRow};
25
26use itertools::Itertools;
27
28use super::{
29    cfg::CFGBuilder, conditional::ConditionalBuilder, dataflow::DFGBuilder,
30    tail_loop::TailLoopBuilder, BuildError, Wire,
31};
32
33use crate::Hugr;
34
35use crate::hugr::HugrMut;
36
37/// Trait for HUGR container builders.
38/// Containers are nodes that are parents of sibling graphs.
39/// Implementations of this trait allow the child sibling graph to be added to
40/// the HUGR.
41pub trait Container {
42    /// The container node.
43    fn container_node(&self) -> Node;
44    /// The underlying [`Hugr`] being built
45    fn hugr_mut(&mut self) -> &mut Hugr;
46    /// Immutable reference to HUGR being built
47    fn hugr(&self) -> &Hugr;
48    /// Add an [`OpType`] as the final child of the container.
49    ///
50    /// Adds the extensions required by the op to the HUGR, if they are not already present.
51    fn add_child_node(&mut self, node: impl Into<OpType>) -> Node {
52        let node: OpType = node.into();
53
54        // Add the extension the operation is defined in to the HUGR.
55        let used_extensions = node
56            .used_extensions()
57            .unwrap_or_else(|e| panic!("Build-time signatures should have valid extensions. {e}"));
58        self.use_extensions(used_extensions);
59
60        let parent = self.container_node();
61        self.hugr_mut().add_node_with_parent(parent, node)
62    }
63
64    /// Adds a non-dataflow edge between two nodes. The kind is given by the operation's [`other_inputs`] or  [`other_outputs`]
65    ///
66    /// [`other_inputs`]: crate::ops::OpTrait::other_input
67    /// [`other_outputs`]: crate::ops::OpTrait::other_output
68    fn add_other_wire(&mut self, src: Node, dst: Node) -> Wire {
69        let (src_port, _) = self.hugr_mut().add_other_edge(src, dst);
70        Wire::new(src, src_port)
71    }
72
73    /// Add a constant value to the container and return a handle to it.
74    ///
75    /// Adds the extensions required by the op to the HUGR, if they are not already present.
76    ///
77    /// # Errors
78    ///
79    /// This function will return an error if there is an error in adding the
80    /// [`OpType::Const`] node.
81    fn add_constant(&mut self, constant: impl Into<ops::Const>) -> ConstID {
82        self.add_child_node(constant.into()).into()
83    }
84
85    /// Add a [`ops::FuncDefn`] node and returns a builder to define the function
86    /// body graph.
87    ///
88    /// # Errors
89    ///
90    /// This function will return an error if there is an error in adding the
91    /// [`ops::FuncDefn`] node.
92    fn define_function(
93        &mut self,
94        name: impl Into<String>,
95        signature: impl Into<PolyFuncType>,
96    ) -> Result<FunctionBuilder<&mut Hugr>, BuildError> {
97        let signature: PolyFuncType = signature.into();
98        let body = signature.body().clone();
99        let f_node = self.add_child_node(ops::FuncDefn {
100            name: name.into(),
101            signature,
102        });
103
104        // Add the extensions used by the function types.
105        self.use_extensions(
106            body.used_extensions().unwrap_or_else(|e| {
107                panic!("Build-time signatures should have valid extensions. {e}")
108            }),
109        );
110
111        let db = DFGBuilder::create_with_io(self.hugr_mut(), f_node, body)?;
112        Ok(FunctionBuilder::from_dfg_builder(db))
113    }
114
115    /// Insert a HUGR as a child of the container.
116    fn add_hugr(&mut self, child: Hugr) -> InsertionResult {
117        let parent = self.container_node();
118        self.hugr_mut().insert_hugr(parent, child)
119    }
120
121    /// Insert a copy of a HUGR as a child of the container.
122    fn add_hugr_view<H: HugrView>(&mut self, child: &H) -> InsertionResult<H::Node, Node> {
123        let parent = self.container_node();
124        self.hugr_mut().insert_from_view(parent, child)
125    }
126
127    /// Add metadata to the container node.
128    fn set_metadata(&mut self, key: impl AsRef<str>, meta: impl Into<NodeMetadata>) {
129        let parent = self.container_node();
130        // Implementor's container_node() should be a valid node
131        self.hugr_mut().set_metadata(parent, key, meta);
132    }
133
134    /// Add metadata to a child node.
135    ///
136    /// Returns an error if the specified `child` is not a child of this container
137    fn set_child_metadata(
138        &mut self,
139        child: Node,
140        key: impl AsRef<str>,
141        meta: impl Into<NodeMetadata>,
142    ) {
143        self.hugr_mut().set_metadata(child, key, meta);
144    }
145
146    /// Add an extension to the set of extensions used by the hugr.
147    fn use_extension(&mut self, ext: impl Into<Arc<Extension>>) {
148        self.hugr_mut().use_extension(ext);
149    }
150
151    /// Extend the set of extensions used by the hugr with the extensions in the registry.
152    fn use_extensions<Reg>(&mut self, registry: impl IntoIterator<Item = Reg>)
153    where
154        ExtensionRegistry: Extend<Reg>,
155    {
156        self.hugr_mut().use_extensions(registry);
157    }
158}
159
160/// Types implementing this trait can be used to build complete HUGRs
161/// (with varying root node types)
162pub trait HugrBuilder: Container {
163    /// Finish building the HUGR, perform any validation checks and return it.
164    fn finish_hugr(self) -> Result<Hugr, ValidationError<Node>>;
165}
166
167/// Types implementing this trait build a container graph region by borrowing a HUGR
168pub trait SubContainer: Container {
169    /// A handle to the finished container node, typically returned when the
170    /// child graph has been finished.
171    type ContainerHandle;
172    /// Consume the container builder and return the handle, may perform some
173    /// checks before finishing.
174    fn finish_sub_container(self) -> Result<Self::ContainerHandle, BuildError>;
175}
176/// Trait for building dataflow regions of a HUGR.
177pub trait Dataflow: Container {
178    /// Return the number of inputs to the dataflow sibling graph.
179    fn num_inputs(&self) -> usize;
180    /// Return indices of input and output nodes.
181    fn io(&self) -> [Node; 2] {
182        self.hugr()
183            .children(self.container_node())
184            .take(2)
185            .collect_vec()
186            .try_into()
187            .expect("First two children should be IO")
188    }
189    /// Handle to input node.
190    fn input(&self) -> BuildHandle<DataflowOpID> {
191        (self.io()[0], self.num_inputs()).into()
192    }
193    /// Handle to output node.
194    fn output(&self) -> DataflowOpID {
195        self.io()[1].into()
196    }
197    /// Return iterator over all input Value wires.
198    fn input_wires(&self) -> Outputs {
199        self.input().outputs()
200    }
201    /// Add a dataflow [`OpType`] to the sibling graph, wiring up the `input_wires` to the
202    /// incoming ports of the resulting node.
203    ///
204    /// Adds the extensions required by the op to the HUGR, if they are not already present.
205    ///
206    /// # Errors
207    ///
208    /// Returns a [`BuildError::OperationWiring`] error if the `input_wires` cannot be connected.
209    fn add_dataflow_op(
210        &mut self,
211        nodetype: impl Into<OpType>,
212        input_wires: impl IntoIterator<Item = Wire>,
213    ) -> Result<BuildHandle<DataflowOpID>, BuildError> {
214        let outs = add_node_with_wires(self, nodetype, input_wires)?;
215
216        Ok(outs.into())
217    }
218
219    /// Insert a hugr-defined op to the sibling graph, wiring up the
220    /// `input_wires` to the incoming ports of the resulting root node.
221    ///
222    /// # Errors
223    ///
224    /// This function will return an error if there is an error when adding the
225    /// node.
226    fn add_hugr_with_wires(
227        &mut self,
228        hugr: Hugr,
229        input_wires: impl IntoIterator<Item = Wire>,
230    ) -> Result<BuildHandle<DataflowOpID>, BuildError> {
231        let optype = hugr.get_optype(hugr.entrypoint()).clone();
232        let num_outputs = optype.value_output_count();
233        let node = self.add_hugr(hugr).inserted_entrypoint;
234
235        wire_up_inputs(input_wires, node, self)
236            .map_err(|error| BuildError::OperationWiring { op: optype, error })?;
237
238        Ok((node, num_outputs).into())
239    }
240
241    /// Copy a hugr-defined op into the sibling graph, wiring up the
242    /// `input_wires` to the incoming ports of the resulting root node.
243    ///
244    /// # Errors
245    ///
246    /// This function will return an error if there is an error when adding the
247    /// node.
248    fn add_hugr_view_with_wires(
249        &mut self,
250        hugr: &impl HugrView,
251        input_wires: impl IntoIterator<Item = Wire>,
252    ) -> Result<BuildHandle<DataflowOpID>, BuildError> {
253        let node = self.add_hugr_view(hugr).inserted_entrypoint;
254        let optype = hugr.get_optype(hugr.entrypoint()).clone();
255        let num_outputs = optype.value_output_count();
256
257        wire_up_inputs(input_wires, node, self)
258            .map_err(|error| BuildError::OperationWiring { op: optype, error })?;
259
260        Ok((node, num_outputs).into())
261    }
262
263    /// Wire up the `output_wires` to the input ports of the Output node.
264    ///
265    /// # Errors
266    ///
267    /// This function will return an error if there is an error when wiring up.
268    fn set_outputs(
269        &mut self,
270        output_wires: impl IntoIterator<Item = Wire>,
271    ) -> Result<(), BuildError> {
272        let [_, out] = self.io();
273        wire_up_inputs(output_wires.into_iter().collect_vec(), out, self).map_err(|error| {
274            BuildError::OutputWiring {
275                container_op: self.hugr().get_optype(self.container_node()).clone(),
276                container_node: self.container_node(),
277                error,
278            }
279        })
280    }
281
282    /// Return an array of the input wires.
283    ///
284    /// # Panics
285    ///
286    /// Panics if the number of input Wires does not match the size of the array.
287    #[track_caller]
288    fn input_wires_arr<const N: usize>(&self) -> [Wire; N] {
289        collect_array(self.input_wires())
290    }
291
292    /// Return a builder for a [`crate::ops::DFG`] node, i.e. a nested dataflow subgraph,
293    /// given a signature describing its input and output types and extension delta,
294    /// and the input wires (which must match the input types)
295    ///
296    /// # Errors
297    ///
298    /// This function will return an error if there is an error when building
299    /// the DFG node.
300    // TODO: Should this be one function, or should there be a temporary "op" one like with the others?
301    fn dfg_builder(
302        &mut self,
303        signature: Signature,
304        input_wires: impl IntoIterator<Item = Wire>,
305    ) -> Result<DFGBuilder<&mut Hugr>, BuildError> {
306        let op = ops::DFG {
307            signature: signature.clone(),
308        };
309        let (dfg_n, _) = add_node_with_wires(self, op, input_wires)?;
310
311        DFGBuilder::create_with_io(self.hugr_mut(), dfg_n, signature)
312    }
313
314    /// Return a builder for a [`crate::ops::DFG`] node, i.e. a nested dataflow subgraph,
315    /// that is endomorphic (the output types are the same as the input types).
316    /// The `inputs` must be an iterable over pairs of the type of the input and
317    /// the corresponding wire.
318    fn dfg_builder_endo(
319        &mut self,
320        inputs: impl IntoIterator<Item = (Type, Wire)>,
321    ) -> Result<DFGBuilder<&mut Hugr>, BuildError> {
322        let (types, input_wires): (Vec<Type>, Vec<Wire>) = inputs.into_iter().unzip();
323        self.dfg_builder(Signature::new_endo(types), input_wires)
324    }
325
326    /// Return a builder for a [`crate::ops::CFG`] node,
327    /// i.e. a nested controlflow subgraph.
328    /// The `inputs` must be an iterable over pairs of the type of the input and
329    /// the corresponding wire.
330    /// The `output_types` are the types of the outputs.
331    ///
332    /// # Errors
333    ///
334    /// This function will return an error if there is an error when building
335    /// the CFG node.
336    fn cfg_builder(
337        &mut self,
338        inputs: impl IntoIterator<Item = (Type, Wire)>,
339        output_types: TypeRow,
340    ) -> Result<CFGBuilder<&mut Hugr>, BuildError> {
341        let (input_types, input_wires): (Vec<Type>, Vec<Wire>) = inputs.into_iter().unzip();
342
343        let inputs: TypeRow = input_types.into();
344
345        let (cfg_node, _) = add_node_with_wires(
346            self,
347            ops::CFG {
348                signature: Signature::new(inputs.clone(), output_types.clone()),
349            },
350            input_wires,
351        )?;
352        CFGBuilder::create(self.hugr_mut(), cfg_node, inputs, output_types)
353    }
354
355    /// Load a static constant and return the local dataflow wire for that constant.
356    /// Adds a [`OpType::LoadConstant`] node.
357    fn load_const(&mut self, cid: &ConstID) -> Wire {
358        let const_node = cid.node();
359        let nodetype = self.hugr().get_optype(const_node);
360        let op: ops::Const = nodetype
361            .clone()
362            .try_into()
363            .expect("ConstID does not refer to Const op.");
364
365        let load_n = self
366            .add_dataflow_op(
367                ops::LoadConstant {
368                    datatype: op.get_type().clone(),
369                },
370                // Constant wire from the constant value node
371                vec![Wire::new(const_node, OutgoingPort::from(0))],
372            )
373            .expect("The constant type should match the LoadConstant type.");
374
375        load_n.out_wire(0)
376    }
377
378    /// Load a static constant and return the local dataflow wire for that constant.
379    /// Adds a [`ops::Const`] and a [`ops::LoadConstant`] node.
380    fn add_load_const(&mut self, constant: impl Into<ops::Const>) -> Wire {
381        let cid = self.add_constant(constant);
382        self.load_const(&cid)
383    }
384
385    /// Load a [`ops::Value`] and return the local dataflow wire for that constant.
386    /// Adds a [`ops::Const`] and a [`ops::LoadConstant`] node.
387    fn add_load_value(&mut self, constant: impl Into<ops::Value>) -> Wire {
388        self.add_load_const(constant.into())
389    }
390
391    /// Load a static function and return the local dataflow wire for that function.
392    /// Adds a [`OpType::LoadFunction`] node.
393    ///
394    /// The `DEF` const generic is used to indicate whether the function is defined
395    /// or just declared.
396    fn load_func<const DEFINED: bool>(
397        &mut self,
398        fid: &FuncID<DEFINED>,
399        type_args: &[TypeArg],
400    ) -> Result<Wire, BuildError> {
401        let func_node = fid.node();
402        let func_op = self.hugr().get_optype(func_node);
403        let func_sig = match func_op {
404            OpType::FuncDefn(ops::FuncDefn { signature, .. })
405            | OpType::FuncDecl(ops::FuncDecl { signature, .. }) => signature.clone(),
406            _ => {
407                return Err(BuildError::UnexpectedType {
408                    node: func_node,
409                    op_desc: "FuncDecl/FuncDefn",
410                })
411            }
412        };
413
414        let load_n = self.add_dataflow_op(
415            ops::LoadFunction::try_new(func_sig, type_args)?,
416            // Static wire from the function node
417            vec![Wire::new(func_node, func_op.static_output_port().unwrap())],
418        )?;
419
420        Ok(load_n.out_wire(0))
421    }
422
423    /// Return a builder for a [`crate::ops::TailLoop`] node.
424    /// The `inputs` must be an iterable over pairs of the type of the input and
425    /// the corresponding wire.
426    /// The `output_types` are the types of the outputs.
427    ///
428    /// # Errors
429    ///
430    /// This function will return an error if there is an error when building
431    /// the [`ops::TailLoop`] node.
432    ///
433    fn tail_loop_builder(
434        &mut self,
435        just_inputs: impl IntoIterator<Item = (Type, Wire)>,
436        inputs_outputs: impl IntoIterator<Item = (Type, Wire)>,
437        just_out_types: TypeRow,
438    ) -> Result<TailLoopBuilder<&mut Hugr>, BuildError> {
439        let (input_types, mut input_wires): (Vec<Type>, Vec<Wire>) =
440            just_inputs.into_iter().unzip();
441        let (rest_types, rest_input_wires): (Vec<Type>, Vec<Wire>) =
442            inputs_outputs.into_iter().unzip();
443        input_wires.extend(rest_input_wires);
444
445        let tail_loop = ops::TailLoop {
446            just_inputs: input_types.into(),
447            just_outputs: just_out_types,
448            rest: rest_types.into(),
449        };
450        // TODO: Make input extensions a parameter
451        let (loop_node, _) = add_node_with_wires(self, tail_loop.clone(), input_wires)?;
452
453        TailLoopBuilder::create_with_io(self.hugr_mut(), loop_node, &tail_loop)
454    }
455
456    /// Return a builder for a [`crate::ops::Conditional`] node.
457    /// `sum_input` is a tuple of the type of the Sum
458    /// variants and the corresponding wire.
459    ///
460    /// The `other_inputs` must be an iterable over pairs of the type of the input and
461    /// the corresponding wire.
462    /// The `output_types` are the types of the outputs.
463    ///
464    /// # Errors
465    ///
466    /// This function will return an error if there is an error when building
467    /// the Conditional node.
468    fn conditional_builder(
469        &mut self,
470        (sum_rows, sum_wire): (impl IntoIterator<Item = TypeRow>, Wire),
471        other_inputs: impl IntoIterator<Item = (Type, Wire)>,
472        output_types: TypeRow,
473    ) -> Result<ConditionalBuilder<&mut Hugr>, BuildError> {
474        let mut input_wires = vec![sum_wire];
475        let (input_types, rest_input_wires): (Vec<Type>, Vec<Wire>) =
476            other_inputs.into_iter().unzip();
477
478        input_wires.extend(rest_input_wires);
479        let inputs: TypeRow = input_types.into();
480        let sum_rows: Vec<_> = sum_rows.into_iter().collect();
481        let n_cases = sum_rows.len();
482        let n_out_wires = output_types.len();
483
484        let conditional_id = self.add_dataflow_op(
485            ops::Conditional {
486                sum_rows,
487                other_inputs: inputs,
488                outputs: output_types,
489            },
490            input_wires,
491        )?;
492
493        Ok(ConditionalBuilder {
494            base: self.hugr_mut(),
495            conditional_node: conditional_id.node(),
496            n_out_wires,
497            case_nodes: vec![None; n_cases],
498        })
499    }
500
501    /// Add an order edge from `before` to `after`. Assumes any additional edges
502    /// to both nodes will be Order kind.
503    fn set_order(&mut self, before: &impl NodeHandle, after: &impl NodeHandle) {
504        self.add_other_wire(before.node(), after.node());
505    }
506
507    /// Get the type of a Value [`Wire`]. If not valid port or of Value kind, returns None.
508    fn get_wire_type(&self, wire: Wire) -> Result<Type, BuildError> {
509        let kind = self.hugr().get_optype(wire.node()).port_kind(wire.source());
510
511        if let Some(EdgeKind::Value(typ)) = kind {
512            Ok(typ)
513        } else {
514            Err(BuildError::WireNotFound(wire))
515        }
516    }
517
518    /// Add a [`MakeTuple`] node and wire in the `values` Wires,
519    /// returning the Wire corresponding to the tuple.
520    ///
521    /// # Errors
522    ///
523    /// This function will return an error if there is an error adding the
524    /// [`MakeTuple`] node.
525    fn make_tuple(&mut self, values: impl IntoIterator<Item = Wire>) -> Result<Wire, BuildError> {
526        let values = values.into_iter().collect_vec();
527        let types: Result<Vec<Type>, _> = values
528            .iter()
529            .map(|&wire| self.get_wire_type(wire))
530            .collect();
531        let types = types?.into();
532        let make_op = self.add_dataflow_op(MakeTuple(types), values)?;
533        Ok(make_op.out_wire(0))
534    }
535
536    /// Add a [`Tag`] node and wire in the `value` Wire,
537    /// to make a value with Sum type, with `tag` and possible types described
538    /// by `variants`.
539    /// Returns the Wire corresponding to the Sum value.
540    ///
541    /// # Errors
542    ///
543    /// This function will return an error if there is an error adding the
544    /// Tag node.
545    fn make_sum(
546        &mut self,
547        tag: usize,
548        variants: impl IntoIterator<Item = TypeRow>,
549        values: impl IntoIterator<Item = Wire>,
550    ) -> Result<Wire, BuildError> {
551        let make_op = self.add_dataflow_op(
552            Tag {
553                tag,
554                variants: variants.into_iter().collect_vec(),
555            },
556            values.into_iter().collect_vec(),
557        )?;
558        Ok(make_op.out_wire(0))
559    }
560
561    /// Use the wires in `values` to return a wire corresponding to the
562    /// "Continue" variant of a [`ops::TailLoop`] with `loop_signature`.
563    ///
564    /// Packs the values in to a tuple and tags appropriately to generate a
565    /// value of Sum type.
566    ///
567    /// # Errors
568    ///
569    /// This function will return an error if there is an error in adding the nodes.
570    fn make_continue(
571        &mut self,
572        tail_loop: ops::TailLoop,
573        values: impl IntoIterator<Item = Wire>,
574    ) -> Result<Wire, BuildError> {
575        self.make_sum(
576            TailLoop::CONTINUE_TAG,
577            [tail_loop.just_inputs, tail_loop.just_outputs],
578            values,
579        )
580    }
581
582    /// Use the wires in `values` to return a wire corresponding to the
583    /// "Break" variant of a [`ops::TailLoop`] with `loop_signature`.
584    ///
585    /// Packs the values in to a tuple and tags appropriately to generate a
586    /// value of Sum type.
587    ///
588    /// # Errors
589    ///
590    /// This function will return an error if there is an error in adding the nodes.
591    fn make_break(
592        &mut self,
593        loop_op: ops::TailLoop,
594        values: impl IntoIterator<Item = Wire>,
595    ) -> Result<Wire, BuildError> {
596        self.make_sum(
597            TailLoop::BREAK_TAG,
598            [loop_op.just_inputs, loop_op.just_outputs],
599            values,
600        )
601    }
602
603    /// Add a [`ops::Call`] node, calling `function`, with inputs
604    /// specified by `input_wires`. Returns a handle to the corresponding Call node.
605    ///
606    /// # Errors
607    ///
608    /// This function will return an error if there is an error adding the Call
609    /// node, or if `function` does not refer to a [`ops::FuncDecl`] or
610    /// [`ops::FuncDefn`] node.
611    fn call<const DEFINED: bool>(
612        &mut self,
613        function: &FuncID<DEFINED>,
614        type_args: &[TypeArg],
615        input_wires: impl IntoIterator<Item = Wire>,
616    ) -> Result<BuildHandle<DataflowOpID>, BuildError> {
617        let hugr = self.hugr();
618        let def_op = hugr.get_optype(function.node());
619        let type_scheme = match def_op {
620            OpType::FuncDefn(ops::FuncDefn { signature, .. })
621            | OpType::FuncDecl(ops::FuncDecl { signature, .. }) => signature.clone(),
622            _ => {
623                return Err(BuildError::UnexpectedType {
624                    node: function.node(),
625                    op_desc: "FuncDecl/FuncDefn",
626                })
627            }
628        };
629        let op: OpType = ops::Call::try_new(type_scheme, type_args)?.into();
630        let const_in_port = op.static_input_port().unwrap();
631        let op_id = self.add_dataflow_op(op, input_wires)?;
632        let src_port = self.hugr_mut().num_outputs(function.node()) - 1;
633
634        self.hugr_mut()
635            .connect(function.node(), src_port, op_id.node(), const_in_port);
636        Ok(op_id)
637    }
638
639    /// For the vector of `wires`, produce a `CircuitBuilder` where ops can be
640    /// added using indices in to the vector.
641    fn as_circuit(&mut self, wires: impl IntoIterator<Item = Wire>) -> CircuitBuilder<Self> {
642        CircuitBuilder::new(wires, self)
643    }
644
645    /// Add a [Barrier] to a set of wires and return them in the same order.
646    ///
647    /// [Barrier]: crate::extension::prelude::Barrier
648    ///
649    /// # Errors
650    ///
651    /// This function will return an error if there is an error adding the Barrier node
652    /// or retrieving the type of the incoming wires.
653    fn add_barrier(
654        &mut self,
655        wires: impl IntoIterator<Item = Wire>,
656    ) -> Result<BuildHandle<DataflowOpID>, BuildError> {
657        let wires = wires.into_iter().collect_vec();
658        let types: Result<Vec<Type>, _> =
659            wires.iter().map(|&wire| self.get_wire_type(wire)).collect();
660        let types = types?;
661        let barrier_op =
662            self.add_dataflow_op(crate::extension::prelude::Barrier::new(types), wires)?;
663        Ok(barrier_op)
664    }
665}
666
667/// Add a node to the graph, wiring up the `inputs` to the input ports of the resulting node.
668///
669/// Adds the extensions required by the op to the HUGR, if they are not already present.
670///
671/// # Errors
672///
673/// Returns a [`BuildError::OperationWiring`] if any of the connections produces an
674/// invalid edge.
675fn add_node_with_wires<T: Dataflow + ?Sized>(
676    data_builder: &mut T,
677    nodetype: impl Into<OpType>,
678    inputs: impl IntoIterator<Item = Wire>,
679) -> Result<(Node, usize), BuildError> {
680    let op: OpType = nodetype.into();
681    let num_outputs = op.value_output_count();
682    let op_node = data_builder.add_child_node(op.clone());
683
684    wire_up_inputs(inputs, op_node, data_builder)
685        .map_err(|error| BuildError::OperationWiring { op, error })?;
686
687    Ok((op_node, num_outputs))
688}
689
690/// Connect each of the `inputs` wires sequentially to the input ports of
691/// `op_node`.
692///
693/// # Errors
694///
695/// Returns a [`BuilderWiringError`] if any of the connections produces an
696/// invalid edge.
697fn wire_up_inputs<T: Dataflow + ?Sized>(
698    inputs: impl IntoIterator<Item = Wire>,
699    op_node: Node,
700    data_builder: &mut T,
701) -> Result<(), BuilderWiringError> {
702    for (dst_port, wire) in inputs.into_iter().enumerate() {
703        wire_up(data_builder, wire.node(), wire.source(), op_node, dst_port)?;
704    }
705    Ok(())
706}
707
708/// Add edge from src to dst.
709///
710/// # Errors
711///
712/// Returns a [`BuilderWiringError`] if the edge is invalid.
713fn wire_up<T: Dataflow + ?Sized>(
714    data_builder: &mut T,
715    src: Node,
716    src_port: impl Into<OutgoingPort>,
717    dst: Node,
718    dst_port: impl Into<IncomingPort>,
719) -> Result<bool, BuilderWiringError> {
720    let src_port = src_port.into();
721    let dst_port = dst_port.into();
722    let base = data_builder.hugr_mut();
723
724    let src_parent = base.get_parent(src);
725    let src_parent_parent = src_parent.and_then(|src| base.get_parent(src));
726    let dst_parent = base.get_parent(dst);
727    let local_source = src_parent == dst_parent;
728    if let EdgeKind::Value(typ) = base.get_optype(src).port_kind(src_port).unwrap() {
729        if !local_source {
730            // Non-local value sources require a state edge to an ancestor of dst
731            if !typ.copyable() {
732                return Err(BuilderWiringError::NonCopyableIntergraph {
733                    src,
734                    src_offset: src_port.into(),
735                    dst,
736                    dst_offset: dst_port.into(),
737                    typ,
738                });
739            }
740
741            let src_parent = src_parent.expect("Node has no parent");
742            let Some(src_sibling) = iter::successors(dst_parent, |&p| base.get_parent(p))
743                .tuple_windows()
744                .find_map(|(ancestor, ancestor_parent)| {
745                    (ancestor_parent == src_parent ||
746                        // Dom edge - in CFGs
747                        Some(ancestor_parent) == src_parent_parent)
748                        .then_some(ancestor)
749                })
750            else {
751                return Err(BuilderWiringError::NoRelationIntergraph {
752                    src,
753                    src_offset: src_port.into(),
754                    dst,
755                    dst_offset: dst_port.into(),
756                });
757            };
758
759            if !OpTag::ControlFlowChild.is_superset(base.get_optype(src).tag())
760                && !OpTag::ControlFlowChild.is_superset(base.get_optype(src_sibling).tag())
761            {
762                // Add a state order constraint unless one of the nodes is a CFG BasicBlock
763                base.add_other_edge(src, src_sibling);
764            }
765        } else if !typ.copyable() & base.linked_ports(src, src_port).next().is_some() {
766            // Don't copy linear edges.
767            return Err(BuilderWiringError::NoCopyLinear {
768                typ,
769                src,
770                src_offset: src_port.into(),
771            });
772        }
773    }
774
775    data_builder
776        .hugr_mut()
777        .connect(src, src_port, dst, dst_port);
778    Ok(local_source
779        && matches!(
780            data_builder
781                .hugr_mut()
782                .get_optype(dst)
783                .port_kind(dst_port)
784                .unwrap(),
785            EdgeKind::Value(_)
786        ))
787}
788
789/// Trait implemented by builders of Dataflow Hugrs
790pub trait DataflowHugr: HugrBuilder + Dataflow {
791    /// Set outputs of dataflow HUGR and return validated HUGR
792    /// # Errors
793    ///
794    /// * if there is an error when setting outputs
795    /// * if the Hugr does not validate
796    fn finish_hugr_with_outputs(
797        mut self,
798        outputs: impl IntoIterator<Item = Wire>,
799    ) -> Result<Hugr, BuildError>
800    where
801        Self: Sized,
802    {
803        self.set_outputs(outputs)?;
804        Ok(self.finish_hugr()?)
805    }
806}
807
808/// Trait implemented by builders of Dataflow container regions of a HUGR
809pub trait DataflowSubContainer: SubContainer + Dataflow {
810    /// Set the outputs of the graph and consume the builder, while returning a
811    /// handle to the parent.
812    ///
813    /// # Errors
814    ///
815    /// This function will return an error if there is an error when setting outputs.
816    fn finish_with_outputs(
817        mut self,
818        outputs: impl IntoIterator<Item = Wire>,
819    ) -> Result<Self::ContainerHandle, BuildError>
820    where
821        Self: Sized,
822    {
823        self.set_outputs(outputs)?;
824        self.finish_sub_container()
825    }
826}
827
828impl<T: HugrBuilder + Dataflow> DataflowHugr for T {}
829impl<T: SubContainer + Dataflow> DataflowSubContainer for T {}