Skip to main content

dfir_lang/graph/
meta_graph.rs

1#![warn(missing_docs)]
2
3extern crate proc_macro;
4
5use std::collections::{BTreeMap, BTreeSet};
6use std::fmt::Debug;
7use std::iter::FusedIterator;
8
9use itertools::Itertools;
10use proc_macro2::{Ident, Literal, Span, TokenStream};
11use quote::{ToTokens, format_ident, quote, quote_spanned};
12use serde::{Deserialize, Serialize};
13use slotmap::{Key, SecondaryMap, SlotMap, SparseSecondaryMap};
14use syn::spanned::Spanned;
15
16use super::graph_write::{Dot, GraphWrite, Mermaid};
17use super::ops::{
18    DelayType, OPERATORS, OperatorWriteOutput, WriteContextArgs, find_op_op_constraints,
19    null_write_iterator_fn,
20};
21use super::{
22    CONTEXT, Color, DiMulGraph, GRAPH, GraphEdgeId, GraphLoopId, GraphNode, GraphNodeId,
23    GraphSubgraphId, HANDOFF_NODE_STR, MODULE_BOUNDARY_NODE_STR, OperatorInstance, PortIndexValue,
24    Varname, change_spans, get_operator_generics,
25};
26use crate::diagnostic::{Diagnostic, Diagnostics, Level};
27use crate::pretty_span::{PrettyRowCol, PrettySpan};
28use crate::process_singletons;
29
30/// An abstract "meta graph" representation of a DFIR graph.
31///
32/// Can be with or without subgraph partitioning, stratification, and handoff insertion. This is
33/// the meta graph used for generating Rust source code in macros from DFIR sytnax.
34///
35/// This struct has a lot of methods for manipulating the graph, vaguely grouped together in
36/// separate `impl` blocks. You might notice a few particularly specific arbitray-seeming methods
37/// in here--those are just what was needed for the compilation algorithms. If you need another
38/// method then add it.
39#[derive(Default, Debug, Serialize, Deserialize)]
40pub struct DfirGraph {
41    /// Each node type (operator or handoff).
42    nodes: SlotMap<GraphNodeId, GraphNode>,
43
44    /// Instance data corresponding to each operator node.
45    /// This field will be empty after deserialization.
46    #[serde(skip)]
47    operator_instances: SecondaryMap<GraphNodeId, OperatorInstance>,
48    /// Debugging/tracing tag for each operator node.
49    operator_tag: SecondaryMap<GraphNodeId, String>,
50    /// Graph data structure (two-way adjacency list).
51    graph: DiMulGraph<GraphNodeId, GraphEdgeId>,
52    /// Input and output port for each edge.
53    ports: SecondaryMap<GraphEdgeId, (PortIndexValue, PortIndexValue)>,
54
55    /// Which loop a node belongs to (or none for top-level).
56    node_loops: SecondaryMap<GraphNodeId, GraphLoopId>,
57    /// Which nodes belong to each loop.
58    loop_nodes: SlotMap<GraphLoopId, Vec<GraphNodeId>>,
59    /// For the loop, what is its parent (`None` for top-level).
60    loop_parent: SparseSecondaryMap<GraphLoopId, GraphLoopId>,
61    /// What loops are at the root.
62    root_loops: Vec<GraphLoopId>,
63    /// For the loop, what are its child loops.
64    loop_children: SecondaryMap<GraphLoopId, Vec<GraphLoopId>>,
65
66    /// Which subgraph each node belongs to.
67    node_subgraph: SecondaryMap<GraphNodeId, GraphSubgraphId>,
68
69    /// Which nodes belong to each subgraph.
70    subgraph_nodes: SlotMap<GraphSubgraphId, Vec<GraphNodeId>>,
71
72    /// Resolved singletons varnames references, per node.
73    node_singleton_references: SparseSecondaryMap<GraphNodeId, Vec<Option<GraphNodeId>>>,
74    /// What variable name each graph node belongs to (if any). For debugging (graph writing) purposes only.
75    node_varnames: SparseSecondaryMap<GraphNodeId, Varname>,
76
77    /// Delay type for handoff nodes that represent tick-boundary back-edges.
78    /// Set by `order_subgraphs` for `defer_tick` / `defer_tick_lazy`, either on handoff nodes
79    /// it injects or on existing handoff nodes that it marks as tick-boundary back-edges.
80    handoff_delay_type: SparseSecondaryMap<GraphNodeId, DelayType>,
81}
82
83/// Basic methods.
84impl DfirGraph {
85    /// Create a new empty graph.
86    pub fn new() -> Self {
87        Default::default()
88    }
89}
90
91/// Node methods.
92impl DfirGraph {
93    /// Get a node with its operator instance (if applicable).
94    pub fn node(&self, node_id: GraphNodeId) -> &GraphNode {
95        self.nodes.get(node_id).expect("Node not found.")
96    }
97
98    /// Get the `OperatorInstance` for a given node. Node must be an operator and have an
99    /// `OperatorInstance` present, otherwise will return `None`.
100    ///
101    /// Note that no operator instances will be persent after deserialization.
102    pub fn node_op_inst(&self, node_id: GraphNodeId) -> Option<&OperatorInstance> {
103        self.operator_instances.get(node_id)
104    }
105
106    /// Get the debug variable name attached to a graph node.
107    pub fn node_varname(&self, node_id: GraphNodeId) -> Option<&Varname> {
108        self.node_varnames.get(node_id)
109    }
110
111    /// Get subgraph for node.
112    pub fn node_subgraph(&self, node_id: GraphNodeId) -> Option<GraphSubgraphId> {
113        self.node_subgraph.get(node_id).copied()
114    }
115
116    /// Degree into a node, i.e. the number of predecessors.
117    pub fn node_degree_in(&self, node_id: GraphNodeId) -> usize {
118        self.graph.degree_in(node_id)
119    }
120
121    /// Degree out of a node, i.e. the number of successors.
122    pub fn node_degree_out(&self, node_id: GraphNodeId) -> usize {
123        self.graph.degree_out(node_id)
124    }
125
126    /// Successors, iterator of `(GraphEdgeId, GraphNodeId)` of outgoing edges.
127    pub fn node_successors(
128        &self,
129        src: GraphNodeId,
130    ) -> impl '_
131    + DoubleEndedIterator<Item = (GraphEdgeId, GraphNodeId)>
132    + ExactSizeIterator
133    + FusedIterator
134    + Clone
135    + Debug {
136        self.graph.successors(src)
137    }
138
139    /// Predecessors, iterator of `(GraphEdgeId, GraphNodeId)` of incoming edges.
140    pub fn node_predecessors(
141        &self,
142        dst: GraphNodeId,
143    ) -> impl '_
144    + DoubleEndedIterator<Item = (GraphEdgeId, GraphNodeId)>
145    + ExactSizeIterator
146    + FusedIterator
147    + Clone
148    + Debug {
149        self.graph.predecessors(dst)
150    }
151
152    /// Successor edges, iterator of `GraphEdgeId` of outgoing edges.
153    pub fn node_successor_edges(
154        &self,
155        src: GraphNodeId,
156    ) -> impl '_
157    + DoubleEndedIterator<Item = GraphEdgeId>
158    + ExactSizeIterator
159    + FusedIterator
160    + Clone
161    + Debug {
162        self.graph.successor_edges(src)
163    }
164
165    /// Predecessor edges, iterator of `GraphEdgeId` of incoming edges.
166    pub fn node_predecessor_edges(
167        &self,
168        dst: GraphNodeId,
169    ) -> impl '_
170    + DoubleEndedIterator<Item = GraphEdgeId>
171    + ExactSizeIterator
172    + FusedIterator
173    + Clone
174    + Debug {
175        self.graph.predecessor_edges(dst)
176    }
177
178    /// Successor nodes, iterator of `GraphNodeId`.
179    pub fn node_successor_nodes(
180        &self,
181        src: GraphNodeId,
182    ) -> impl '_
183    + DoubleEndedIterator<Item = GraphNodeId>
184    + ExactSizeIterator
185    + FusedIterator
186    + Clone
187    + Debug {
188        self.graph.successor_vertices(src)
189    }
190
191    /// Predecessor nodes, iterator of `GraphNodeId`.
192    pub fn node_predecessor_nodes(
193        &self,
194        dst: GraphNodeId,
195    ) -> impl '_
196    + DoubleEndedIterator<Item = GraphNodeId>
197    + ExactSizeIterator
198    + FusedIterator
199    + Clone
200    + Debug {
201        self.graph.predecessor_vertices(dst)
202    }
203
204    /// Iterator of node IDs `GraphNodeId`.
205    pub fn node_ids(&self) -> slotmap::basic::Keys<'_, GraphNodeId, GraphNode> {
206        self.nodes.keys()
207    }
208
209    /// Iterator over `(GraphNodeId, &Node)` pairs.
210    pub fn nodes(&self) -> slotmap::basic::Iter<'_, GraphNodeId, GraphNode> {
211        self.nodes.iter()
212    }
213
214    /// Insert a node, assigning the given varname.
215    pub fn insert_node(
216        &mut self,
217        node: GraphNode,
218        varname_opt: Option<Ident>,
219        loop_opt: Option<GraphLoopId>,
220    ) -> GraphNodeId {
221        let node_id = self.nodes.insert(node);
222        if let Some(varname) = varname_opt {
223            self.node_varnames.insert(node_id, Varname(varname));
224        }
225        if let Some(loop_id) = loop_opt {
226            self.node_loops.insert(node_id, loop_id);
227            self.loop_nodes[loop_id].push(node_id);
228        }
229        node_id
230    }
231
232    /// Insert an operator instance for the given node. Panics if already set.
233    pub fn insert_node_op_inst(&mut self, node_id: GraphNodeId, op_inst: OperatorInstance) {
234        assert!(matches!(
235            self.nodes.get(node_id),
236            Some(GraphNode::Operator(_))
237        ));
238        let old_inst = self.operator_instances.insert(node_id, op_inst);
239        assert!(old_inst.is_none());
240    }
241
242    /// Assign all operator instances if not set. Write diagnostic messages/errors into `diagnostics`.
243    pub fn insert_node_op_insts_all(&mut self, diagnostics: &mut Diagnostics) {
244        let mut op_insts = Vec::new();
245        for (node_id, node) in self.nodes() {
246            let GraphNode::Operator(operator) = node else {
247                continue;
248            };
249            if self.node_op_inst(node_id).is_some() {
250                continue;
251            };
252
253            // Op constraints.
254            let Some(op_constraints) = find_op_op_constraints(operator) else {
255                diagnostics.push(Diagnostic::spanned(
256                    operator.path.span(),
257                    Level::Error,
258                    format!("Unknown operator `{}`", operator.name_string()),
259                ));
260                continue;
261            };
262
263            // Input and output ports.
264            let (input_ports, output_ports) = {
265                let mut input_edges: Vec<(&PortIndexValue, GraphNodeId)> = self
266                    .node_predecessors(node_id)
267                    .map(|(edge_id, pred_id)| (self.edge_ports(edge_id).1, pred_id))
268                    .collect();
269                // Ensure sorted by port index.
270                input_edges.sort();
271                let input_ports: Vec<PortIndexValue> = input_edges
272                    .into_iter()
273                    .map(|(port, _pred)| port)
274                    .cloned()
275                    .collect();
276
277                // Collect output arguments (successors).
278                let mut output_edges: Vec<(&PortIndexValue, GraphNodeId)> = self
279                    .node_successors(node_id)
280                    .map(|(edge_id, succ)| (self.edge_ports(edge_id).0, succ))
281                    .collect();
282                // Ensure sorted by port index.
283                output_edges.sort();
284                let output_ports: Vec<PortIndexValue> = output_edges
285                    .into_iter()
286                    .map(|(port, _succ)| port)
287                    .cloned()
288                    .collect();
289
290                (input_ports, output_ports)
291            };
292
293            // Generic arguments.
294            let generics = get_operator_generics(diagnostics, operator);
295            // Generic argument errors.
296            {
297                // Span of `generic_args` (if it exists), otherwise span of the operator name.
298                let generics_span = generics
299                    .generic_args
300                    .as_ref()
301                    .map(Spanned::span)
302                    .unwrap_or_else(|| operator.path.span());
303
304                if !op_constraints
305                    .persistence_args
306                    .contains(&generics.persistence_args.len())
307                {
308                    diagnostics.push(Diagnostic::spanned(
309                        generics.persistence_args_span().unwrap_or(generics_span),
310                        Level::Error,
311                        format!(
312                            "`{}` should have {} persistence lifetime arguments, actually has {}.",
313                            op_constraints.name,
314                            op_constraints.persistence_args.human_string(),
315                            generics.persistence_args.len()
316                        ),
317                    ));
318                }
319                if !op_constraints.type_args.contains(&generics.type_args.len()) {
320                    diagnostics.push(Diagnostic::spanned(
321                        generics.type_args_span().unwrap_or(generics_span),
322                        Level::Error,
323                        format!(
324                            "`{}` should have {} generic type arguments, actually has {}.",
325                            op_constraints.name,
326                            op_constraints.type_args.human_string(),
327                            generics.type_args.len()
328                        ),
329                    ));
330                }
331            }
332
333            op_insts.push((
334                node_id,
335                OperatorInstance {
336                    op_constraints,
337                    input_ports,
338                    output_ports,
339                    singletons_referenced: operator.singletons_referenced.clone(),
340                    generics,
341                    arguments_pre: operator.args.clone(),
342                    arguments_raw: operator.args_raw.clone(),
343                },
344            ));
345        }
346
347        for (node_id, op_inst) in op_insts {
348            self.insert_node_op_inst(node_id, op_inst);
349        }
350    }
351
352    /// Inserts a node between two existing nodes connected by the given `edge_id`.
353    ///
354    /// `edge`: (src, dst, dst_idx)
355    ///
356    /// Before: A (src) ------------> B (dst)
357    /// After:  A (src) -> X (new) -> B (dst)
358    ///
359    /// Returns the ID of X & ID of edge OUT of X.
360    ///
361    /// Note that both the edges will be new and `edge_id` will be removed. Both new edges will
362    /// get the edge type of the original edge.
363    pub fn insert_intermediate_node(
364        &mut self,
365        edge_id: GraphEdgeId,
366        new_node: GraphNode,
367    ) -> (GraphNodeId, GraphEdgeId) {
368        let span = Some(new_node.span());
369
370        // Make corresponding operator instance (if `node` is an operator).
371        let op_inst_opt = 'oc: {
372            let GraphNode::Operator(operator) = &new_node else {
373                break 'oc None;
374            };
375            let Some(op_constraints) = find_op_op_constraints(operator) else {
376                break 'oc None;
377            };
378            let (input_port, output_port) = self.ports.get(edge_id).cloned().unwrap();
379
380            let mut dummy_diagnostics = Diagnostics::new();
381            let generics = get_operator_generics(&mut dummy_diagnostics, operator);
382            assert!(dummy_diagnostics.is_empty());
383
384            Some(OperatorInstance {
385                op_constraints,
386                input_ports: vec![input_port],
387                output_ports: vec![output_port],
388                singletons_referenced: operator.singletons_referenced.clone(),
389                generics,
390                arguments_pre: operator.args.clone(),
391                arguments_raw: operator.args_raw.clone(),
392            })
393        };
394
395        // Insert new `node`.
396        let node_id = self.nodes.insert(new_node);
397        // Insert corresponding `OperatorInstance` if applicable.
398        if let Some(op_inst) = op_inst_opt {
399            self.operator_instances.insert(node_id, op_inst);
400        }
401        // Update edges to insert node within `edge_id`.
402        let (e0, e1) = self
403            .graph
404            .insert_intermediate_vertex(node_id, edge_id)
405            .unwrap();
406
407        // Update corresponding ports.
408        let (src_idx, dst_idx) = self.ports.remove(edge_id).unwrap();
409        self.ports
410            .insert(e0, (src_idx, PortIndexValue::Elided(span)));
411        self.ports
412            .insert(e1, (PortIndexValue::Elided(span), dst_idx));
413
414        (node_id, e1)
415    }
416
417    /// Remove the node `node_id` but preserves and connects the single predecessor and single successor.
418    /// Panics if the node does not have exactly one predecessor and one successor, or is not in the graph.
419    pub fn remove_intermediate_node(&mut self, node_id: GraphNodeId) {
420        assert_eq!(
421            1,
422            self.node_degree_in(node_id),
423            "Removed intermediate node must have one predecessor"
424        );
425        assert_eq!(
426            1,
427            self.node_degree_out(node_id),
428            "Removed intermediate node must have one successor"
429        );
430        assert!(
431            self.node_subgraph.is_empty() && self.subgraph_nodes.is_empty(),
432            "Should not remove intermediate node after subgraph partitioning"
433        );
434
435        assert!(self.nodes.remove(node_id).is_some());
436        let (new_edge_id, (pred_edge_id, succ_edge_id)) =
437            self.graph.remove_intermediate_vertex(node_id).unwrap();
438        self.operator_instances.remove(node_id);
439        self.node_varnames.remove(node_id);
440
441        let (src_port, _) = self.ports.remove(pred_edge_id).unwrap();
442        let (_, dst_port) = self.ports.remove(succ_edge_id).unwrap();
443        self.ports.insert(new_edge_id, (src_port, dst_port));
444    }
445
446    /// Helper method: determine the "color" (pull vs push) of a node based on its in and out degree,
447    /// excluding reference edges. If linear (1 in, 1 out), color is `None`, indicating it can be
448    /// either push or pull.
449    ///
450    /// Note that this does NOT consider `DelayType` barriers (which generally implies `Pull`).
451    pub(crate) fn node_color(&self, node_id: GraphNodeId) -> Option<Color> {
452        if matches!(self.node(node_id), GraphNode::Handoff { .. }) {
453            return Some(Color::Hoff);
454        }
455
456        // TODO(shadaj): this is a horrible hack
457        if let GraphNode::Operator(op) = self.node(node_id)
458            && (op.name_string() == "resolve_futures_blocking"
459                || op.name_string() == "resolve_futures_blocking_ordered")
460        {
461            return Some(Color::Push);
462        }
463
464        // In-degree, excluding ref-edges.
465        let inn_degree = self.node_predecessor_nodes(node_id).len();
466        // Out-degree excluding ref-edges.
467        let out_degree = self.node_successor_nodes(node_id).len();
468
469        match (inn_degree, out_degree) {
470            (0, 0) => None, // Generally should not happen, "Degenerate subgraph detected".
471            (0, 1) => Some(Color::Pull),
472            (1, 0) => Some(Color::Push),
473            (1, 1) => None, // Linear, can be either push or pull.
474            (_many, 0 | 1) => Some(Color::Pull),
475            (0 | 1, _many) => Some(Color::Push),
476            (_many, _to_many) => Some(Color::Comp),
477        }
478    }
479
480    /// Set the operator tag (for debugging/tracing).
481    pub fn set_operator_tag(&mut self, node_id: GraphNodeId, tag: String) {
482        self.operator_tag.insert(node_id, tag);
483    }
484}
485
486/// Singleton references.
487impl DfirGraph {
488    /// Set the singletons referenced for the `node_id` operator. Each reference corresponds to the
489    /// same index in the [`crate::parse::Operator::singletons_referenced`] vec.
490    pub fn set_node_singleton_references(
491        &mut self,
492        node_id: GraphNodeId,
493        singletons_referenced: Vec<Option<GraphNodeId>>,
494    ) -> Option<Vec<Option<GraphNodeId>>> {
495        self.node_singleton_references
496            .insert(node_id, singletons_referenced)
497    }
498
499    /// Gets the singletons referenced by a node. Returns an empty iterator for non-operators and
500    /// operators that do not reference singletons.
501    pub fn node_singleton_references(&self, node_id: GraphNodeId) -> &[Option<GraphNodeId>] {
502        self.node_singleton_references
503            .get(node_id)
504            .map(std::ops::Deref::deref)
505            .unwrap_or_default()
506    }
507}
508
509/// Module methods.
510impl DfirGraph {
511    /// When modules are imported into a flat graph, they come with an input and output ModuleBoundary node.
512    /// The partitioner doesn't understand these nodes and will panic if it encounters them.
513    /// merge_modules removes them from the graph, stitching the input and ouput sides of the ModuleBondaries based on their ports
514    /// For example:
515    ///     source_iter([]) -> \[myport\]ModuleBoundary(input)\[my_port\] -> map(|x| x) -> ModuleBoundary(output) -> null();
516    /// in the above eaxmple, the \[myport\] port will be used to connect the source_iter with the map that is inside of the module.
517    /// The output module boundary has elided ports, this is also used to match up the input/output across the module boundary.
518    pub fn merge_modules(&mut self) -> Result<(), Diagnostic> {
519        let mod_bound_nodes = self
520            .nodes()
521            .filter(|(_nid, node)| matches!(node, GraphNode::ModuleBoundary { .. }))
522            .map(|(nid, _node)| nid)
523            .collect::<Vec<_>>();
524
525        for mod_bound_node in mod_bound_nodes {
526            self.remove_module_boundary(mod_bound_node)?;
527        }
528
529        Ok(())
530    }
531
532    /// see `merge_modules`
533    /// This function removes a singular module boundary from the graph and performs the necessary stitching to fix the graph afterward.
534    /// `merge_modules` calls this function for each module boundary in the graph.
535    fn remove_module_boundary(&mut self, mod_bound_node: GraphNodeId) -> Result<(), Diagnostic> {
536        assert!(
537            self.node_subgraph.is_empty() && self.subgraph_nodes.is_empty(),
538            "Should not remove intermediate node after subgraph partitioning"
539        );
540
541        let mut mod_pred_ports = BTreeMap::new();
542        let mut mod_succ_ports = BTreeMap::new();
543
544        for mod_out_edge in self.node_predecessor_edges(mod_bound_node) {
545            let (pred_port, succ_port) = self.edge_ports(mod_out_edge);
546            mod_pred_ports.insert(succ_port.clone(), (mod_out_edge, pred_port.clone()));
547        }
548
549        for mod_inn_edge in self.node_successor_edges(mod_bound_node) {
550            let (pred_port, succ_port) = self.edge_ports(mod_inn_edge);
551            mod_succ_ports.insert(pred_port.clone(), (mod_inn_edge, succ_port.clone()));
552        }
553
554        if mod_pred_ports.keys().collect::<BTreeSet<_>>()
555            != mod_succ_ports.keys().collect::<BTreeSet<_>>()
556        {
557            // get module boundary node
558            let GraphNode::ModuleBoundary { input, import_expr } = self.node(mod_bound_node) else {
559                panic!();
560            };
561
562            if *input {
563                return Err(Diagnostic {
564                    span: *import_expr,
565                    level: Level::Error,
566                    message: format!(
567                        "The ports into the module did not match. input: {:?}, expected: {:?}",
568                        mod_pred_ports.keys().map(|x| x.to_string()).join(", "),
569                        mod_succ_ports.keys().map(|x| x.to_string()).join(", ")
570                    ),
571                });
572            } else {
573                return Err(Diagnostic {
574                    span: *import_expr,
575                    level: Level::Error,
576                    message: format!(
577                        "The ports out of the module did not match. output: {:?}, expected: {:?}",
578                        mod_succ_ports.keys().map(|x| x.to_string()).join(", "),
579                        mod_pred_ports.keys().map(|x| x.to_string()).join(", "),
580                    ),
581                });
582            }
583        }
584
585        for (port, (pred_edge, pred_port)) in mod_pred_ports {
586            let (succ_edge, succ_port) = mod_succ_ports.remove(&port).unwrap();
587
588            let (src, _) = self.edge(pred_edge);
589            let (_, dst) = self.edge(succ_edge);
590            self.remove_edge(pred_edge);
591            self.remove_edge(succ_edge);
592
593            let new_edge_id = self.graph.insert_edge(src, dst);
594            self.ports.insert(new_edge_id, (pred_port, succ_port));
595        }
596
597        self.graph.remove_vertex(mod_bound_node);
598        self.nodes.remove(mod_bound_node);
599
600        Ok(())
601    }
602}
603
604/// Edge methods.
605impl DfirGraph {
606    /// Get the `src` and `dst` for an edge: `(src GraphNodeId, dst GraphNodeId)`.
607    pub fn edge(&self, edge_id: GraphEdgeId) -> (GraphNodeId, GraphNodeId) {
608        let (src, dst) = self.graph.edge(edge_id).expect("Edge not found.");
609        (src, dst)
610    }
611
612    /// Get the source and destination ports for an edge: `(src &PortIndexValue, dst &PortIndexValue)`.
613    pub fn edge_ports(&self, edge_id: GraphEdgeId) -> (&PortIndexValue, &PortIndexValue) {
614        let (src_port, dst_port) = self.ports.get(edge_id).expect("Edge not found.");
615        (src_port, dst_port)
616    }
617
618    /// Iterator of all edge IDs `GraphEdgeId`.
619    pub fn edge_ids(&self) -> slotmap::basic::Keys<'_, GraphEdgeId, (GraphNodeId, GraphNodeId)> {
620        self.graph.edge_ids()
621    }
622
623    /// Iterator over all edges: `(GraphEdgeId, (src GraphNodeId, dst GraphNodeId))`.
624    pub fn edges(
625        &self,
626    ) -> impl '_
627    + ExactSizeIterator<Item = (GraphEdgeId, (GraphNodeId, GraphNodeId))>
628    + FusedIterator
629    + Clone
630    + Debug {
631        self.graph.edges()
632    }
633
634    /// Insert an edge between nodes thru the given ports.
635    pub fn insert_edge(
636        &mut self,
637        src: GraphNodeId,
638        src_port: PortIndexValue,
639        dst: GraphNodeId,
640        dst_port: PortIndexValue,
641    ) -> GraphEdgeId {
642        let edge_id = self.graph.insert_edge(src, dst);
643        self.ports.insert(edge_id, (src_port, dst_port));
644        edge_id
645    }
646
647    /// Removes an edge and its corresponding ports and edge type info.
648    pub fn remove_edge(&mut self, edge: GraphEdgeId) {
649        let (_src, _dst) = self.graph.remove_edge(edge).unwrap();
650        let (_src_port, _dst_port) = self.ports.remove(edge).unwrap();
651    }
652}
653
654/// Subgraph methods.
655impl DfirGraph {
656    /// Nodes belonging to the given subgraph.
657    pub fn subgraph(&self, subgraph_id: GraphSubgraphId) -> &Vec<GraphNodeId> {
658        self.subgraph_nodes
659            .get(subgraph_id)
660            .expect("Subgraph not found.")
661    }
662
663    /// Iterator over all subgraph IDs.
664    pub fn subgraph_ids(&self) -> slotmap::basic::Keys<'_, GraphSubgraphId, Vec<GraphNodeId>> {
665        self.subgraph_nodes.keys()
666    }
667
668    /// Iterator over all subgraphs, ID and members: `(GraphSubgraphId, Vec<GraphNodeId>)`.
669    pub fn subgraphs(&self) -> slotmap::basic::Iter<'_, GraphSubgraphId, Vec<GraphNodeId>> {
670        self.subgraph_nodes.iter()
671    }
672
673    /// Create a subgraph consisting of `node_ids`. Returns an error if any of the nodes are already in a subgraph.
674    pub fn insert_subgraph(
675        &mut self,
676        node_ids: Vec<GraphNodeId>,
677    ) -> Result<GraphSubgraphId, (GraphNodeId, GraphSubgraphId)> {
678        // Check none are already in subgraphs
679        for &node_id in node_ids.iter() {
680            if let Some(&old_sg_id) = self.node_subgraph.get(node_id) {
681                return Err((node_id, old_sg_id));
682            }
683        }
684        let subgraph_id = self.subgraph_nodes.insert_with_key(|sg_id| {
685            for &node_id in node_ids.iter() {
686                self.node_subgraph.insert(node_id, sg_id);
687            }
688            node_ids
689        });
690
691        Ok(subgraph_id)
692    }
693
694    /// Removes a node from its subgraph. Returns true if the node was in a subgraph.
695    pub fn remove_from_subgraph(&mut self, node_id: GraphNodeId) -> bool {
696        if let Some(old_sg_id) = self.node_subgraph.remove(node_id) {
697            self.subgraph_nodes[old_sg_id].retain(|&other_node_id| other_node_id != node_id);
698            true
699        } else {
700            false
701        }
702    }
703
704    /// Gets the delay type for a handoff node, if set.
705    pub fn handoff_delay_type(&self, node_id: GraphNodeId) -> Option<DelayType> {
706        self.handoff_delay_type.get(node_id).copied()
707    }
708
709    /// Sets the delay type for a handoff node.
710    pub fn set_handoff_delay_type(&mut self, node_id: GraphNodeId, delay_type: DelayType) {
711        self.handoff_delay_type.insert(node_id, delay_type);
712    }
713
714    /// Helper: finds the first index in `subgraph_nodes` where it transitions from pull to push.
715    fn find_pull_to_push_idx(&self, subgraph_nodes: &[GraphNodeId]) -> usize {
716        subgraph_nodes
717            .iter()
718            .position(|&node_id| {
719                self.node_color(node_id)
720                    .is_some_and(|color| Color::Pull != color)
721            })
722            .unwrap_or(subgraph_nodes.len())
723    }
724}
725
726/// Display/output methods.
727impl DfirGraph {
728    /// Helper to generate a deterministic `Ident` for the given node.
729    fn node_as_ident(&self, node_id: GraphNodeId, is_pred: bool) -> Ident {
730        let name = match &self.nodes[node_id] {
731            GraphNode::Operator(_) => format!("op_{:?}", node_id.data()),
732            GraphNode::Handoff { .. } => format!(
733                "hoff_{:?}_{}",
734                node_id.data(),
735                if is_pred { "recv" } else { "send" }
736            ),
737            GraphNode::ModuleBoundary { .. } => panic!(),
738        };
739        let span = match (is_pred, &self.nodes[node_id]) {
740            (_, GraphNode::Operator(operator)) => operator.span(),
741            (true, &GraphNode::Handoff { src_span, .. }) => src_span,
742            (false, &GraphNode::Handoff { dst_span, .. }) => dst_span,
743            (_, GraphNode::ModuleBoundary { .. }) => panic!(),
744        };
745        Ident::new(&name, span)
746    }
747
748    /// For per-node singleton references. Helper to generate a deterministic `Ident` for the given node.
749    fn node_as_singleton_ident(&self, node_id: GraphNodeId, span: Span) -> Ident {
750        Ident::new(&format!("singleton_op_{:?}", node_id.data()), span)
751    }
752
753    /// Resolve the singletons via [`Self::node_singleton_references`] for the given `node_id`.
754    fn helper_resolve_singletons(&self, node_id: GraphNodeId, span: Span) -> Vec<Ident> {
755        self.node_singleton_references(node_id)
756            .iter()
757            .map(|singleton_node_id| {
758                // TODO(mingwei): this `expect` should be caught in error checking
759                self.node_as_singleton_ident(
760                    singleton_node_id
761                        .expect("Expected singleton to be resolved but was not, this is a bug."),
762                    span,
763                )
764            })
765            .collect::<Vec<_>>()
766    }
767
768    /// Returns each subgraph's receive and send handoffs.
769    /// `Map<GraphSubgraphId, (recv handoffs, send handoffs)>`
770    fn helper_collect_subgraph_handoffs(
771        &self,
772    ) -> SecondaryMap<GraphSubgraphId, (Vec<GraphNodeId>, Vec<GraphNodeId>)> {
773        // Get data on handoff src and dst subgraphs.
774        let mut subgraph_handoffs: SecondaryMap<
775            GraphSubgraphId,
776            (Vec<GraphNodeId>, Vec<GraphNodeId>),
777        > = self
778            .subgraph_nodes
779            .keys()
780            .map(|k| (k, Default::default()))
781            .collect();
782
783        // For each handoff node, add it to the `send`/`recv` lists for the corresponding subgraphs.
784        for (hoff_id, node) in self.nodes() {
785            if !matches!(node, GraphNode::Handoff { .. }) {
786                continue;
787            }
788            // Receivers from the handoff. (Should really only be one).
789            for (_edge, succ_id) in self.node_successors(hoff_id) {
790                let succ_sg = self.node_subgraph(succ_id).unwrap();
791                subgraph_handoffs[succ_sg].0.push(hoff_id);
792            }
793            // Senders into the handoff. (Should really only be one).
794            for (_edge, pred_id) in self.node_predecessors(hoff_id) {
795                let pred_sg = self.node_subgraph(pred_id).unwrap();
796                subgraph_handoffs[pred_sg].1.push(hoff_id);
797            }
798        }
799
800        subgraph_handoffs
801    }
802
803    /// Emit this graph as runnable Rust source code tokens that execute inline.
804    /// Generates a flat `async move |df: &mut Context|` closure where subgraph
805    /// blocks are inlined in topological order, using local `Vec<T>` buffers
806    /// instead of runtime handoffs. Each call to the closure runs one tick.
807    ///
808    /// The generated code block evaluates to a `Dfir` instance wrapping the
809    /// closure. Operator prologues (`add_state`, `set_state_lifespan_hook`)
810    /// run at construction time on the `Context` before it is moved into
811    /// `Dfir::new`. `Dfir` provides the `Context` to the closure on
812    /// each tick run.
813    ///
814    /// # Errors
815    ///
816    /// Returns all diagnostics as `Err(diagnostics)` if any are errors
817    /// (leaving `&mut diagnostics` empty).
818    pub fn as_code(
819        &self,
820        root: &TokenStream,
821        include_type_guards: bool,
822        prefix: TokenStream,
823        diagnostics: &mut Diagnostics,
824    ) -> Result<TokenStream, Diagnostics> {
825        // Extract the slot index from a slotmap key for use as a runtime metrics key.
826        // Uses the low 32 bits of `KeyData::as_ffi()` (the idx, ignoring the version).
827        // TODO(cleanup): When scheduled Dfir is removed, DfirMetrics could use slotmap
828        // SecondaryMaps directly, eliminating this conversion.
829        fn slotmap_raw_idx(key: impl Key) -> usize {
830            (key.data().as_ffi() & 0xFFFF_FFFF) as usize
831        }
832
833        let df = Ident::new(GRAPH, Span::call_site());
834        let context = Ident::new(CONTEXT, Span::call_site());
835
836        // 1. Generate local Vec buffers for each handoff node.
837        let handoff_nodes: Vec<_> = self
838            .nodes
839            .iter()
840            .filter_map(|(node_id, node)| match node {
841                GraphNode::Operator(_) => None,
842                &GraphNode::Handoff { src_span, dst_span } => Some((node_id, (src_span, dst_span))),
843                GraphNode::ModuleBoundary { .. } => panic!(),
844            })
845            .collect();
846
847        let buffer_code: Vec<TokenStream> = handoff_nodes
848            .iter()
849            .map(|&(node_id, (src_span, dst_span))| {
850                let span = src_span.join(dst_span).unwrap_or(src_span);
851                let buf_ident = Ident::new(&format!("hoff_{:?}_buf", node_id.data()), span);
852                quote_spanned! {span=>
853                    let mut #buf_ident: Vec<_> = Vec::new();
854                }
855            })
856            .collect();
857
858        // 2. Collect subgraph handoffs (same as as_code).
859        let subgraph_handoffs = self.helper_collect_subgraph_handoffs();
860
861        // 3. Sort subgraphs topologically and collect non-lazy defer_tick buffer idents.
862        //
863        // Handoffs marked with a `DelayType` (Tick/TickLazy) are tick-boundary back-edges.
864        // For these, we reverse the ordering constraint (producer runs after consumer) to
865        // preserve the required same-tick ordering. Unmarked handoffs are forward edges.
866        //
867        // While iterating handoffs, we also collect buffer idents for non-lazy tick-boundary
868        // edges (defer_tick). When these buffers are non-empty at end of tick, we set
869        // can_start_tick so that run_available continues ticking.
870        let mut defer_tick_buf_idents: Vec<Ident> = Vec::new();
871        let all_subgraphs = {
872            // Build predecessor map for subgraphs.
873            let mut sg_preds = SecondaryMap::<_, Vec<_>>::with_capacity(self.subgraph_nodes.len());
874            for (hoff_id, node) in self.nodes() {
875                if !matches!(node, GraphNode::Handoff { .. }) {
876                    // Not a handoff; skip.
877                    continue;
878                }
879                assert_eq!(1, self.node_successors(hoff_id).len());
880                assert_eq!(1, self.node_predecessors(hoff_id).len());
881                let (_edge_id, pred) = self.node_predecessors(hoff_id).next().unwrap();
882                let (_edge_id, succ) = self.node_successors(hoff_id).next().unwrap();
883                let pred_sg = self.node_subgraph(pred).unwrap();
884                let succ_sg = self.node_subgraph(succ).unwrap();
885                if pred_sg == succ_sg {
886                    panic!("bug: unexpected subgraph self-handoff cycle");
887                }
888                if let Some(delay_type) = self.handoff_delay_type(hoff_id) {
889                    debug_assert!(matches!(delay_type, DelayType::Tick | DelayType::TickLazy));
890                    // Tick/back-edge handoff: preserve the required same-tick ordering by
891                    // forcing the higher-order producer subgraph to run after the
892                    // lower-order consumer subgraph.
893                    sg_preds.entry(pred_sg).unwrap().or_default().push(succ_sg);
894
895                    // Non-lazy tick-boundary: defer_tick (not defer_tick_lazy).
896                    if !matches!(delay_type, DelayType::TickLazy) {
897                        defer_tick_buf_idents.push(Ident::new(
898                            &format!("hoff_{:?}_buf", hoff_id.data()),
899                            node.span(),
900                        ));
901                    }
902                } else {
903                    sg_preds.entry(succ_sg).unwrap().or_default().push(pred_sg);
904                }
905            }
906
907            // Include singleton reference edges: if node A references the
908            // singleton output of node B, then A's subgraph must run after B's.
909            for dst_id in self.node_ids() {
910                for src_ref_id in self
911                    .node_singleton_references(dst_id)
912                    .iter()
913                    .copied()
914                    .flatten()
915                {
916                    let src_sg = self
917                        .node_subgraph(src_ref_id)
918                        .expect("bug: singleton ref node must belong to a subgraph");
919                    let dst_sg = self
920                        .node_subgraph(dst_id)
921                        .expect("bug: singleton ref consumer must belong to a subgraph");
922                    if src_sg != dst_sg {
923                        sg_preds.entry(dst_sg).unwrap().or_default().push(src_sg);
924                    }
925                }
926            }
927
928            let topo_sort = super::graph_algorithms::topo_sort(self.subgraph_ids(), |sg_id| {
929                sg_preds.get(sg_id).into_iter().flatten().copied()
930            })
931            .expect("bug: unexpected cycle between subgraphs within the tick");
932
933            topo_sort
934                .into_iter()
935                .map(|sg_id| (sg_id, self.subgraph(sg_id)))
936                .collect::<Vec<_>>()
937        };
938
939        let mut op_prologue_code = Vec::new();
940        let mut op_prologue_after_code = Vec::new();
941        let mut subgraph_blocks = Vec::new();
942        {
943            for &(subgraph_id, subgraph_nodes) in all_subgraphs.iter() {
944                let sg_metrics_idx = slotmap_raw_idx(subgraph_id);
945                let (recv_hoffs, send_hoffs) = &subgraph_handoffs[subgraph_id];
946
947                // Generate buffer ident helpers for this subgraph's handoffs.
948                let recv_port_idents: Vec<Ident> = recv_hoffs
949                    .iter()
950                    .map(|&hoff_id| self.node_as_ident(hoff_id, true))
951                    .collect();
952                let send_port_idents: Vec<Ident> = send_hoffs
953                    .iter()
954                    .map(|&hoff_id| self.node_as_ident(hoff_id, false))
955                    .collect();
956
957                // Map handoff node IDs to buffer idents.
958                let recv_buf_idents: Vec<Ident> = recv_hoffs
959                    .iter()
960                    .map(|&hoff_id| {
961                        let span = self.nodes[hoff_id].span();
962                        Ident::new(&format!("hoff_{:?}_buf", hoff_id.data()), span)
963                    })
964                    .collect();
965                let send_buf_idents: Vec<Ident> = send_hoffs
966                    .iter()
967                    .map(|&hoff_id| {
968                        let span = self.nodes[hoff_id].span();
969                        Ident::new(&format!("hoff_{:?}_buf", hoff_id.data()), span)
970                    })
971                    .collect();
972
973                // Recv port code: drain from buffer into iterator, tracking if non-empty.
974                // Also update handoff metrics (measured at recv, not send — see graph.rs).
975                let recv_port_code: Vec<TokenStream> = recv_port_idents
976                    .iter()
977                    .zip(recv_buf_idents.iter())
978                    .zip(recv_hoffs.iter())
979                    .map(|((port_ident, buf_ident), &hoff_id)| {
980                        let hoff_idx = slotmap_raw_idx(hoff_id);
981                        // Use call_site span for internal identifiers to avoid
982                        // hygiene issues when invoked through declarative macros
983                        // (e.g. dfir_expect_warnings!). TODO(#2781): define these once.
984                        let work_done = Ident::new("__dfir_work_done", Span::call_site());
985                        let metrics = Ident::new("__dfir_metrics", Span::call_site());
986                        quote_spanned! {port_ident.span()=>
987                            {
988                                let hoff_len = #buf_ident.len();
989                                if hoff_len > 0 {
990                                    #work_done = true;
991                                }
992                                let hoff_metrics = &#metrics.handoffs[
993                                    #root::util::slot_vec::Key::<#root::scheduled::HandoffTag>::from_raw(#hoff_idx)
994                                ];
995                                hoff_metrics.total_items_count.update(|x| x + hoff_len);
996                                hoff_metrics.curr_items_count.set(hoff_len);
997                            }
998                            let #port_ident = #root::dfir_pipes::pull::iter(#buf_ident.drain(..));
999                        }
1000                    })
1001                    .collect();
1002
1003                // Send port code: push into buffer.
1004                let send_port_code: Vec<TokenStream> = send_port_idents
1005                    .iter()
1006                    .zip(send_buf_idents.iter())
1007                    .map(|(port_ident, buf_ident)| {
1008                        quote_spanned! {port_ident.span()=>
1009                            let #port_ident = #root::dfir_pipes::push::vec_push(&mut #buf_ident);
1010                        }
1011                    })
1012                    .collect();
1013
1014                // All nodes in a subgraph should be in the same loop.
1015                let loop_id = self.node_loop(subgraph_nodes[0]);
1016
1017                let mut subgraph_op_iter_code = Vec::new();
1018                let mut subgraph_op_iter_after_code = Vec::new();
1019                {
1020                    let pull_to_push_idx = self.find_pull_to_push_idx(subgraph_nodes);
1021
1022                    let (pull_half, push_half) = subgraph_nodes.split_at(pull_to_push_idx);
1023                    let nodes_iter = pull_half.iter().chain(push_half.iter().rev());
1024
1025                    for (idx, &node_id) in nodes_iter.enumerate() {
1026                        let node = &self.nodes[node_id];
1027                        assert!(
1028                            matches!(node, GraphNode::Operator(_)),
1029                            "Handoffs are not part of subgraphs."
1030                        );
1031                        let op_inst = &self.operator_instances[node_id];
1032
1033                        let op_span = node.span();
1034                        let op_name = op_inst.op_constraints.name;
1035                        // Use op's span for root. #root is expected to be correct, any errors should span back to the op gen.
1036                        let root = change_spans(root.clone(), op_span);
1037                        let op_constraints = OPERATORS
1038                            .iter()
1039                            .find(|op| op_name == op.name)
1040                            .unwrap_or_else(|| panic!("Failed to find op: {}", op_name));
1041
1042                        let ident = self.node_as_ident(node_id, false);
1043
1044                        {
1045                            // TODO clean this up.
1046                            // Collect input arguments (predecessors).
1047                            let mut input_edges = self
1048                                .graph
1049                                .predecessor_edges(node_id)
1050                                .map(|edge_id| (self.edge_ports(edge_id).1, edge_id))
1051                                .collect::<Vec<_>>();
1052                            // Ensure sorted by port index.
1053                            input_edges.sort();
1054
1055                            let inputs = input_edges
1056                                .iter()
1057                                .map(|&(_port, edge_id)| {
1058                                    let (pred, _) = self.edge(edge_id);
1059                                    self.node_as_ident(pred, true)
1060                                })
1061                                .collect::<Vec<_>>();
1062
1063                            // Collect output arguments (successors).
1064                            let mut output_edges = self
1065                                .graph
1066                                .successor_edges(node_id)
1067                                .map(|edge_id| (&self.ports[edge_id].0, edge_id))
1068                                .collect::<Vec<_>>();
1069                            // Ensure sorted by port index.
1070                            output_edges.sort();
1071
1072                            let outputs = output_edges
1073                                .iter()
1074                                .map(|&(_port, edge_id)| {
1075                                    let (_, succ) = self.edge(edge_id);
1076                                    self.node_as_ident(succ, false)
1077                                })
1078                                .collect::<Vec<_>>();
1079
1080                            let is_pull = idx < pull_to_push_idx;
1081
1082                            let singleton_output_ident = &if op_constraints.has_singleton_output {
1083                                self.node_as_singleton_ident(node_id, op_span)
1084                            } else {
1085                                // This ident *should* go unused.
1086                                Ident::new(&format!("{}_has_no_singleton_output", op_name), op_span)
1087                            };
1088
1089                            // There's a bit of dark magic hidden in `Span`s... you'd think it's just a `file:line:column`,
1090                            // but it has one extra bit of info for _name resolution_, used for `Ident`s. `Span::call_site()`
1091                            // has the (unhygienic) resolution we want, an ident is just solely determined by its string name,
1092                            // which is what you'd expect out of unhygienic proc macros like this. Meanwhile, declarative macros
1093                            // use `Span::mixed_site()` which is weird and I don't understand it. It turns out that if you call
1094                            // the dfir syntax proc macro from _within_ a declarative macro then `op_span` will have the
1095                            // bad `Span::mixed_site()` name resolution and cause "Cannot find value `df/context`" errors. So
1096                            // we call `.resolved_at()` to fix resolution back to `Span::call_site()`. -Mingwei
1097                            let df_local = &Ident::new(GRAPH, op_span.resolved_at(df.span()));
1098                            let context = &Ident::new(CONTEXT, op_span.resolved_at(context.span()));
1099
1100                            let singletons_resolved =
1101                                self.helper_resolve_singletons(node_id, op_span);
1102                            let arguments = &process_singletons::postprocess_singletons(
1103                                op_inst.arguments_raw.clone(),
1104                                singletons_resolved.clone(),
1105                                context,
1106                            );
1107                            let arguments_handles =
1108                                &process_singletons::postprocess_singletons_handles(
1109                                    op_inst.arguments_raw.clone(),
1110                                    singletons_resolved.clone(),
1111                                );
1112
1113                            let source_tag = 'a: {
1114                                if let Some(tag) = self.operator_tag.get(node_id).cloned() {
1115                                    break 'a tag;
1116                                }
1117
1118                                #[cfg(nightly)]
1119                                if proc_macro::is_available() {
1120                                    let op_span = op_span.unwrap();
1121                                    break 'a format!(
1122                                        "loc_{}_{}_{}_{}_{}",
1123                                        crate::pretty_span::make_source_path_relative(
1124                                            &op_span.file()
1125                                        )
1126                                        .display()
1127                                        .to_string()
1128                                        .replace(|x: char| !x.is_ascii_alphanumeric(), "_"),
1129                                        op_span.start().line(),
1130                                        op_span.start().column(),
1131                                        op_span.end().line(),
1132                                        op_span.end().column(),
1133                                    );
1134                                }
1135
1136                                format!(
1137                                    "loc_nopath_{}_{}_{}_{}",
1138                                    op_span.start().line,
1139                                    op_span.start().column,
1140                                    op_span.end().line,
1141                                    op_span.end().column
1142                                )
1143                            };
1144
1145                            let work_fn = format_ident!(
1146                                "{}__{}__{}",
1147                                ident,
1148                                op_name,
1149                                source_tag,
1150                                span = op_span
1151                            );
1152                            let work_fn_async = format_ident!("{}__async", work_fn, span = op_span);
1153
1154                            let context_args = WriteContextArgs {
1155                                root: &root,
1156                                df_ident: df_local,
1157                                context,
1158                                subgraph_id,
1159                                node_id,
1160                                loop_id,
1161                                op_span,
1162                                op_tag: self.operator_tag.get(node_id).cloned(),
1163                                work_fn: &work_fn,
1164                                work_fn_async: &work_fn_async,
1165                                ident: &ident,
1166                                is_pull,
1167                                inputs: &inputs,
1168                                outputs: &outputs,
1169                                singleton_output_ident,
1170                                op_name,
1171                                op_inst,
1172                                arguments,
1173                                arguments_handles,
1174                            };
1175
1176                            let write_result =
1177                                (op_constraints.write_fn)(&context_args, diagnostics);
1178                            let OperatorWriteOutput {
1179                                write_prologue,
1180                                write_prologue_after,
1181                                write_iterator,
1182                                write_iterator_after,
1183                            } = write_result.unwrap_or_else(|()| {
1184                                assert!(
1185                                    diagnostics.has_error(),
1186                                    "Operator `{}` returned `Err` but emitted no diagnostics, this is a bug.",
1187                                    op_name,
1188                                );
1189                                OperatorWriteOutput {
1190                                    write_iterator: null_write_iterator_fn(&context_args),
1191                                    ..Default::default()
1192                                }
1193                            });
1194
1195                            op_prologue_code.push(syn::parse_quote! {
1196                                #[allow(non_snake_case)]
1197                                #[inline(always)]
1198                                fn #work_fn<T>(thunk: impl ::std::ops::FnOnce() -> T) -> T {
1199                                    thunk()
1200                                }
1201
1202                                #[allow(non_snake_case)]
1203                                #[inline(always)]
1204                                async fn #work_fn_async<T>(
1205                                    thunk: impl ::std::future::Future<Output = T>,
1206                                ) -> T {
1207                                    thunk.await
1208                                }
1209                            });
1210                            op_prologue_code.push(write_prologue);
1211                            op_prologue_after_code.push(write_prologue_after);
1212                            subgraph_op_iter_code.push(write_iterator);
1213
1214                            if include_type_guards {
1215                                let type_guard = if is_pull {
1216                                    quote_spanned! {op_span=>
1217                                        let #ident = {
1218                                            #[allow(non_snake_case)]
1219                                            #[inline(always)]
1220                                            pub fn #work_fn<Item, Input>(input: Input)
1221                                                -> impl #root::dfir_pipes::pull::Pull<Item = Item, Meta = (), CanPend = Input::CanPend, CanEnd = Input::CanEnd>
1222                                            where
1223                                                Input: #root::dfir_pipes::pull::Pull<Item = Item, Meta = ()>,
1224                                            {
1225                                                #root::pin_project_lite::pin_project! {
1226                                                    #[repr(transparent)]
1227                                                    struct Pull<Item, Input: #root::dfir_pipes::pull::Pull<Item = Item>> {
1228                                                        #[pin]
1229                                                        inner: Input
1230                                                    }
1231                                                }
1232
1233                                                impl<Item, Input> #root::dfir_pipes::pull::Pull for Pull<Item, Input>
1234                                                where
1235                                                    Input: #root::dfir_pipes::pull::Pull<Item = Item>,
1236                                                {
1237                                                    type Ctx<'ctx> = Input::Ctx<'ctx>;
1238
1239                                                    type Item = Item;
1240                                                    type Meta = Input::Meta;
1241                                                    type CanPend = Input::CanPend;
1242                                                    type CanEnd = Input::CanEnd;
1243
1244                                                    #[inline(always)]
1245                                                    fn pull(
1246                                                        self: ::std::pin::Pin<&mut Self>,
1247                                                        ctx: &mut Self::Ctx<'_>,
1248                                                    ) -> #root::dfir_pipes::pull::PullStep<Self::Item, Self::Meta, Self::CanPend, Self::CanEnd> {
1249                                                        #root::dfir_pipes::pull::Pull::pull(self.project().inner, ctx)
1250                                                    }
1251
1252                                                    #[inline(always)]
1253                                                    fn size_hint(&self) -> (usize, Option<usize>) {
1254                                                        #root::dfir_pipes::pull::Pull::size_hint(&self.inner)
1255                                                    }
1256                                                }
1257
1258                                                Pull {
1259                                                    inner: input
1260                                                }
1261                                            }
1262                                            #work_fn::<_, _>( #ident )
1263                                        };
1264                                    }
1265                                } else {
1266                                    quote_spanned! {op_span=>
1267                                        let #ident = {
1268                                            #[allow(non_snake_case)]
1269                                            #[inline(always)]
1270                                            pub fn #work_fn<Item, Psh>(psh: Psh) -> impl #root::dfir_pipes::push::Push<Item, (), CanPend = Psh::CanPend>
1271                                            where
1272                                                Psh: #root::dfir_pipes::push::Push<Item, ()>
1273                                            {
1274                                                #root::pin_project_lite::pin_project! {
1275                                                    #[repr(transparent)]
1276                                                    struct PushGuard<Psh> {
1277                                                        #[pin]
1278                                                        inner: Psh,
1279                                                    }
1280                                                }
1281
1282                                                impl<Item, Psh> #root::dfir_pipes::push::Push<Item, ()> for PushGuard<Psh>
1283                                                where
1284                                                    Psh: #root::dfir_pipes::push::Push<Item, ()>,
1285                                                {
1286                                                    type Ctx<'ctx> = Psh::Ctx<'ctx>;
1287
1288                                                    type CanPend = Psh::CanPend;
1289
1290                                                    #[inline(always)]
1291                                                    fn poll_ready(
1292                                                        self: ::std::pin::Pin<&mut Self>,
1293                                                        ctx: &mut Self::Ctx<'_>,
1294                                                    ) -> #root::dfir_pipes::push::PushStep<Self::CanPend> {
1295                                                        #root::dfir_pipes::push::Push::poll_ready(self.project().inner, ctx)
1296                                                    }
1297
1298                                                    #[inline(always)]
1299                                                    fn start_send(
1300                                                        self: ::std::pin::Pin<&mut Self>,
1301                                                        item: Item,
1302                                                        meta: (),
1303                                                    ) {
1304                                                        #root::dfir_pipes::push::Push::start_send(self.project().inner, item, meta)
1305                                                    }
1306
1307                                                    #[inline(always)]
1308                                                    fn poll_flush(
1309                                                        self: ::std::pin::Pin<&mut Self>,
1310                                                        ctx: &mut Self::Ctx<'_>,
1311                                                    ) -> #root::dfir_pipes::push::PushStep<Self::CanPend> {
1312                                                        #root::dfir_pipes::push::Push::poll_flush(self.project().inner, ctx)
1313                                                    }
1314
1315                                                    #[inline(always)]
1316                                                    fn size_hint(
1317                                                        self: ::std::pin::Pin<&mut Self>,
1318                                                        hint: (usize, Option<usize>),
1319                                                    ) {
1320                                                        #root::dfir_pipes::push::Push::size_hint(self.project().inner, hint)
1321                                                    }
1322                                                }
1323
1324                                                PushGuard {
1325                                                    inner: psh
1326                                                }
1327                                            }
1328                                            #work_fn( #ident )
1329                                        };
1330                                    }
1331                                };
1332                                subgraph_op_iter_code.push(type_guard);
1333                            }
1334                            subgraph_op_iter_after_code.push(write_iterator_after);
1335                        }
1336                    }
1337
1338                    {
1339                        // Determine pull and push halves of the `Pivot`.
1340                        let pull_ident = if 0 < pull_to_push_idx {
1341                            self.node_as_ident(subgraph_nodes[pull_to_push_idx - 1], false)
1342                        } else {
1343                            // Entire subgraph is push (with a single recv/pull handoff input).
1344                            recv_port_idents[0].clone()
1345                        };
1346
1347                        #[rustfmt::skip]
1348                        let push_ident = if let Some(&node_id) =
1349                            subgraph_nodes.get(pull_to_push_idx)
1350                        {
1351                            self.node_as_ident(node_id, false)
1352                        } else if 1 == send_port_idents.len() {
1353                            // Entire subgraph is pull (with a single send/push handoff output).
1354                            send_port_idents[0].clone()
1355                        } else {
1356                            diagnostics.push(Diagnostic::spanned(
1357                                pull_ident.span(),
1358                                Level::Error,
1359                                "Degenerate subgraph detected, is there a disconnected `null()` or other degenerate pipeline somewhere?",
1360                            ));
1361                            continue;
1362                        };
1363
1364                        // Pivot span is combination of pull and push spans (or if not possible, just take the push).
1365                        let pivot_span = pull_ident
1366                            .span()
1367                            .join(push_ident.span())
1368                            .unwrap_or_else(|| push_ident.span());
1369                        let pivot_fn_ident =
1370                            Ident::new(&format!("pivot_run_sg_{:?}", subgraph_id.0), pivot_span);
1371                        let root = change_spans(root.clone(), pivot_span);
1372                        subgraph_op_iter_code.push(quote_spanned! {pivot_span=>
1373                            #[inline(always)]
1374                            fn #pivot_fn_ident<Pul, Psh, Item>(pull: Pul, push: Psh)
1375                                -> impl ::std::future::Future<Output = ()>
1376                            where
1377                                Pul: #root::dfir_pipes::pull::Pull<Item = Item>,
1378                                Psh: #root::dfir_pipes::push::Push<Item, Pul::Meta>,
1379                            {
1380                                #root::dfir_pipes::pull::Pull::send_push(pull, push)
1381                            }
1382                            (#pivot_fn_ident)(#pull_ident, #push_ident).await;
1383                        });
1384                    }
1385                };
1386
1387                // Each subgraph block is an async block so it can be individually instrumented.
1388                // Note: this ident is for the subgraph future, not a runtime SubgraphId binding
1389                // (unlike the scheduled path's `sg_ident`).
1390                let sg_fut_ident = subgraph_id.as_ident(Span::call_site());
1391
1392                // Generate send-side curr_items_count updates (after subgraph runs).
1393                let send_metrics_code: Vec<TokenStream> = send_hoffs
1394                    .iter()
1395                    .zip(send_buf_idents.iter())
1396                    .map(|(&hoff_id, buf_ident)| {
1397                        let hoff_idx = slotmap_raw_idx(hoff_id);
1398                        quote! {
1399                            __dfir_metrics.handoffs[
1400                                #root::util::slot_vec::Key::<#root::scheduled::HandoffTag>::from_raw(#hoff_idx)
1401                            ].curr_items_count.set(#buf_ident.len());
1402                        }
1403                    })
1404                    .collect();
1405
1406                subgraph_blocks.push(quote! {
1407                    let #sg_fut_ident = async {
1408                        let #context = &#df;
1409                        #( #recv_port_code )*
1410                        #( #send_port_code )*
1411                        #( #subgraph_op_iter_code )*
1412                        #( #subgraph_op_iter_after_code )*
1413                    };
1414                    {
1415                        let sg_metrics = &__dfir_metrics.subgraphs[
1416                            #root::util::slot_vec::Key::<#root::scheduled::SubgraphTag>::from_raw(#sg_metrics_idx)
1417                        ];
1418                        #root::scheduled::metrics::InstrumentSubgraph::new(
1419                            #sg_fut_ident, sg_metrics
1420                        ).await;
1421                        sg_metrics.total_run_count.update(|x| x + 1);
1422                    }
1423                    #( #send_metrics_code )*
1424                });
1425
1426                // Collect per-subgraph prologues into the main prologue lists.
1427                // (They are already pushed above in the operator loop.)
1428            }
1429        }
1430
1431        if diagnostics.has_error() {
1432            return Err(std::mem::take(diagnostics));
1433        }
1434        let _ = diagnostics; // Ensure no more diagnostics may be added after checking for errors.
1435
1436        let meta_graph_json = serde_json::to_string(&self).unwrap();
1437        let meta_graph_json = Literal::string(&meta_graph_json);
1438
1439        let serde_diagnostics: Vec<_> = diagnostics.iter().map(Diagnostic::to_serde).collect();
1440        let diagnostics_json = serde_json::to_string(&*serde_diagnostics).unwrap();
1441        let diagnostics_json = Literal::string(&diagnostics_json);
1442
1443        // Generate metrics initialization: one entry per handoff and per subgraph.
1444        let metrics_init_code = {
1445            let handoff_inits = handoff_nodes.iter().map(|&(node_id, _)| {
1446                let idx = slotmap_raw_idx(node_id);
1447                quote! {
1448                    dfir_metrics.handoffs.insert(
1449                        #root::util::slot_vec::Key::from_raw(#idx),
1450                        ::std::default::Default::default(),
1451                    );
1452                }
1453            });
1454            let subgraph_inits = all_subgraphs.iter().map(|&(sg_id, _)| {
1455                let idx = slotmap_raw_idx(sg_id);
1456                quote! {
1457                    dfir_metrics.subgraphs.insert(
1458                        #root::util::slot_vec::Key::from_raw(#idx),
1459                        ::std::default::Default::default(),
1460                    );
1461                }
1462            });
1463            handoff_inits.chain(subgraph_inits).collect::<Vec<_>>()
1464        };
1465
1466        // Prologues and buffer declarations persist across ticks (outside the closure).
1467        // Subgraph blocks run each tick (inside the closure).
1468        Ok(quote! {
1469            {
1470                #prefix
1471
1472                use #root::{var_expr, var_args};
1473
1474                let __dfir_wake_state = ::std::sync::Arc::new(
1475                    #root::scheduled::context::WakeState::default()
1476                );
1477
1478                let __dfir_metrics = {
1479                    let mut dfir_metrics = #root::scheduled::metrics::DfirMetrics::default();
1480                    #( #metrics_init_code )*
1481                    ::std::rc::Rc::new(dfir_metrics)
1482                };
1483
1484                #[allow(unused_mut)]
1485                let mut #df = #root::scheduled::context::Context::new(
1486                    ::std::clone::Clone::clone(&__dfir_wake_state),
1487                    __dfir_metrics,
1488                );
1489
1490                #( #buffer_code )*
1491                #( #op_prologue_code )*
1492                #( #op_prologue_after_code )*
1493
1494                // Pre-set to true so the first tick always returns true
1495                // (matching Dfir pre-scheduling behavior). Subsequent ticks
1496                // start false (from take()) and are set true by recv port code
1497                // if any handoff buffer has data.
1498                let mut __dfir_work_done = true;
1499                #[allow(unused_qualifications, unused_mut, unused_variables, clippy::await_holding_refcell_ref)]
1500                let __dfir_inline_tick = async move |#df: &mut #root::scheduled::context::Context| {
1501                    let __dfir_metrics = #df.metrics();
1502                    #( #subgraph_blocks )*
1503
1504                    // For non-lazy defer_tick: if any deferred buffer has data,
1505                    // signal that another tick should run (sets can_start_tick).
1506                    // Inline DFIR doesn't dynamically schedule subgraph IDs, so the
1507                    // subgraph ID here is a meaningless placeholder.
1508                    // TODO(cleanup): remove the subgraph ID parameter once scheduled DFIR is gone.
1509                    if false #( || !#defer_tick_buf_idents.is_empty() )* {
1510                        #df.schedule_subgraph(
1511                            #root::scheduled::SubgraphId::from_raw(0),
1512                            true,
1513                        );
1514                    }
1515
1516                    #df.__end_tick();
1517                    ::std::mem::take(&mut __dfir_work_done)
1518                };
1519                #root::scheduled::context::Dfir::new(
1520                    __dfir_inline_tick,
1521                    #df,
1522                    Some(#meta_graph_json),
1523                    Some(#diagnostics_json),
1524                )
1525            }
1526        })
1527    }
1528
1529    /// Color mode (pull vs. push, handoff vs. comp) for nodes. Some nodes can be push *OR* pull;
1530    /// those nodes will not be set in the returned map.
1531    pub fn node_color_map(&self) -> SparseSecondaryMap<GraphNodeId, Color> {
1532        let mut node_color_map: SparseSecondaryMap<GraphNodeId, Color> = self
1533            .node_ids()
1534            .filter_map(|node_id| {
1535                let op_color = self.node_color(node_id)?;
1536                Some((node_id, op_color))
1537            })
1538            .collect();
1539
1540        // Fill in rest via subgraphs.
1541        for sg_nodes in self.subgraph_nodes.values() {
1542            let pull_to_push_idx = self.find_pull_to_push_idx(sg_nodes);
1543
1544            for (idx, node_id) in sg_nodes.iter().copied().enumerate() {
1545                let is_pull = idx < pull_to_push_idx;
1546                node_color_map.insert(node_id, if is_pull { Color::Pull } else { Color::Push });
1547            }
1548        }
1549
1550        node_color_map
1551    }
1552
1553    /// Writes this graph as mermaid into a string.
1554    pub fn to_mermaid(&self, write_config: &WriteConfig) -> String {
1555        let mut output = String::new();
1556        self.write_mermaid(&mut output, write_config).unwrap();
1557        output
1558    }
1559
1560    /// Writes this graph as mermaid into the given `Write`.
1561    pub fn write_mermaid(
1562        &self,
1563        output: impl std::fmt::Write,
1564        write_config: &WriteConfig,
1565    ) -> std::fmt::Result {
1566        let mut graph_write = Mermaid::new(output);
1567        self.write_graph(&mut graph_write, write_config)
1568    }
1569
1570    /// Writes this graph as DOT (graphviz) into a string.
1571    pub fn to_dot(&self, write_config: &WriteConfig) -> String {
1572        let mut output = String::new();
1573        let mut graph_write = Dot::new(&mut output);
1574        self.write_graph(&mut graph_write, write_config).unwrap();
1575        output
1576    }
1577
1578    /// Writes this graph as DOT (graphviz) into the given `Write`.
1579    pub fn write_dot(
1580        &self,
1581        output: impl std::fmt::Write,
1582        write_config: &WriteConfig,
1583    ) -> std::fmt::Result {
1584        let mut graph_write = Dot::new(output);
1585        self.write_graph(&mut graph_write, write_config)
1586    }
1587
1588    /// Write out this graph using the given `GraphWrite`. E.g. `Mermaid` or `Dot.
1589    pub(crate) fn write_graph<W>(
1590        &self,
1591        mut graph_write: W,
1592        write_config: &WriteConfig,
1593    ) -> Result<(), W::Err>
1594    where
1595        W: GraphWrite,
1596    {
1597        fn helper_edge_label(
1598            src_port: &PortIndexValue,
1599            dst_port: &PortIndexValue,
1600        ) -> Option<String> {
1601            let src_label = match src_port {
1602                PortIndexValue::Path(path) => Some(path.to_token_stream().to_string()),
1603                PortIndexValue::Int(index) => Some(index.value.to_string()),
1604                _ => None,
1605            };
1606            let dst_label = match dst_port {
1607                PortIndexValue::Path(path) => Some(path.to_token_stream().to_string()),
1608                PortIndexValue::Int(index) => Some(index.value.to_string()),
1609                _ => None,
1610            };
1611            let label = match (src_label, dst_label) {
1612                (Some(l1), Some(l2)) => Some(format!("{}\n{}", l1, l2)),
1613                (Some(l1), None) => Some(l1),
1614                (None, Some(l2)) => Some(l2),
1615                (None, None) => None,
1616            };
1617            label
1618        }
1619
1620        // Make node color map one time.
1621        let node_color_map = self.node_color_map();
1622
1623        // Write prologue.
1624        graph_write.write_prologue()?;
1625
1626        // Define nodes.
1627        let mut skipped_handoffs = BTreeSet::new();
1628        let mut subgraph_handoffs = <BTreeMap<GraphSubgraphId, Vec<GraphNodeId>>>::new();
1629        for (node_id, node) in self.nodes() {
1630            if matches!(node, GraphNode::Handoff { .. }) {
1631                if write_config.no_handoffs {
1632                    skipped_handoffs.insert(node_id);
1633                    continue;
1634                } else {
1635                    let pred_node = self.node_predecessor_nodes(node_id).next().unwrap();
1636                    let pred_sg = self.node_subgraph(pred_node);
1637                    let succ_node = self.node_successor_nodes(node_id).next().unwrap();
1638                    let succ_sg = self.node_subgraph(succ_node);
1639                    if let Some((pred_sg, succ_sg)) = pred_sg.zip(succ_sg)
1640                        && pred_sg == succ_sg
1641                    {
1642                        subgraph_handoffs.entry(pred_sg).or_default().push(node_id);
1643                    }
1644                }
1645            }
1646            graph_write.write_node_definition(
1647                node_id,
1648                &if write_config.op_short_text {
1649                    node.to_name_string()
1650                } else if write_config.op_text_no_imports {
1651                    // Remove any lines that start with "use" (imports)
1652                    let full_text = node.to_pretty_string();
1653                    let mut output = String::new();
1654                    for sentence in full_text.split('\n') {
1655                        if sentence.trim().starts_with("use") {
1656                            continue;
1657                        }
1658                        output.push('\n');
1659                        output.push_str(sentence);
1660                    }
1661                    output.into()
1662                } else {
1663                    node.to_pretty_string()
1664                },
1665                if write_config.no_pull_push {
1666                    None
1667                } else {
1668                    node_color_map.get(node_id).copied()
1669                },
1670            )?;
1671        }
1672
1673        // Write edges.
1674        for (edge_id, (src_id, mut dst_id)) in self.edges() {
1675            // Handling for if `write_config.no_handoffs` true.
1676            if skipped_handoffs.contains(&src_id) {
1677                continue;
1678            }
1679
1680            let (src_port, mut dst_port) = self.edge_ports(edge_id);
1681            if skipped_handoffs.contains(&dst_id) {
1682                let mut handoff_succs = self.node_successors(dst_id);
1683                assert_eq!(1, handoff_succs.len());
1684                let (succ_edge, succ_node) = handoff_succs.next().unwrap();
1685                dst_id = succ_node;
1686                dst_port = self.edge_ports(succ_edge).1;
1687            }
1688
1689            let label = helper_edge_label(src_port, dst_port);
1690            let delay_type = self
1691                .node_op_inst(dst_id)
1692                .and_then(|op_inst| (op_inst.op_constraints.input_delaytype_fn)(dst_port));
1693            graph_write.write_edge(src_id, dst_id, delay_type, label.as_deref(), false)?;
1694        }
1695
1696        // Write reference edges.
1697        if !write_config.no_references {
1698            for dst_id in self.node_ids() {
1699                for src_ref_id in self
1700                    .node_singleton_references(dst_id)
1701                    .iter()
1702                    .copied()
1703                    .flatten()
1704                {
1705                    let delay_type = Some(DelayType::Stratum);
1706                    let label = None;
1707                    graph_write.write_edge(src_ref_id, dst_id, delay_type, label, true)?;
1708                }
1709            }
1710        }
1711
1712        // The following code is a little bit tricky. Generally, the graph has the hierarchy:
1713        // `loop -> subgraph -> varname -> node`. However, each of these can be disabled via the `write_config`. To
1714        // handle both the enabled and disabled case, this code is structured as a series of nested loops. If the layer
1715        // is disabled, then the HashMap<Option<KEY>, Vec<VALUE>> will only have a single key (`None`) with a
1716        // corresponding `Vec` value containing everything. This way no special handling is needed for the next layer.
1717
1718        // Loop -> Subgraphs
1719        let loop_subgraphs = self.subgraph_ids().map(|sg_id| {
1720            let loop_id = if write_config.no_loops {
1721                None
1722            } else {
1723                self.subgraph_loop(sg_id)
1724            };
1725            (loop_id, sg_id)
1726        });
1727        let loop_subgraphs = into_group_map(loop_subgraphs);
1728        for (loop_id, subgraph_ids) in loop_subgraphs {
1729            if let Some(loop_id) = loop_id {
1730                graph_write.write_loop_start(loop_id)?;
1731            }
1732
1733            // Subgraph -> Varnames.
1734            let subgraph_varnames_nodes = subgraph_ids.into_iter().flat_map(|sg_id| {
1735                self.subgraph(sg_id).iter().copied().map(move |node_id| {
1736                    let opt_sg_id = if write_config.no_subgraphs {
1737                        None
1738                    } else {
1739                        Some(sg_id)
1740                    };
1741                    (opt_sg_id, (self.node_varname(node_id), node_id))
1742                })
1743            });
1744            let subgraph_varnames_nodes = into_group_map(subgraph_varnames_nodes);
1745            for (sg_id, varnames) in subgraph_varnames_nodes {
1746                if let Some(sg_id) = sg_id {
1747                    graph_write.write_subgraph_start(sg_id)?;
1748                }
1749
1750                // Varnames -> Nodes.
1751                let varname_nodes = varnames.into_iter().map(|(varname, node)| {
1752                    let varname = if write_config.no_varnames {
1753                        None
1754                    } else {
1755                        varname
1756                    };
1757                    (varname, node)
1758                });
1759                let varname_nodes = into_group_map(varname_nodes);
1760                for (varname, node_ids) in varname_nodes {
1761                    if let Some(varname) = varname {
1762                        graph_write.write_varname_start(&varname.0.to_string(), sg_id)?;
1763                    }
1764
1765                    // Write all nodes.
1766                    for node_id in node_ids {
1767                        graph_write.write_node(node_id)?;
1768                    }
1769
1770                    if varname.is_some() {
1771                        graph_write.write_varname_end()?;
1772                    }
1773                }
1774
1775                if sg_id.is_some() {
1776                    graph_write.write_subgraph_end()?;
1777                }
1778            }
1779
1780            if loop_id.is_some() {
1781                graph_write.write_loop_end()?;
1782            }
1783        }
1784
1785        // Write epilogue.
1786        graph_write.write_epilogue()?;
1787
1788        Ok(())
1789    }
1790
1791    /// Convert back into surface syntax.
1792    pub fn surface_syntax_string(&self) -> String {
1793        let mut string = String::new();
1794        self.write_surface_syntax(&mut string).unwrap();
1795        string
1796    }
1797
1798    /// Convert back into surface syntax.
1799    pub fn write_surface_syntax(&self, write: &mut impl std::fmt::Write) -> std::fmt::Result {
1800        for (key, node) in self.nodes.iter() {
1801            match node {
1802                GraphNode::Operator(op) => {
1803                    writeln!(write, "{:?} = {};", key.data(), op.to_token_stream())?;
1804                }
1805                GraphNode::Handoff { .. } => {
1806                    writeln!(write, "// {:?} = <handoff>;", key.data())?;
1807                }
1808                GraphNode::ModuleBoundary { .. } => panic!(),
1809            }
1810        }
1811        writeln!(write)?;
1812        for (_e, (src_key, dst_key)) in self.graph.edges() {
1813            writeln!(write, "{:?} -> {:?};", src_key.data(), dst_key.data())?;
1814        }
1815        Ok(())
1816    }
1817
1818    /// Convert into a [mermaid](https://mermaid-js.github.io/) graph. Ignores subgraphs.
1819    pub fn mermaid_string_flat(&self) -> String {
1820        let mut string = String::new();
1821        self.write_mermaid_flat(&mut string).unwrap();
1822        string
1823    }
1824
1825    /// Convert into a [mermaid](https://mermaid-js.github.io/) graph. Ignores subgraphs.
1826    pub fn write_mermaid_flat(&self, write: &mut impl std::fmt::Write) -> std::fmt::Result {
1827        writeln!(write, "flowchart TB")?;
1828        for (key, node) in self.nodes.iter() {
1829            match node {
1830                GraphNode::Operator(operator) => writeln!(
1831                    write,
1832                    "    %% {span}\n    {id:?}[\"{row_col} <tt>{code}</tt>\"]",
1833                    span = PrettySpan(node.span()),
1834                    id = key.data(),
1835                    row_col = PrettyRowCol(node.span()),
1836                    code = operator
1837                        .to_token_stream()
1838                        .to_string()
1839                        .replace('&', "&amp;")
1840                        .replace('<', "&lt;")
1841                        .replace('>', "&gt;")
1842                        .replace('"', "&quot;")
1843                        .replace('\n', "<br>"),
1844                ),
1845                GraphNode::Handoff { .. } => {
1846                    writeln!(write, r#"    {:?}{{"{}"}}"#, key.data(), HANDOFF_NODE_STR)
1847                }
1848                GraphNode::ModuleBoundary { .. } => {
1849                    writeln!(
1850                        write,
1851                        r#"    {:?}{{"{}"}}"#,
1852                        key.data(),
1853                        MODULE_BOUNDARY_NODE_STR
1854                    )
1855                }
1856            }?;
1857        }
1858        writeln!(write)?;
1859        for (_e, (src_key, dst_key)) in self.graph.edges() {
1860            writeln!(write, "    {:?}-->{:?}", src_key.data(), dst_key.data())?;
1861        }
1862        Ok(())
1863    }
1864}
1865
1866/// Loops
1867impl DfirGraph {
1868    /// Iterator over all loop IDs.
1869    pub fn loop_ids(&self) -> slotmap::basic::Keys<'_, GraphLoopId, Vec<GraphNodeId>> {
1870        self.loop_nodes.keys()
1871    }
1872
1873    /// Iterator over all loops, ID and members: `(GraphLoopId, Vec<GraphNodeId>)`.
1874    pub fn loops(&self) -> slotmap::basic::Iter<'_, GraphLoopId, Vec<GraphNodeId>> {
1875        self.loop_nodes.iter()
1876    }
1877
1878    /// Create a new loop context, with the given parent loop (or `None`).
1879    pub fn insert_loop(&mut self, parent_loop: Option<GraphLoopId>) -> GraphLoopId {
1880        let loop_id = self.loop_nodes.insert(Vec::new());
1881        self.loop_children.insert(loop_id, Vec::new());
1882        if let Some(parent_loop) = parent_loop {
1883            self.loop_parent.insert(loop_id, parent_loop);
1884            self.loop_children
1885                .get_mut(parent_loop)
1886                .unwrap()
1887                .push(loop_id);
1888        } else {
1889            self.root_loops.push(loop_id);
1890        }
1891        loop_id
1892    }
1893
1894    /// Get a node's loop context (or `None` for root).
1895    pub fn node_loop(&self, node_id: GraphNodeId) -> Option<GraphLoopId> {
1896        self.node_loops.get(node_id).copied()
1897    }
1898
1899    /// Get a subgraph's loop context (or `None` for root).
1900    pub fn subgraph_loop(&self, subgraph_id: GraphSubgraphId) -> Option<GraphLoopId> {
1901        let &node_id = self.subgraph(subgraph_id).first().unwrap();
1902        let out = self.node_loop(node_id);
1903        debug_assert!(
1904            self.subgraph(subgraph_id)
1905                .iter()
1906                .all(|&node_id| self.node_loop(node_id) == out),
1907            "Subgraph nodes should all have the same loop context."
1908        );
1909        out
1910    }
1911
1912    /// Get a loop context's parent loop context (or `None` for root).
1913    pub fn loop_parent(&self, loop_id: GraphLoopId) -> Option<GraphLoopId> {
1914        self.loop_parent.get(loop_id).copied()
1915    }
1916
1917    /// Get a loop context's child loops.
1918    pub fn loop_children(&self, loop_id: GraphLoopId) -> &Vec<GraphLoopId> {
1919        self.loop_children.get(loop_id).unwrap()
1920    }
1921}
1922
1923/// Configuration for writing graphs.
1924#[derive(Clone, Debug, Default)]
1925#[cfg_attr(feature = "clap-derive", derive(clap::Args))]
1926pub struct WriteConfig {
1927    /// Subgraphs will not be rendered if set.
1928    #[cfg_attr(feature = "clap-derive", arg(long))]
1929    pub no_subgraphs: bool,
1930    /// Variable names will not be rendered if set.
1931    #[cfg_attr(feature = "clap-derive", arg(long))]
1932    pub no_varnames: bool,
1933    /// Will not render pull/push shapes if set.
1934    #[cfg_attr(feature = "clap-derive", arg(long))]
1935    pub no_pull_push: bool,
1936    /// Will not render handoffs if set.
1937    #[cfg_attr(feature = "clap-derive", arg(long))]
1938    pub no_handoffs: bool,
1939    /// Will not render singleton references if set.
1940    #[cfg_attr(feature = "clap-derive", arg(long))]
1941    pub no_references: bool,
1942    /// Will not render loops if set.
1943    #[cfg_attr(feature = "clap-derive", arg(long))]
1944    pub no_loops: bool,
1945
1946    /// Op text will only be their name instead of the whole source.
1947    #[cfg_attr(feature = "clap-derive", arg(long))]
1948    pub op_short_text: bool,
1949    /// Op text will exclude any line that starts with "use".
1950    #[cfg_attr(feature = "clap-derive", arg(long))]
1951    pub op_text_no_imports: bool,
1952}
1953
1954/// Enum for choosing between mermaid and dot graph writing.
1955#[derive(Copy, Clone, Debug)]
1956#[cfg_attr(feature = "clap-derive", derive(clap::Parser, clap::ValueEnum))]
1957pub enum WriteGraphType {
1958    /// Mermaid graphs.
1959    Mermaid,
1960    /// Dot (Graphviz) graphs.
1961    Dot,
1962}
1963
1964/// [`itertools::Itertools::into_group_map`], but for `BTreeMap`.
1965fn into_group_map<K, V>(iter: impl IntoIterator<Item = (K, V)>) -> BTreeMap<K, Vec<V>>
1966where
1967    K: Ord,
1968{
1969    let mut out: BTreeMap<_, Vec<_>> = BTreeMap::new();
1970    for (k, v) in iter {
1971        out.entry(k).or_default().push(v);
1972    }
1973    out
1974}