hugr_core/hugr/patch/
replace.rs

1//! Implementation of the `Replace` operation.
2
3use std::collections::{HashMap, HashSet, VecDeque};
4
5use itertools::Itertools;
6use thiserror::Error;
7
8use crate::core::HugrNode;
9use crate::hugr::HugrMut;
10use crate::hugr::hugrmut::InsertionResult;
11use crate::hugr::views::check_valid_non_entrypoint;
12use crate::ops::{OpTag, OpTrait};
13use crate::types::EdgeKind;
14use crate::{Direction, Hugr, HugrView, IncomingPort, Node, OutgoingPort};
15
16use super::{PatchHugrMut, PatchVerification};
17
18/// Specifies how to create a new edge.
19#[derive(Clone, Debug, PartialEq, Eq)]
20pub struct NewEdgeSpec<SrcNode, TgtNode> {
21    /// The source of the new edge. For [`Replacement::mu_inp`] and
22    /// [`Replacement::mu_new`], this is in the existing Hugr; for edges in
23    /// [`Replacement::mu_out`] this is in the [`Replacement::replacement`]
24    pub src: SrcNode,
25    /// The target of the new edge. For [`Replacement::mu_inp`], this is in the
26    /// [`Replacement::replacement`]; for edges in [`Replacement::mu_out`] and
27    /// [`Replacement::mu_new`], this is in the existing Hugr.
28    pub tgt: TgtNode,
29    /// The kind of edge to create, and any port specifiers required
30    pub kind: NewEdgeKind,
31}
32
33/// Describes an edge that should be created between two nodes already given
34#[derive(Clone, Copy, Debug, PartialEq, Eq)]
35pub enum NewEdgeKind {
36    /// An [`EdgeKind::StateOrder`] edge (between DFG nodes only)
37    Order,
38    /// An [`EdgeKind::Value`] edge (between DFG nodes only)
39    Value {
40        /// The source port
41        src_pos: OutgoingPort,
42        /// The target port
43        tgt_pos: IncomingPort,
44    },
45    /// An [`EdgeKind::Const`] or [`EdgeKind::Function`] edge
46    Static {
47        /// The source port
48        src_pos: OutgoingPort,
49        /// The target port
50        tgt_pos: IncomingPort,
51    },
52    /// A [`EdgeKind::ControlFlow`] edge (between CFG nodes only)
53    ControlFlow {
54        /// Identifies a control-flow output (successor) of the source node.
55        src_pos: OutgoingPort,
56    },
57}
58
59/// Specification of a `Replace` operation
60#[derive(Debug, Clone, PartialEq)]
61pub struct Replacement<HostNode = Node> {
62    /// The nodes to remove from the existing Hugr (known as Gamma).
63    /// These must all have a common parent (i.e. be siblings).  Called "S" in
64    /// the spec. Must be non-empty - otherwise there is no parent under
65    /// which to place [`Self::replacement`], and there would be no possible
66    /// [`Self::mu_inp`], [`Self::mu_out`] or [`Self::adoptions`].
67    pub removal: Vec<HostNode>,
68    /// A hugr (not necessarily valid, as it may be missing edges and/or nodes),
69    /// whose root is the same type as the root of [`Self::replacement`].  "G"
70    /// in the spec.
71    pub replacement: Hugr,
72    /// Describes how parts of the Hugr that would otherwise be removed should
73    /// instead be preserved but with new parents amongst the newly-inserted
74    /// nodes.  This is a Map from container nodes in [`Self::replacement`]
75    /// that have no children, to container nodes that are descended from
76    /// [`Self::removal`]. The keys are the new parents for the children of
77    /// the values.  Note no value may be ancestor or descendant of another.
78    /// This is "B" in the spec; "R" is the set of descendants of
79    /// [`Self::removal`]  that are not descendants of values here.
80    pub adoptions: HashMap<Node, HostNode>,
81    /// Edges from nodes in the existing Hugr that are not removed
82    /// ([`NewEdgeSpec::src`] in Gamma\R) to inserted nodes
83    /// ([`NewEdgeSpec::tgt`] in [`Self::replacement`]).
84    pub mu_inp: Vec<NewEdgeSpec<HostNode, Node>>,
85    /// Edges from inserted nodes ([`NewEdgeSpec::src`] in [`Self::replacement`]) to
86    /// existing nodes not removed ([`NewEdgeSpec::tgt`] in Gamma \ R).
87    pub mu_out: Vec<NewEdgeSpec<Node, HostNode>>,
88    /// Edges to add between existing nodes (both [`NewEdgeSpec::src`] and
89    /// [`NewEdgeSpec::tgt`] in Gamma \ R). For example, in cases where the
90    /// source had an edge to a removed node, and the target had an
91    /// edge from a removed node, this would allow source to be directly
92    /// connected to target.
93    pub mu_new: Vec<NewEdgeSpec<HostNode, HostNode>>,
94}
95
96impl<SrcNode: Copy, TgtNode: Copy> NewEdgeSpec<SrcNode, TgtNode> {
97    fn check_src<HostNode>(
98        &self,
99        h: &impl HugrView<Node = SrcNode>,
100        err_spec: impl Fn(Self) -> WhichEdgeSpec<HostNode>,
101    ) -> Result<(), ReplaceError<HostNode>> {
102        let optype = h.get_optype(self.src);
103        let ok = match self.kind {
104            NewEdgeKind::Order => optype.other_output() == Some(EdgeKind::StateOrder),
105            NewEdgeKind::Value { src_pos, .. } => {
106                matches!(optype.port_kind(src_pos), Some(EdgeKind::Value(_)))
107            }
108            NewEdgeKind::Static { src_pos, .. } => optype
109                .port_kind(src_pos)
110                .as_ref()
111                .is_some_and(EdgeKind::is_static),
112            NewEdgeKind::ControlFlow { src_pos } => {
113                matches!(optype.port_kind(src_pos), Some(EdgeKind::ControlFlow))
114            }
115        };
116        ok.then_some(())
117            .ok_or_else(|| ReplaceError::BadEdgeKind(Direction::Outgoing, err_spec(self.clone())))
118    }
119
120    fn check_tgt<HostNode>(
121        &self,
122        h: &impl HugrView<Node = TgtNode>,
123        err_spec: impl Fn(Self) -> WhichEdgeSpec<HostNode>,
124    ) -> Result<(), ReplaceError<HostNode>> {
125        let optype = h.get_optype(self.tgt);
126        let ok = match self.kind {
127            NewEdgeKind::Order => optype.other_input() == Some(EdgeKind::StateOrder),
128            NewEdgeKind::Value { tgt_pos, .. } => {
129                matches!(optype.port_kind(tgt_pos), Some(EdgeKind::Value(_)))
130            }
131            NewEdgeKind::Static { tgt_pos, .. } => optype
132                .port_kind(tgt_pos)
133                .as_ref()
134                .is_some_and(EdgeKind::is_static),
135            NewEdgeKind::ControlFlow { .. } => matches!(
136                optype.port_kind(IncomingPort::from(0)),
137                Some(EdgeKind::ControlFlow)
138            ),
139        };
140        ok.then_some(())
141            .ok_or_else(|| ReplaceError::BadEdgeKind(Direction::Incoming, err_spec(self.clone())))
142    }
143}
144
145impl<HostNode: HugrNode, N: Clone> NewEdgeSpec<N, HostNode> {
146    fn check_existing_edge(
147        &self,
148        h: &impl HugrView<Node = HostNode>,
149        legal_src_ancestors: &HashSet<HostNode>,
150        err_edge: impl Fn(Self) -> WhichEdgeSpec<HostNode>,
151    ) -> Result<(), ReplaceError<HostNode>> {
152        if let NewEdgeKind::Static { tgt_pos, .. } | NewEdgeKind::Value { tgt_pos, .. } = self.kind
153        {
154            let descends_from_legal = |mut descendant: HostNode| -> bool {
155                while !legal_src_ancestors.contains(&descendant) {
156                    let Some(p) = h.get_parent(descendant) else {
157                        return false;
158                    };
159                    descendant = p;
160                }
161                true
162            };
163            let found_incoming = h
164                .single_linked_output(self.tgt, tgt_pos)
165                .is_some_and(|(src_n, _)| descends_from_legal(src_n));
166            if !found_incoming {
167                return Err(ReplaceError::NoRemovedEdge(err_edge(self.clone())));
168            }
169        }
170        Ok(())
171    }
172}
173
174impl<HostNode: HugrNode> Replacement<HostNode> {
175    fn check_parent(
176        &self,
177        h: &impl HugrView<Node = HostNode>,
178    ) -> Result<HostNode, ReplaceError<HostNode>> {
179        let parent = self
180            .removal
181            .iter()
182            .map(|n| h.get_parent(*n))
183            .unique()
184            .exactly_one()
185            .map_err(|ex_one| ReplaceError::MultipleParents(ex_one.flatten().collect()))?
186            .ok_or(ReplaceError::CantReplaceRoot)?; // If no parent
187
188        // Check replacement parent is of same tag. Note we do not require exact
189        // equality of OpType/Signature, e.g. to ease changing of Input/Output
190        // node signatures too.
191        let removed = h.get_optype(parent).tag();
192        let replacement = self.replacement.entrypoint_optype().tag();
193        if removed != replacement {
194            return Err(ReplaceError::WrongRootNodeTag {
195                removed,
196                replacement,
197            });
198        }
199        Ok(parent)
200    }
201
202    fn get_removed_nodes(
203        &self,
204        h: &impl HugrView<Node = HostNode>,
205    ) -> Result<HashSet<HostNode>, ReplaceError<HostNode>> {
206        // Check the keys of the transfer map too, the values we'll use imminently
207        self.adoptions.keys().try_for_each(|&n| {
208            (self.replacement.contains_node(n)
209                && self.replacement.get_optype(n).is_container()
210                && self.replacement.children(n).next().is_none())
211            .then_some(())
212            .ok_or(ReplaceError::InvalidAdoptingParent(n))
213        })?;
214        let mut transferred: HashSet<HostNode> = self.adoptions.values().copied().collect();
215        if transferred.len() != self.adoptions.values().len() {
216            return Err(ReplaceError::AdopteesNotSeparateDescendants(
217                self.adoptions
218                    .values()
219                    .filter(|v| !transferred.remove(v))
220                    .copied()
221                    .collect(),
222            ));
223        }
224
225        let mut removed = HashSet::new();
226        let mut queue = VecDeque::from_iter(self.removal.iter().copied());
227        while let Some(n) = queue.pop_front() {
228            let new = removed.insert(n);
229            debug_assert!(new); // Fails only if h's hierarchy has merges (is not a tree)
230            if !transferred.remove(&n) {
231                h.children(n).for_each(|ch| queue.push_back(ch));
232            }
233        }
234        if !transferred.is_empty() {
235            return Err(ReplaceError::AdopteesNotSeparateDescendants(
236                transferred.into_iter().collect(),
237            ));
238        }
239        Ok(removed)
240    }
241}
242
243impl<HostNode: HugrNode> PatchVerification for Replacement<HostNode> {
244    type Error = ReplaceError<HostNode>;
245    type Node = HostNode;
246
247    fn verify(&self, h: &impl HugrView<Node = HostNode>) -> Result<(), Self::Error> {
248        self.check_parent(h)?;
249        let removed = self.get_removed_nodes(h)?;
250        // Edge sources...
251        for e in &self.mu_inp {
252            if !h.contains_node(e.src) || removed.contains(&e.src) {
253                return Err(ReplaceError::BadEdgeSpec(
254                    Direction::Outgoing,
255                    WhichEdgeSpec::HostToRepl(e.clone()),
256                ));
257            }
258            e.check_src(h, WhichEdgeSpec::HostToRepl)?;
259        }
260        for e in &self.mu_new {
261            if !h.contains_node(e.src) || removed.contains(&e.src) {
262                return Err(ReplaceError::BadEdgeSpec(
263                    Direction::Outgoing,
264                    WhichEdgeSpec::HostToHost(e.clone()),
265                ));
266            }
267            e.check_src(h, WhichEdgeSpec::HostToHost)?;
268        }
269        self.mu_out.iter().try_for_each(|e| {
270            if check_valid_non_entrypoint(&self.replacement, e.src) {
271                e.check_src(&self.replacement, WhichEdgeSpec::ReplToHost)
272            } else {
273                Err(ReplaceError::BadEdgeSpec(
274                    Direction::Outgoing,
275                    WhichEdgeSpec::ReplToHost(e.clone()),
276                ))
277            }
278        })?;
279        // Edge targets...
280        self.mu_inp.iter().try_for_each(|e| {
281            if check_valid_non_entrypoint(&self.replacement, e.tgt) {
282                e.check_tgt(&self.replacement, WhichEdgeSpec::HostToRepl)
283            } else {
284                Err(ReplaceError::BadEdgeSpec(
285                    Direction::Incoming,
286                    WhichEdgeSpec::HostToRepl(e.clone()),
287                ))
288            }
289        })?;
290        for e in &self.mu_out {
291            if !h.contains_node(e.tgt) || removed.contains(&e.tgt) {
292                return Err(ReplaceError::BadEdgeSpec(
293                    Direction::Incoming,
294                    WhichEdgeSpec::ReplToHost(e.clone()),
295                ));
296            }
297            e.check_tgt(h, WhichEdgeSpec::ReplToHost)?;
298            // The descendant check is to allow the case where the old edge is nonlocal
299            // from a part of the Hugr being moved (which may require changing source,
300            // depending on where the transplanted portion ends up). While this subsumes
301            // the first "removed.contains" check, we'll keep that as a common-case
302            // fast-path.
303            e.check_existing_edge(h, &removed, WhichEdgeSpec::ReplToHost)?;
304        }
305        for e in &self.mu_new {
306            if !h.contains_node(e.tgt) || removed.contains(&e.tgt) {
307                return Err(ReplaceError::BadEdgeSpec(
308                    Direction::Incoming,
309                    WhichEdgeSpec::HostToHost(e.clone()),
310                ));
311            }
312            e.check_tgt(h, WhichEdgeSpec::HostToHost)?;
313            // The descendant check is to allow the case where the old edge is nonlocal
314            // from a part of the Hugr being moved (which may require changing source,
315            // depending on where the transplanted portion ends up). While this subsumes
316            // the first "removed.contains" check, we'll keep that as a common-case
317            // fast-path.
318            e.check_existing_edge(h, &removed, WhichEdgeSpec::HostToHost)?;
319        }
320        Ok(())
321    }
322
323    fn invalidation_set(&self) -> impl Iterator<Item = HostNode> {
324        self.removal.iter().copied()
325    }
326}
327
328impl<HostNode: HugrNode> PatchHugrMut for Replacement<HostNode> {
329    /// Map from Node in replacement to corresponding Node in the result Hugr
330    type Outcome = HashMap<Node, HostNode>;
331
332    const UNCHANGED_ON_FAILURE: bool = false;
333
334    fn apply_hugr_mut(
335        self,
336        h: &mut impl HugrMut<Node = HostNode>,
337    ) -> Result<Self::Outcome, Self::Error> {
338        let parent = self.check_parent(h)?;
339        // Calculate removed nodes here. (Does not include transfers, so enumerates only
340        // nodes we are going to remove, individually, anyway; so no *asymptotic* speed
341        // penalty)
342        let to_remove = self.get_removed_nodes(h)?;
343
344        // 1. Add all the new nodes. Note this includes replacement.root(), which we
345        //    don't want.
346        // TODO what would an error here mean? e.g. malformed self.replacement??
347        let InsertionResult {
348            inserted_entrypoint,
349            node_map,
350        } = h.insert_hugr(parent, self.replacement);
351
352        // 2. Add new edges from existing to copied nodes according to mu_in
353        let translate_idx = |n| node_map.get(&n).copied();
354        let kept = |n| (!to_remove.contains(&n)).then_some(n);
355        transfer_edges(
356            h,
357            self.mu_inp.iter(),
358            kept,
359            translate_idx,
360            WhichEdgeSpec::HostToRepl,
361            None,
362        )?;
363
364        // 3. Add new edges from copied to existing nodes according to mu_out,
365        // replacing existing value/static edges incoming to targets
366        transfer_edges(
367            h,
368            self.mu_out.iter(),
369            translate_idx,
370            kept,
371            WhichEdgeSpec::ReplToHost,
372            Some(&to_remove),
373        )?;
374
375        // 4. Add new edges between existing nodes according to mu_new,
376        // replacing existing value/static edges incoming to targets.
377        transfer_edges(
378            h,
379            self.mu_new.iter(),
380            kept,
381            kept,
382            WhichEdgeSpec::HostToHost,
383            Some(&to_remove),
384        )?;
385
386        // 5. Put newly-added copies into correct places in hierarchy
387        // (these will be correct places after removing nodes)
388        let mut remove_top_sibs = self.removal.iter();
389        for new_node in h.children(inserted_entrypoint).collect::<Vec<HostNode>>() {
390            if let Some(top_sib) = remove_top_sibs.next() {
391                h.move_before_sibling(new_node, *top_sib);
392            } else {
393                h.set_parent(new_node, parent);
394            }
395        }
396        debug_assert!(h.children(inserted_entrypoint).next().is_none());
397        h.remove_node(inserted_entrypoint);
398
399        // 6. Transfer to keys of `transfers` children of the corresponding values.
400        for (new_parent, &old_parent) in &self.adoptions {
401            let new_parent = node_map.get(new_parent).unwrap();
402            debug_assert!(h.children(old_parent).next().is_some());
403            while let Some(ch) = h.first_child(old_parent) {
404                h.set_parent(ch, *new_parent);
405            }
406        }
407
408        // 7. Remove remaining nodes
409        for n in to_remove {
410            h.remove_node(n);
411        }
412        Ok(node_map)
413    }
414}
415
416fn transfer_edges<'a, SrcNode, TgtNode, HostNode>(
417    h: &mut impl HugrMut<Node = HostNode>,
418    edges: impl Iterator<Item = &'a NewEdgeSpec<SrcNode, TgtNode>>,
419    trans_src: impl Fn(SrcNode) -> Option<HostNode>,
420    trans_tgt: impl Fn(TgtNode) -> Option<HostNode>,
421    err_spec: impl Fn(NewEdgeSpec<SrcNode, TgtNode>) -> WhichEdgeSpec<HostNode>,
422    legal_src_ancestors: Option<&HashSet<HostNode>>,
423) -> Result<(), ReplaceError<HostNode>>
424where
425    SrcNode: 'a + HugrNode,
426    TgtNode: 'a + HugrNode,
427    HostNode: 'a + HugrNode,
428{
429    for oe in edges {
430        let err_spec = err_spec(oe.clone());
431        let e = NewEdgeSpec {
432            // Translation can only fail for Nodes that are supposed to be in the replacement
433            src: trans_src(oe.src)
434                .ok_or_else(|| ReplaceError::BadEdgeSpec(Direction::Outgoing, err_spec.clone()))?,
435            tgt: trans_tgt(oe.tgt)
436                .ok_or_else(|| ReplaceError::BadEdgeSpec(Direction::Incoming, err_spec.clone()))?,
437            kind: oe.kind,
438        };
439        if !h.contains_node(e.src) {
440            return Err(ReplaceError::BadEdgeSpec(
441                Direction::Outgoing,
442                err_spec.clone(),
443            ));
444        }
445        if !h.contains_node(e.tgt) {
446            return Err(ReplaceError::BadEdgeSpec(
447                Direction::Incoming,
448                err_spec.clone(),
449            ));
450        }
451        let err_spec = |_| err_spec.clone();
452        e.check_src(h, err_spec)?;
453        e.check_tgt(h, err_spec)?;
454        match e.kind {
455            NewEdgeKind::Order => {
456                h.add_other_edge(e.src, e.tgt);
457            }
458            NewEdgeKind::Value { src_pos, tgt_pos } | NewEdgeKind::Static { src_pos, tgt_pos } => {
459                if let Some(legal_src_ancestors) = legal_src_ancestors {
460                    e.check_existing_edge(h, legal_src_ancestors, err_spec)?;
461                    h.disconnect(e.tgt, tgt_pos);
462                }
463                h.connect(e.src, src_pos, e.tgt, tgt_pos);
464            }
465            NewEdgeKind::ControlFlow { src_pos } => h.connect(e.src, src_pos, e.tgt, 0),
466        }
467    }
468    Ok(())
469}
470
471/// Error in a [`Replacement`]
472#[derive(Clone, Debug, PartialEq, Eq, Error)]
473#[non_exhaustive]
474pub enum ReplaceError<HostNode = Node> {
475    /// The node(s) to replace had no parent i.e. were root(s).
476    // (Perhaps if there is only one node to replace we should be able to?)
477    #[error("Cannot replace the root node of the Hugr")]
478    CantReplaceRoot,
479    /// The nodes to replace did not have a unique common parent
480    #[error("Removed nodes had different parents {0:?}")]
481    MultipleParents(Vec<HostNode>),
482    /// Replacement root node had different tag from parent of removed nodes
483    #[error("Expected replacement root with tag {removed} but found {replacement}")]
484    WrongRootNodeTag {
485        /// The tag of the parent of the removed nodes
486        removed: OpTag,
487        /// The tag of the root in the replacement Hugr
488        replacement: OpTag,
489    },
490    /// Keys in [`Replacement::adoptions`] were not valid container nodes in
491    /// [`Replacement::replacement`]
492    #[error("Node {0} was not an empty container node in the replacement")]
493    InvalidAdoptingParent(Node),
494    /// Some values in [`Replacement::adoptions`] were either descendants of other
495    /// values, or not descendants of the [`Replacement::removal`]. The nodes
496    /// are indicated on a best-effort basis.
497    #[error("Nodes not free to be moved into new locations: {0:?}")]
498    AdopteesNotSeparateDescendants(Vec<HostNode>),
499    /// A node at one end of a [`NewEdgeSpec`] was not found
500    #[error("{0:?} end of edge {1:?} not found in {which_hugr}", which_hugr = .1.which_hugr(*.0))]
501    BadEdgeSpec(Direction, WhichEdgeSpec<HostNode>),
502    /// The target of the edge was found, but there was no existing edge to
503    /// replace
504    #[error("Target of edge {0:?} did not have a corresponding incoming edge being removed")]
505    NoRemovedEdge(WhichEdgeSpec<HostNode>),
506    /// The [`NewEdgeKind`] was not applicable for the source/target node(s)
507    #[error("The edge kind was not applicable to the {0:?} node: {1:?}")]
508    BadEdgeKind(Direction, WhichEdgeSpec<HostNode>),
509}
510
511/// The three kinds of [`NewEdgeSpec`] that may appear in a [`ReplaceError`]
512#[derive(Clone, Debug, PartialEq, Eq)]
513pub enum WhichEdgeSpec<HostNode> {
514    /// An edge from the host Hugr into the replacement, i.e.
515    /// [`Replacement::mu_inp`]
516    HostToRepl(NewEdgeSpec<HostNode, Node>),
517    /// An edge from the replacement to the host, i.e. [`Replacement::mu_out`]
518    ReplToHost(NewEdgeSpec<Node, HostNode>),
519    /// An edge between two nodes in the host (bypassing the replacement),
520    /// i.e. [`Replacement::mu_new`]
521    HostToHost(NewEdgeSpec<HostNode, HostNode>),
522}
523
524impl<HostNode> WhichEdgeSpec<HostNode> {
525    fn which_hugr(&self, d: Direction) -> &str {
526        match (self, d) {
527            (Self::HostToRepl(_), Direction::Incoming)
528            | (Self::ReplToHost(_), Direction::Outgoing) => "replacement Hugr",
529            _ => "retained portion of Hugr",
530        }
531    }
532}
533
534#[cfg(test)]
535mod test {
536    use std::collections::HashMap;
537
538    use cool_asserts::assert_matches;
539    use itertools::Itertools;
540
541    use crate::builder::{
542        BuildError, CFGBuilder, Container, DFGBuilder, Dataflow, DataflowHugr,
543        DataflowSubContainer, HugrBuilder, SubContainer, endo_sig,
544    };
545    use crate::extension::prelude::{bool_t, usize_t};
546    use crate::extension::{ExtensionRegistry, PRELUDE};
547    use crate::hugr::internal::HugrMutInternals;
548    use crate::hugr::patch::PatchVerification;
549    use crate::hugr::{HugrMut, Patch};
550    use crate::ops::custom::ExtensionOp;
551    use crate::ops::dataflow::DataflowOpTrait;
552    use crate::ops::handle::{BasicBlockID, ConstID, NodeHandle};
553    use crate::ops::{self, Case, DFG, DataflowBlock, OpTag, OpType};
554    use crate::std_extensions::collections::list;
555    use crate::types::{Signature, Type, TypeRow};
556    use crate::utils::{depth, test_quantum_extension};
557    use crate::{Direction, Extension, Hugr, HugrView, OutgoingPort, type_row};
558
559    use super::{NewEdgeKind, NewEdgeSpec, ReplaceError, Replacement, WhichEdgeSpec};
560
561    #[test]
562    #[ignore] // FIXME: This needs a rewrite now that `pop` returns an optional value -.-'
563    fn cfg() -> Result<(), Box<dyn std::error::Error>> {
564        let reg = ExtensionRegistry::new([PRELUDE.to_owned(), list::EXTENSION.to_owned()]);
565        reg.validate()?;
566        let listy = list::list_type(usize_t());
567        let pop: ExtensionOp = list::ListOp::pop
568            .with_type(usize_t())
569            .to_extension_op()
570            .unwrap();
571        let push: ExtensionOp = list::ListOp::push
572            .with_type(usize_t())
573            .to_extension_op()
574            .unwrap();
575        let just_list = TypeRow::from(vec![listy.clone()]);
576        let intermed = TypeRow::from(vec![listy.clone(), usize_t()]);
577
578        let mut cfg = CFGBuilder::new(endo_sig(just_list.clone()))?;
579
580        let pred_const = cfg.add_constant(ops::Value::unary_unit_sum());
581
582        let entry = single_node_block(&mut cfg, pop, &pred_const, true)?;
583        let bb2 = single_node_block(&mut cfg, push, &pred_const, false)?;
584
585        let exit = cfg.exit_block();
586        cfg.branch(&entry, 0, &bb2)?;
587        cfg.branch(&bb2, 0, &exit)?;
588
589        let mut h = cfg.finish_hugr().unwrap();
590        {
591            let pop = find_node(&h, "pop");
592            let push = find_node(&h, "push");
593            assert_eq!(depth(&h, pop), 2); // BB, CFG
594            assert_eq!(depth(&h, push), 2);
595
596            let popp = h.get_parent(pop).unwrap();
597            let pushp = h.get_parent(push).unwrap();
598            assert_ne!(popp, pushp); // Two different BBs
599            assert!(h.get_optype(popp).is_dataflow_block());
600            assert!(h.get_optype(pushp).is_dataflow_block());
601
602            assert_eq!(h.get_parent(popp).unwrap(), h.get_parent(pushp).unwrap());
603        }
604
605        // Replacement: one BB with two DFGs inside.
606        // Use Hugr rather than Builder because it must be empty (not even
607        // Input/Output).
608        let mut replacement = Hugr::new_with_entrypoint(ops::CFG {
609            signature: Signature::new_endo(just_list.clone()),
610        })
611        .expect("CFG is a valid entrypoint");
612        let r_bb = replacement.add_node_with_parent(
613            replacement.entrypoint(),
614            DataflowBlock {
615                inputs: vec![listy.clone()].into(),
616                sum_rows: vec![type_row![]],
617                other_outputs: vec![listy.clone()].into(),
618            },
619        );
620        let r_df1 = replacement.add_node_with_parent(
621            r_bb,
622            DFG {
623                signature: Signature::new(vec![listy.clone()], simple_unary_plus(intermed.clone())),
624            },
625        );
626        let r_df2 = replacement.add_node_with_parent(
627            r_bb,
628            DFG {
629                signature: Signature::new(intermed, simple_unary_plus(just_list.clone())),
630            },
631        );
632        [0, 1]
633            .iter()
634            .for_each(|p| replacement.connect(r_df1, *p + 1, r_df2, *p));
635
636        {
637            let inp = replacement.add_node_before(
638                r_df1,
639                ops::Input {
640                    types: just_list.clone(),
641                },
642            );
643            let out = replacement.add_node_before(
644                r_df1,
645                ops::Output {
646                    types: simple_unary_plus(just_list),
647                },
648            );
649            replacement.connect(inp, 0, r_df1, 0);
650            replacement.connect(r_df2, 0, out, 0);
651            replacement.connect(r_df2, 1, out, 1);
652        }
653
654        h.apply_patch(Replacement {
655            removal: vec![entry.node(), bb2.node()],
656            replacement,
657            adoptions: HashMap::from([(r_df1.node(), entry.node()), (r_df2.node(), bb2.node())]),
658            mu_inp: vec![],
659            mu_out: vec![NewEdgeSpec {
660                src: r_bb,
661                tgt: exit.node(),
662                kind: NewEdgeKind::ControlFlow {
663                    src_pos: OutgoingPort::from(0),
664                },
665            }],
666            mu_new: vec![],
667        })?;
668        h.validate()?;
669        {
670            let pop = find_node(&h, "pop");
671            let push = find_node(&h, "push");
672            assert_eq!(depth(&h, pop), 3); // DFG, BB, CFG
673            assert_eq!(depth(&h, push), 3);
674
675            let popp = h.get_parent(pop).unwrap();
676            let pushp = h.get_parent(push).unwrap();
677            assert_ne!(popp, pushp); // Two different DFGs
678            assert!(h.get_optype(popp).is_dfg());
679            assert!(h.get_optype(pushp).is_dfg());
680
681            let grandp = h.get_parent(popp).unwrap();
682            assert_eq!(grandp, h.get_parent(pushp).unwrap());
683            assert!(h.get_optype(grandp).is_dataflow_block());
684        }
685
686        Ok(())
687    }
688
689    fn find_node(h: &Hugr, s: &str) -> crate::Node {
690        h.entry_descendants()
691            .filter(|n| format!("{}", h.get_optype(*n)).contains(s))
692            .exactly_one()
693            .ok()
694            .unwrap()
695    }
696
697    fn single_node_block<T: AsRef<Hugr> + AsMut<Hugr>, O: DataflowOpTrait + Into<OpType>>(
698        h: &mut CFGBuilder<T>,
699        op: O,
700        pred_const: &ConstID,
701        entry: bool,
702    ) -> Result<BasicBlockID, BuildError> {
703        let op_sig = op.signature();
704        let mut bb = if entry {
705            assert_eq!(
706                if let OpType::CFG(c) = h.hugr().get_optype(h.container_node()) {
707                    &c.signature.input
708                } else {
709                    panic!()
710                },
711                op_sig.input()
712            );
713            h.simple_entry_builder(op_sig.output.clone(), 1)?
714        } else {
715            h.simple_block_builder(op_sig.into_owned(), 1)?
716        };
717        let op: OpType = op.into();
718        let op = bb.add_dataflow_op(op, bb.input_wires())?;
719        let load_pred = bb.load_const(pred_const);
720        bb.finish_with_outputs(load_pred, op.outputs())
721    }
722
723    fn simple_unary_plus(t: TypeRow) -> TypeRow {
724        let mut v = t.into_owned();
725        v.insert(0, Type::new_unit_sum(1));
726        v.into()
727    }
728
729    #[test]
730    fn test_invalid() {
731        let utou = Signature::new_endo(vec![usize_t()]);
732        let ext = Extension::new_test_arc("new_ext".try_into().unwrap(), |ext, extension_ref| {
733            ext.add_op("foo".into(), String::new(), utou.clone(), extension_ref)
734                .unwrap();
735            ext.add_op("bar".into(), String::new(), utou.clone(), extension_ref)
736                .unwrap();
737            ext.add_op("baz".into(), String::new(), utou.clone(), extension_ref)
738                .unwrap();
739        });
740        let foo = ext.instantiate_extension_op("foo", []).unwrap();
741        let bar = ext.instantiate_extension_op("bar", []).unwrap();
742        let baz = ext.instantiate_extension_op("baz", []).unwrap();
743        let mut registry = test_quantum_extension::REG.clone();
744        registry.register(ext).unwrap();
745
746        let mut h =
747            DFGBuilder::new(Signature::new(vec![usize_t(), bool_t()], vec![usize_t()])).unwrap();
748        let [i, b] = h.input_wires_arr();
749        let mut cond = h
750            .conditional_builder(
751                (vec![type_row![]; 2], b),
752                [(usize_t(), i)],
753                vec![usize_t()].into(),
754            )
755            .unwrap();
756        let mut case1 = cond.case_builder(0).unwrap();
757        let foo = case1.add_dataflow_op(foo, case1.input_wires()).unwrap();
758        let case1 = case1.finish_with_outputs(foo.outputs()).unwrap().node();
759        let mut case2 = cond.case_builder(1).unwrap();
760        let bar = case2.add_dataflow_op(bar, case2.input_wires()).unwrap();
761        let mut baz_dfg = case2.dfg_builder(utou.clone(), bar.outputs()).unwrap();
762        let baz = baz_dfg.add_dataflow_op(baz, baz_dfg.input_wires()).unwrap();
763        let baz_dfg = baz_dfg.finish_with_outputs(baz.outputs()).unwrap();
764        let case2 = case2.finish_with_outputs(baz_dfg.outputs()).unwrap().node();
765        let cond = cond.finish_sub_container().unwrap();
766        let h = h.finish_hugr_with_outputs(cond.outputs()).unwrap();
767
768        let mut r_hugr = Hugr::new_with_entrypoint(h.get_optype(cond.node()).clone()).unwrap();
769        let r1 = r_hugr.add_node_with_parent(
770            r_hugr.entrypoint(),
771            Case {
772                signature: utou.clone(),
773            },
774        );
775        let r2 = r_hugr.add_node_with_parent(
776            r_hugr.entrypoint(),
777            Case {
778                signature: utou.clone(),
779            },
780        );
781        let rep: Replacement = Replacement {
782            removal: vec![case1, case2],
783            replacement: r_hugr,
784            adoptions: HashMap::from_iter([(r1, case1), (r2, baz_dfg.node())]),
785            mu_inp: vec![],
786            mu_out: vec![],
787            mu_new: vec![],
788        };
789        assert_eq!(h.get_parent(baz.node()), Some(baz_dfg.node()));
790        rep.verify(&h).unwrap();
791        {
792            let mut target = h.clone();
793            let node_map = rep.clone().apply(&mut target).unwrap();
794            let new_case2 = *node_map.get(&r2).unwrap();
795            assert_eq!(target.get_parent(baz.node()), Some(new_case2));
796        }
797
798        // Test some bad Replacements (using variations of the `replacement` Hugr).
799        let check_same_errors = |r: Replacement| {
800            let verify_res = r.verify(&h).unwrap_err();
801            let apply_res = r.apply(&mut h.clone()).unwrap_err();
802            assert_eq!(verify_res, apply_res);
803            apply_res
804        };
805        // Root node type needs to be that of common parent of the removed nodes:
806        let mut rep2 = rep.clone();
807        rep2.replacement
808            .replace_op(rep2.replacement.entrypoint(), h.entrypoint_optype().clone());
809        assert_eq!(
810            check_same_errors(rep2),
811            ReplaceError::WrongRootNodeTag {
812                removed: OpTag::Conditional,
813                replacement: OpTag::Dfg
814            }
815        );
816        // Removed nodes...
817        assert_eq!(
818            check_same_errors(Replacement {
819                removal: vec![h.module_root()],
820                ..rep.clone()
821            }),
822            ReplaceError::CantReplaceRoot
823        );
824        assert_eq!(
825            check_same_errors(Replacement {
826                removal: vec![case1, baz_dfg.node()],
827                ..rep.clone()
828            }),
829            ReplaceError::MultipleParents(vec![cond.node(), case2])
830        );
831        // Adoptions...
832        assert_eq!(
833            check_same_errors(Replacement {
834                adoptions: HashMap::from([(r1, case1), (rep.replacement.entrypoint(), case2)]),
835                ..rep.clone()
836            }),
837            ReplaceError::InvalidAdoptingParent(rep.replacement.entrypoint())
838        );
839        assert_eq!(
840            check_same_errors(Replacement {
841                adoptions: HashMap::from_iter([(r1, case1), (r2, case1)]),
842                ..rep.clone()
843            }),
844            ReplaceError::AdopteesNotSeparateDescendants(vec![case1])
845        );
846        assert_eq!(
847            check_same_errors(Replacement {
848                adoptions: HashMap::from_iter([(r1, case2), (r2, baz_dfg.node())]),
849                ..rep.clone()
850            }),
851            ReplaceError::AdopteesNotSeparateDescendants(vec![baz_dfg.node()])
852        );
853        // Edges....
854        let edge_from_removed = NewEdgeSpec {
855            src: case1,
856            tgt: r2,
857            kind: NewEdgeKind::Order,
858        };
859        assert_eq!(
860            check_same_errors(Replacement {
861                mu_inp: vec![edge_from_removed.clone()],
862                ..rep.clone()
863            }),
864            ReplaceError::BadEdgeSpec(
865                Direction::Outgoing,
866                WhichEdgeSpec::HostToRepl(edge_from_removed)
867            )
868        );
869        let bad_out_edge = NewEdgeSpec {
870            src: h.nodes().max().unwrap(), // not valid in replacement
871            tgt: cond.node(),
872            kind: NewEdgeKind::Order,
873        };
874        assert_eq!(
875            check_same_errors(Replacement {
876                mu_out: vec![bad_out_edge.clone()],
877                ..rep.clone()
878            }),
879            ReplaceError::BadEdgeSpec(Direction::Outgoing, WhichEdgeSpec::ReplToHost(bad_out_edge),)
880        );
881        let bad_order_edge = NewEdgeSpec {
882            src: cond.node(),
883            tgt: h.get_io(h.entrypoint()).unwrap()[1],
884            kind: NewEdgeKind::ControlFlow { src_pos: 0.into() },
885        };
886        assert_matches!(
887            check_same_errors(Replacement {
888                mu_new: vec![bad_order_edge.clone()],
889                ..rep.clone()
890            }),
891            ReplaceError::BadEdgeKind(_, e) => assert_eq!(e, WhichEdgeSpec::HostToHost(bad_order_edge))
892        );
893        let op = OutgoingPort::from(0);
894        let (tgt, ip) = h.linked_inputs(cond.node(), op).next().unwrap();
895        let new_out_edge = NewEdgeSpec {
896            src: r1.node(),
897            tgt,
898            kind: NewEdgeKind::Value {
899                src_pos: op,
900                tgt_pos: ip,
901            },
902        };
903        assert_eq!(
904            check_same_errors(Replacement {
905                mu_out: vec![new_out_edge.clone()],
906                ..rep.clone()
907            }),
908            ReplaceError::BadEdgeKind(Direction::Outgoing, WhichEdgeSpec::ReplToHost(new_out_edge))
909        );
910    }
911}