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
37pub trait Container {
42 fn container_node(&self) -> Node;
44 fn hugr_mut(&mut self) -> &mut Hugr;
46 fn hugr(&self) -> &Hugr;
48 fn add_child_node(&mut self, node: impl Into<OpType>) -> Node {
52 let node: OpType = node.into();
53
54 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 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 fn add_constant(&mut self, constant: impl Into<ops::Const>) -> ConstID {
82 self.add_child_node(constant.into()).into()
83 }
84
85 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 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 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 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 fn set_metadata(&mut self, key: impl AsRef<str>, meta: impl Into<NodeMetadata>) {
129 let parent = self.container_node();
130 self.hugr_mut().set_metadata(parent, key, meta);
132 }
133
134 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 fn use_extension(&mut self, ext: impl Into<Arc<Extension>>) {
148 self.hugr_mut().use_extension(ext);
149 }
150
151 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
160pub trait HugrBuilder: Container {
163 fn finish_hugr(self) -> Result<Hugr, ValidationError<Node>>;
165}
166
167pub trait SubContainer: Container {
169 type ContainerHandle;
172 fn finish_sub_container(self) -> Result<Self::ContainerHandle, BuildError>;
175}
176pub trait Dataflow: Container {
178 fn num_inputs(&self) -> usize;
180 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 fn input(&self) -> BuildHandle<DataflowOpID> {
191 (self.io()[0], self.num_inputs()).into()
192 }
193 fn output(&self) -> DataflowOpID {
195 self.io()[1].into()
196 }
197 fn input_wires(&self) -> Outputs {
199 self.input().outputs()
200 }
201 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 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 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 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 #[track_caller]
288 fn input_wires_arr<const N: usize>(&self) -> [Wire; N] {
289 collect_array(self.input_wires())
290 }
291
292 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 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 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 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 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 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 fn add_load_value(&mut self, constant: impl Into<ops::Value>) -> Wire {
388 self.add_load_const(constant.into())
389 }
390
391 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 vec![Wire::new(func_node, func_op.static_output_port().unwrap())],
418 )?;
419
420 Ok(load_n.out_wire(0))
421 }
422
423 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 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 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 fn set_order(&mut self, before: &impl NodeHandle, after: &impl NodeHandle) {
504 self.add_other_wire(before.node(), after.node());
505 }
506
507 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 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 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 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 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 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 fn as_circuit(&mut self, wires: impl IntoIterator<Item = Wire>) -> CircuitBuilder<Self> {
642 CircuitBuilder::new(wires, self)
643 }
644
645 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
667fn 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
690fn 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
708fn 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 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 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 base.add_other_edge(src, src_sibling);
764 }
765 } else if !typ.copyable() & base.linked_ports(src, src_port).next().is_some() {
766 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
789pub trait DataflowHugr: HugrBuilder + Dataflow {
791 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
808pub trait DataflowSubContainer: SubContainer + Dataflow {
810 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 {}