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#[derive(Default, Debug, Serialize, Deserialize)]
40pub struct DfirGraph {
41 nodes: SlotMap<GraphNodeId, GraphNode>,
43
44 #[serde(skip)]
47 operator_instances: SecondaryMap<GraphNodeId, OperatorInstance>,
48 operator_tag: SecondaryMap<GraphNodeId, String>,
50 graph: DiMulGraph<GraphNodeId, GraphEdgeId>,
52 ports: SecondaryMap<GraphEdgeId, (PortIndexValue, PortIndexValue)>,
54
55 node_loops: SecondaryMap<GraphNodeId, GraphLoopId>,
57 loop_nodes: SlotMap<GraphLoopId, Vec<GraphNodeId>>,
59 loop_parent: SparseSecondaryMap<GraphLoopId, GraphLoopId>,
61 root_loops: Vec<GraphLoopId>,
63 loop_children: SecondaryMap<GraphLoopId, Vec<GraphLoopId>>,
65
66 node_subgraph: SecondaryMap<GraphNodeId, GraphSubgraphId>,
68
69 subgraph_nodes: SlotMap<GraphSubgraphId, Vec<GraphNodeId>>,
71
72 node_singleton_references: SparseSecondaryMap<GraphNodeId, Vec<Option<GraphNodeId>>>,
74 node_varnames: SparseSecondaryMap<GraphNodeId, Varname>,
76
77 handoff_delay_type: SparseSecondaryMap<GraphNodeId, DelayType>,
81}
82
83impl DfirGraph {
85 pub fn new() -> Self {
87 Default::default()
88 }
89}
90
91impl DfirGraph {
93 pub fn node(&self, node_id: GraphNodeId) -> &GraphNode {
95 self.nodes.get(node_id).expect("Node not found.")
96 }
97
98 pub fn node_op_inst(&self, node_id: GraphNodeId) -> Option<&OperatorInstance> {
103 self.operator_instances.get(node_id)
104 }
105
106 pub fn node_varname(&self, node_id: GraphNodeId) -> Option<&Varname> {
108 self.node_varnames.get(node_id)
109 }
110
111 pub fn node_subgraph(&self, node_id: GraphNodeId) -> Option<GraphSubgraphId> {
113 self.node_subgraph.get(node_id).copied()
114 }
115
116 pub fn node_degree_in(&self, node_id: GraphNodeId) -> usize {
118 self.graph.degree_in(node_id)
119 }
120
121 pub fn node_degree_out(&self, node_id: GraphNodeId) -> usize {
123 self.graph.degree_out(node_id)
124 }
125
126 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 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 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 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 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 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 pub fn node_ids(&self) -> slotmap::basic::Keys<'_, GraphNodeId, GraphNode> {
206 self.nodes.keys()
207 }
208
209 pub fn nodes(&self) -> slotmap::basic::Iter<'_, GraphNodeId, GraphNode> {
211 self.nodes.iter()
212 }
213
214 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 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 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 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 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 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 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 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 let generics = get_operator_generics(diagnostics, operator);
295 {
297 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 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 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 let node_id = self.nodes.insert(new_node);
397 if let Some(op_inst) = op_inst_opt {
399 self.operator_instances.insert(node_id, op_inst);
400 }
401 let (e0, e1) = self
403 .graph
404 .insert_intermediate_vertex(node_id, edge_id)
405 .unwrap();
406
407 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 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 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 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 let inn_degree = self.node_predecessor_nodes(node_id).len();
466 let out_degree = self.node_successor_nodes(node_id).len();
468
469 match (inn_degree, out_degree) {
470 (0, 0) => None, (0, 1) => Some(Color::Pull),
472 (1, 0) => Some(Color::Push),
473 (1, 1) => None, (_many, 0 | 1) => Some(Color::Pull),
475 (0 | 1, _many) => Some(Color::Push),
476 (_many, _to_many) => Some(Color::Comp),
477 }
478 }
479
480 pub fn set_operator_tag(&mut self, node_id: GraphNodeId, tag: String) {
482 self.operator_tag.insert(node_id, tag);
483 }
484}
485
486impl DfirGraph {
488 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 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
509impl DfirGraph {
511 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 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 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
604impl DfirGraph {
606 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 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 pub fn edge_ids(&self) -> slotmap::basic::Keys<'_, GraphEdgeId, (GraphNodeId, GraphNodeId)> {
620 self.graph.edge_ids()
621 }
622
623 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 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 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
654impl DfirGraph {
656 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 pub fn subgraph_ids(&self) -> slotmap::basic::Keys<'_, GraphSubgraphId, Vec<GraphNodeId>> {
665 self.subgraph_nodes.keys()
666 }
667
668 pub fn subgraphs(&self) -> slotmap::basic::Iter<'_, GraphSubgraphId, Vec<GraphNodeId>> {
670 self.subgraph_nodes.iter()
671 }
672
673 pub fn insert_subgraph(
675 &mut self,
676 node_ids: Vec<GraphNodeId>,
677 ) -> Result<GraphSubgraphId, (GraphNodeId, GraphSubgraphId)> {
678 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 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 pub fn handoff_delay_type(&self, node_id: GraphNodeId) -> Option<DelayType> {
706 self.handoff_delay_type.get(node_id).copied()
707 }
708
709 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 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
726impl DfirGraph {
728 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 fn hoff_buf_ident(&self, hoff_id: GraphNodeId, span: Span) -> Ident {
750 Ident::new(&format!("hoff_{:?}_buf", hoff_id.data()), span)
751 }
752
753 fn hoff_back_ident(&self, hoff_id: GraphNodeId, span: Span) -> Ident {
755 Ident::new(&format!("hoff_{:?}_back", hoff_id.data()), span)
756 }
757
758 fn node_as_singleton_ident(&self, node_id: GraphNodeId, span: Span) -> Ident {
760 Ident::new(&format!("singleton_op_{:?}", node_id.data()), span)
761 }
762
763 fn helper_resolve_singletons(&self, node_id: GraphNodeId, span: Span) -> Vec<Ident> {
765 self.node_singleton_references(node_id)
766 .iter()
767 .map(|singleton_node_id| {
768 self.node_as_singleton_ident(
770 singleton_node_id
771 .expect("Expected singleton to be resolved but was not, this is a bug."),
772 span,
773 )
774 })
775 .collect::<Vec<_>>()
776 }
777
778 fn helper_collect_subgraph_handoffs(
781 &self,
782 ) -> SecondaryMap<GraphSubgraphId, (Vec<GraphNodeId>, Vec<GraphNodeId>)> {
783 let mut subgraph_handoffs: SecondaryMap<
785 GraphSubgraphId,
786 (Vec<GraphNodeId>, Vec<GraphNodeId>),
787 > = self
788 .subgraph_nodes
789 .keys()
790 .map(|k| (k, Default::default()))
791 .collect();
792
793 for (hoff_id, node) in self.nodes() {
795 if !matches!(node, GraphNode::Handoff { .. }) {
796 continue;
797 }
798 for (_edge, succ_id) in self.node_successors(hoff_id) {
800 let succ_sg = self.node_subgraph(succ_id).unwrap();
801 subgraph_handoffs[succ_sg].0.push(hoff_id);
802 }
803 for (_edge, pred_id) in self.node_predecessors(hoff_id) {
805 let pred_sg = self.node_subgraph(pred_id).unwrap();
806 subgraph_handoffs[pred_sg].1.push(hoff_id);
807 }
808 }
809
810 subgraph_handoffs
811 }
812
813 pub fn as_code(
829 &self,
830 root: &TokenStream,
831 include_type_guards: bool,
832 prefix: TokenStream,
833 diagnostics: &mut Diagnostics,
834 ) -> Result<TokenStream, Diagnostics> {
835 self.as_code_with_options(root, include_type_guards, true, prefix, diagnostics)
836 }
837
838 pub fn as_code_with_options(
847 &self,
848 root: &TokenStream,
849 include_type_guards: bool,
850 include_meta: bool,
851 prefix: TokenStream,
852 diagnostics: &mut Diagnostics,
853 ) -> Result<TokenStream, Diagnostics> {
854 let df = Ident::new(GRAPH, Span::call_site());
855 let context = Ident::new(CONTEXT, Span::call_site());
856
857 let handoff_nodes: Vec<_> = self
859 .nodes
860 .iter()
861 .filter_map(|(node_id, node)| match node {
862 GraphNode::Operator(_) => None,
863 &GraphNode::Handoff { src_span, dst_span } => Some((node_id, (src_span, dst_span))),
864 GraphNode::ModuleBoundary { .. } => panic!(),
865 })
866 .collect();
867
868 let buffer_code: Vec<TokenStream> = handoff_nodes
869 .iter()
870 .map(|&(node_id, (src_span, dst_span))| {
871 let span = src_span.join(dst_span).unwrap_or(src_span);
872 let buf_ident = self.hoff_buf_ident(node_id, span);
873 quote_spanned! {span=>
874 let mut #buf_ident: Vec<_> = Vec::new();
875 }
876 })
877 .collect();
878
879 let back_buffer_code: Vec<TokenStream> = handoff_nodes
884 .iter()
885 .filter(|(node_id, _)| self.handoff_delay_type(*node_id).is_some())
886 .map(|&(node_id, (src_span, dst_span))| {
887 let span = src_span.join(dst_span).unwrap_or(src_span);
888 let back_ident = self.hoff_back_ident(node_id, span);
889 quote_spanned! {span=>
890 let mut #back_ident: Vec<_> = Vec::new();
891 }
892 })
893 .collect();
894
895 let subgraph_handoffs = self.helper_collect_subgraph_handoffs();
897
898 let mut defer_tick_buf_idents: Vec<Ident> = Vec::new();
909 let mut back_edge_hoff_ids: BTreeSet<GraphNodeId> = BTreeSet::new();
910 let all_subgraphs = {
911 let mut sg_preds = SecondaryMap::<_, Vec<_>>::with_capacity(self.subgraph_nodes.len());
913 for (hoff_id, node) in self.nodes() {
914 if !matches!(node, GraphNode::Handoff { .. }) {
915 continue;
917 }
918 assert_eq!(1, self.node_successors(hoff_id).len());
919 assert_eq!(1, self.node_predecessors(hoff_id).len());
920 let (_edge_id, pred) = self.node_predecessors(hoff_id).next().unwrap();
921 let (_edge_id, succ) = self.node_successors(hoff_id).next().unwrap();
922 let pred_sg = self.node_subgraph(pred).unwrap();
923 let succ_sg = self.node_subgraph(succ).unwrap();
924 if pred_sg == succ_sg {
925 panic!("bug: unexpected subgraph self-handoff cycle");
926 }
927 if let Some(delay_type) = self.handoff_delay_type(hoff_id) {
928 debug_assert!(matches!(delay_type, DelayType::Tick | DelayType::TickLazy));
929 back_edge_hoff_ids.insert(hoff_id);
932
933 if !matches!(delay_type, DelayType::TickLazy) {
935 defer_tick_buf_idents.push(self.hoff_buf_ident(hoff_id, node.span()));
936 }
937 } else {
938 sg_preds.entry(succ_sg).unwrap().or_default().push(pred_sg);
939 }
940 }
941
942 for dst_id in self.node_ids() {
945 for src_ref_id in self
946 .node_singleton_references(dst_id)
947 .iter()
948 .copied()
949 .flatten()
950 {
951 let src_sg = self
952 .node_subgraph(src_ref_id)
953 .expect("bug: singleton ref node must belong to a subgraph");
954 let dst_sg = self
955 .node_subgraph(dst_id)
956 .expect("bug: singleton ref consumer must belong to a subgraph");
957 if src_sg != dst_sg {
958 sg_preds.entry(dst_sg).unwrap().or_default().push(src_sg);
959 }
960 }
961 }
962
963 let topo_sort = super::graph_algorithms::topo_sort(self.subgraph_ids(), |sg_id| {
964 sg_preds.get(sg_id).into_iter().flatten().copied()
965 })
966 .expect("bug: unexpected cycle between subgraphs within the tick");
967
968 topo_sort
969 .into_iter()
970 .map(|sg_id| (sg_id, self.subgraph(sg_id)))
971 .collect::<Vec<_>>()
972 };
973
974 let back_edge_swap_code: Vec<TokenStream> = back_edge_hoff_ids
978 .iter()
979 .map(|&hoff_id| {
980 let span = self.nodes[hoff_id].span();
981 let buf_ident = self.hoff_buf_ident(hoff_id, span);
982 let back_ident = self.hoff_back_ident(hoff_id, span);
983 quote_spanned! {span=>
984 ::std::mem::swap(&mut #buf_ident, &mut #back_ident);
985 }
986 })
987 .collect();
988
989 let mut op_prologue_code = Vec::new();
990 let mut op_prologue_after_code = Vec::new();
991 let mut op_tick_end_code = Vec::new();
992 let mut subgraph_blocks = Vec::new();
993 {
994 for &(subgraph_id, subgraph_nodes) in all_subgraphs.iter() {
995 let sg_metrics_ffi = subgraph_id.data().as_ffi();
996 let (recv_hoffs, send_hoffs) = &subgraph_handoffs[subgraph_id];
997
998 let recv_port_idents: Vec<Ident> = recv_hoffs
1000 .iter()
1001 .map(|&hoff_id| self.node_as_ident(hoff_id, true))
1002 .collect();
1003 let send_port_idents: Vec<Ident> = send_hoffs
1004 .iter()
1005 .map(|&hoff_id| self.node_as_ident(hoff_id, false))
1006 .collect();
1007
1008 let recv_buf_idents: Vec<Ident> = recv_hoffs
1010 .iter()
1011 .map(|&hoff_id| self.hoff_buf_ident(hoff_id, self.nodes[hoff_id].span()))
1012 .collect();
1013 let send_buf_idents: Vec<Ident> = send_hoffs
1014 .iter()
1015 .map(|&hoff_id| self.hoff_buf_ident(hoff_id, self.nodes[hoff_id].span()))
1016 .collect();
1017
1018 let recv_port_code: Vec<TokenStream> = recv_port_idents
1022 .iter()
1023 .zip(recv_buf_idents.iter())
1024 .zip(recv_hoffs.iter())
1025 .map(|((port_ident, buf_ident), &hoff_id)| {
1026 let hoff_ffi = hoff_id.data().as_ffi();
1027 let work_done = Ident::new("__dfir_work_done", Span::call_site());
1031 let metrics = Ident::new("__dfir_metrics", Span::call_site());
1032 let drain_ident = if back_edge_hoff_ids.contains(&hoff_id) {
1035 self.hoff_back_ident(hoff_id, buf_ident.span())
1036 } else {
1037 buf_ident.clone()
1038 };
1039 quote_spanned! {port_ident.span()=>
1040 {
1041 let hoff_len = #drain_ident.len();
1042 if hoff_len > 0 {
1043 #work_done = true;
1044 }
1045 let hoff_metrics = &#metrics.handoffs[
1046 #root::slotmap::KeyData::from_ffi(#hoff_ffi).into()
1047 ];
1048 hoff_metrics.total_items_count.update(|x| x + hoff_len);
1049 hoff_metrics.curr_items_count.set(hoff_len);
1050 }
1051 let #port_ident = #root::dfir_pipes::pull::iter(#drain_ident.drain(..));
1052 }
1053 })
1054 .collect();
1055
1056 let send_port_code: Vec<TokenStream> = send_port_idents
1058 .iter()
1059 .zip(send_buf_idents.iter())
1060 .map(|(port_ident, buf_ident)| {
1061 quote_spanned! {port_ident.span()=>
1062 let #port_ident = #root::dfir_pipes::push::vec_push(&mut #buf_ident);
1063 }
1064 })
1065 .collect();
1066
1067 let loop_id = self.node_loop(subgraph_nodes[0]);
1069
1070 let mut subgraph_op_iter_code = Vec::new();
1071 let mut subgraph_op_iter_after_code = Vec::new();
1072 {
1073 let pull_to_push_idx = self.find_pull_to_push_idx(subgraph_nodes);
1074
1075 let (pull_half, push_half) = subgraph_nodes.split_at(pull_to_push_idx);
1076 let nodes_iter = pull_half.iter().chain(push_half.iter().rev());
1077
1078 for (idx, &node_id) in nodes_iter.enumerate() {
1079 let node = &self.nodes[node_id];
1080 assert!(
1081 matches!(node, GraphNode::Operator(_)),
1082 "Handoffs are not part of subgraphs."
1083 );
1084 let op_inst = &self.operator_instances[node_id];
1085
1086 let op_span = node.span();
1087 let op_name = op_inst.op_constraints.name;
1088 let root = change_spans(root.clone(), op_span);
1090 let op_constraints = OPERATORS
1091 .iter()
1092 .find(|op| op_name == op.name)
1093 .unwrap_or_else(|| panic!("Failed to find op: {}", op_name));
1094
1095 let ident = self.node_as_ident(node_id, false);
1096
1097 {
1098 let mut input_edges = self
1101 .graph
1102 .predecessor_edges(node_id)
1103 .map(|edge_id| (self.edge_ports(edge_id).1, edge_id))
1104 .collect::<Vec<_>>();
1105 input_edges.sort();
1107
1108 let inputs = input_edges
1109 .iter()
1110 .map(|&(_port, edge_id)| {
1111 let (pred, _) = self.edge(edge_id);
1112 self.node_as_ident(pred, true)
1113 })
1114 .collect::<Vec<_>>();
1115
1116 let mut output_edges = self
1118 .graph
1119 .successor_edges(node_id)
1120 .map(|edge_id| (&self.ports[edge_id].0, edge_id))
1121 .collect::<Vec<_>>();
1122 output_edges.sort();
1124
1125 let outputs = output_edges
1126 .iter()
1127 .map(|&(_port, edge_id)| {
1128 let (_, succ) = self.edge(edge_id);
1129 self.node_as_ident(succ, false)
1130 })
1131 .collect::<Vec<_>>();
1132
1133 let is_pull = idx < pull_to_push_idx;
1134
1135 let singleton_output_ident = &if op_constraints.has_singleton_output {
1136 self.node_as_singleton_ident(node_id, op_span)
1137 } else {
1138 Ident::new(&format!("{}_has_no_singleton_output", op_name), op_span)
1140 };
1141
1142 let df_local = &Ident::new(GRAPH, op_span.resolved_at(df.span()));
1151 let context = &Ident::new(CONTEXT, op_span.resolved_at(context.span()));
1152
1153 let singletons_resolved =
1154 self.helper_resolve_singletons(node_id, op_span);
1155 let arguments = &process_singletons::postprocess_singletons(
1156 op_inst.arguments_raw.clone(),
1157 singletons_resolved.clone(),
1158 context,
1159 );
1160 let arguments_handles =
1161 &process_singletons::postprocess_singletons_handles(
1162 op_inst.arguments_raw.clone(),
1163 singletons_resolved.clone(),
1164 );
1165
1166 let source_tag = 'a: {
1167 if let Some(tag) = self.operator_tag.get(node_id).cloned() {
1168 break 'a tag;
1169 }
1170
1171 #[cfg(nightly)]
1172 if proc_macro::is_available() {
1173 let op_span = op_span.unwrap();
1174 break 'a format!(
1175 "loc_{}_{}_{}_{}_{}",
1176 crate::pretty_span::make_source_path_relative(
1177 &op_span.file()
1178 )
1179 .display()
1180 .to_string()
1181 .replace(|x: char| !x.is_ascii_alphanumeric(), "_"),
1182 op_span.start().line(),
1183 op_span.start().column(),
1184 op_span.end().line(),
1185 op_span.end().column(),
1186 );
1187 }
1188
1189 format!(
1190 "loc_nopath_{}_{}_{}_{}",
1191 op_span.start().line,
1192 op_span.start().column,
1193 op_span.end().line,
1194 op_span.end().column
1195 )
1196 };
1197
1198 let work_fn = format_ident!(
1199 "{}__{}__{}",
1200 ident,
1201 op_name,
1202 source_tag,
1203 span = op_span
1204 );
1205 let work_fn_async = format_ident!("{}__async", work_fn, span = op_span);
1206
1207 let context_args = WriteContextArgs {
1208 root: &root,
1209 df_ident: df_local,
1210 context,
1211 subgraph_id,
1212 node_id,
1213 loop_id,
1214 op_span,
1215 op_tag: self.operator_tag.get(node_id).cloned(),
1216 work_fn: &work_fn,
1217 work_fn_async: &work_fn_async,
1218 ident: &ident,
1219 is_pull,
1220 inputs: &inputs,
1221 outputs: &outputs,
1222 singleton_output_ident,
1223 op_name,
1224 op_inst,
1225 arguments,
1226 arguments_handles,
1227 };
1228
1229 let write_result =
1230 (op_constraints.write_fn)(&context_args, diagnostics);
1231 let OperatorWriteOutput {
1232 write_prologue,
1233 write_prologue_after,
1234 write_iterator,
1235 write_iterator_after,
1236 write_tick_end,
1237 } = write_result.unwrap_or_else(|()| {
1238 assert!(
1239 diagnostics.has_error(),
1240 "Operator `{}` returned `Err` but emitted no diagnostics, this is a bug.",
1241 op_name,
1242 );
1243 OperatorWriteOutput {
1244 write_iterator: null_write_iterator_fn(&context_args),
1245 ..Default::default()
1246 }
1247 });
1248
1249 op_prologue_code.push(syn::parse_quote! {
1250 #[allow(non_snake_case)]
1251 #[inline(always)]
1252 fn #work_fn<T>(thunk: impl ::std::ops::FnOnce() -> T) -> T {
1253 thunk()
1254 }
1255
1256 #[allow(non_snake_case)]
1257 #[inline(always)]
1258 async fn #work_fn_async<T>(
1259 thunk: impl ::std::future::Future<Output = T>,
1260 ) -> T {
1261 thunk.await
1262 }
1263 });
1264 op_prologue_code.push(write_prologue);
1265 op_prologue_after_code.push(write_prologue_after);
1266 op_tick_end_code.push(write_tick_end);
1267 subgraph_op_iter_code.push(write_iterator);
1268
1269 if include_type_guards {
1270 let type_guard = if is_pull {
1271 quote_spanned! {op_span=>
1272 let #ident = {
1273 #[allow(non_snake_case)]
1274 #[inline(always)]
1275 pub fn #work_fn<Item, Input>(input: Input)
1276 -> impl #root::dfir_pipes::pull::Pull<Item = Item, Meta = (), CanPend = Input::CanPend, CanEnd = Input::CanEnd>
1277 where
1278 Input: #root::dfir_pipes::pull::Pull<Item = Item, Meta = ()>,
1279 {
1280 #root::pin_project_lite::pin_project! {
1281 #[repr(transparent)]
1282 struct Pull<Item, Input: #root::dfir_pipes::pull::Pull<Item = Item>> {
1283 #[pin]
1284 inner: Input
1285 }
1286 }
1287
1288 impl<Item, Input> #root::dfir_pipes::pull::Pull for Pull<Item, Input>
1289 where
1290 Input: #root::dfir_pipes::pull::Pull<Item = Item>,
1291 {
1292 type Ctx<'ctx> = Input::Ctx<'ctx>;
1293
1294 type Item = Item;
1295 type Meta = Input::Meta;
1296 type CanPend = Input::CanPend;
1297 type CanEnd = Input::CanEnd;
1298
1299 #[inline(always)]
1300 fn pull(
1301 self: ::std::pin::Pin<&mut Self>,
1302 ctx: &mut Self::Ctx<'_>,
1303 ) -> #root::dfir_pipes::pull::PullStep<Self::Item, Self::Meta, Self::CanPend, Self::CanEnd> {
1304 #root::dfir_pipes::pull::Pull::pull(self.project().inner, ctx)
1305 }
1306
1307 #[inline(always)]
1308 fn size_hint(&self) -> (usize, Option<usize>) {
1309 #root::dfir_pipes::pull::Pull::size_hint(&self.inner)
1310 }
1311 }
1312
1313 Pull {
1314 inner: input
1315 }
1316 }
1317 #work_fn::<_, _>( #ident )
1318 };
1319 }
1320 } else {
1321 quote_spanned! {op_span=>
1322 let #ident = {
1323 #[allow(non_snake_case)]
1324 #[inline(always)]
1325 pub fn #work_fn<Item, Psh>(psh: Psh) -> impl #root::dfir_pipes::push::Push<Item, (), CanPend = Psh::CanPend>
1326 where
1327 Psh: #root::dfir_pipes::push::Push<Item, ()>
1328 {
1329 #root::pin_project_lite::pin_project! {
1330 #[repr(transparent)]
1331 struct PushGuard<Psh> {
1332 #[pin]
1333 inner: Psh,
1334 }
1335 }
1336
1337 impl<Item, Psh> #root::dfir_pipes::push::Push<Item, ()> for PushGuard<Psh>
1338 where
1339 Psh: #root::dfir_pipes::push::Push<Item, ()>,
1340 {
1341 type Ctx<'ctx> = Psh::Ctx<'ctx>;
1342
1343 type CanPend = Psh::CanPend;
1344
1345 #[inline(always)]
1346 fn poll_ready(
1347 self: ::std::pin::Pin<&mut Self>,
1348 ctx: &mut Self::Ctx<'_>,
1349 ) -> #root::dfir_pipes::push::PushStep<Self::CanPend> {
1350 #root::dfir_pipes::push::Push::poll_ready(self.project().inner, ctx)
1351 }
1352
1353 #[inline(always)]
1354 fn start_send(
1355 self: ::std::pin::Pin<&mut Self>,
1356 item: Item,
1357 meta: (),
1358 ) {
1359 #root::dfir_pipes::push::Push::start_send(self.project().inner, item, meta)
1360 }
1361
1362 #[inline(always)]
1363 fn poll_flush(
1364 self: ::std::pin::Pin<&mut Self>,
1365 ctx: &mut Self::Ctx<'_>,
1366 ) -> #root::dfir_pipes::push::PushStep<Self::CanPend> {
1367 #root::dfir_pipes::push::Push::poll_flush(self.project().inner, ctx)
1368 }
1369
1370 #[inline(always)]
1371 fn size_hint(
1372 self: ::std::pin::Pin<&mut Self>,
1373 hint: (usize, Option<usize>),
1374 ) {
1375 #root::dfir_pipes::push::Push::size_hint(self.project().inner, hint)
1376 }
1377 }
1378
1379 PushGuard {
1380 inner: psh
1381 }
1382 }
1383 #work_fn( #ident )
1384 };
1385 }
1386 };
1387 subgraph_op_iter_code.push(type_guard);
1388 }
1389 subgraph_op_iter_after_code.push(write_iterator_after);
1390 }
1391 }
1392
1393 {
1394 let pull_ident = if 0 < pull_to_push_idx {
1396 self.node_as_ident(subgraph_nodes[pull_to_push_idx - 1], false)
1397 } else {
1398 recv_port_idents[0].clone()
1400 };
1401
1402 #[rustfmt::skip]
1403 let push_ident = if let Some(&node_id) =
1404 subgraph_nodes.get(pull_to_push_idx)
1405 {
1406 self.node_as_ident(node_id, false)
1407 } else if 1 == send_port_idents.len() {
1408 send_port_idents[0].clone()
1410 } else {
1411 diagnostics.push(Diagnostic::spanned(
1412 pull_ident.span(),
1413 Level::Error,
1414 "Degenerate subgraph detected, is there a disconnected `null()` or other degenerate pipeline somewhere?",
1415 ));
1416 continue;
1417 };
1418
1419 let pivot_span = pull_ident
1421 .span()
1422 .join(push_ident.span())
1423 .unwrap_or_else(|| push_ident.span());
1424 let pivot_fn_ident =
1425 Ident::new(&format!("pivot_run_sg_{:?}", subgraph_id.0), pivot_span);
1426 let root = change_spans(root.clone(), pivot_span);
1427 subgraph_op_iter_code.push(quote_spanned! {pivot_span=>
1428 #[inline(always)]
1429 fn #pivot_fn_ident<Pul, Psh, Item>(pull: Pul, push: Psh)
1430 -> impl ::std::future::Future<Output = ()>
1431 where
1432 Pul: #root::dfir_pipes::pull::Pull<Item = Item>,
1433 Psh: #root::dfir_pipes::push::Push<Item, Pul::Meta>,
1434 {
1435 #root::dfir_pipes::pull::Pull::send_push(pull, push)
1436 }
1437 (#pivot_fn_ident)(#pull_ident, #push_ident).await;
1438 });
1439 }
1440 };
1441
1442 let sg_fut_ident = subgraph_id.as_ident(Span::call_site());
1446
1447 let send_metrics_code: Vec<TokenStream> = send_hoffs
1449 .iter()
1450 .zip(send_buf_idents.iter())
1451 .map(|(&hoff_id, buf_ident)| {
1452 let hoff_ffi = hoff_id.data().as_ffi();
1453 quote! {
1454 __dfir_metrics.handoffs[
1455 #root::slotmap::KeyData::from_ffi(#hoff_ffi).into()
1456 ].curr_items_count.set(#buf_ident.len());
1457 }
1458 })
1459 .collect();
1460
1461 subgraph_blocks.push(quote! {
1462 let #sg_fut_ident = async {
1463 let #context = &#df;
1464 #( #recv_port_code )*
1465 #( #send_port_code )*
1466 #( #subgraph_op_iter_code )*
1467 #( #subgraph_op_iter_after_code )*
1468 };
1469 {
1470 let sg_metrics = &__dfir_metrics.subgraphs[
1471 #root::slotmap::KeyData::from_ffi(#sg_metrics_ffi).into()
1472 ];
1473 #root::scheduled::metrics::InstrumentSubgraph::new(
1474 #sg_fut_ident, sg_metrics
1475 ).await;
1476 sg_metrics.total_run_count.update(|x| x + 1);
1477 }
1478 #( #send_metrics_code )*
1479 });
1480
1481 }
1484 }
1485
1486 if diagnostics.has_error() {
1487 return Err(std::mem::take(diagnostics));
1488 }
1489 let _ = diagnostics; let (meta_graph_arg, diagnostics_arg) = if include_meta {
1492 let meta_graph_json = serde_json::to_string(&self).unwrap();
1493 let meta_graph_json = Literal::string(&meta_graph_json);
1494
1495 let serde_diagnostics: Vec<_> = diagnostics.iter().map(Diagnostic::to_serde).collect();
1496 let diagnostics_json = serde_json::to_string(&*serde_diagnostics).unwrap();
1497 let diagnostics_json = Literal::string(&diagnostics_json);
1498
1499 (
1500 quote! { Some(#meta_graph_json) },
1501 quote! { Some(#diagnostics_json) },
1502 )
1503 } else {
1504 (quote! { None }, quote! { None })
1505 };
1506
1507 let metrics_init_code = {
1509 let handoff_inits = handoff_nodes.iter().map(|&(node_id, _)| {
1510 let ffi = node_id.data().as_ffi();
1511 quote! {
1512 dfir_metrics.handoffs.insert(
1513 #root::slotmap::KeyData::from_ffi(#ffi).into(),
1514 ::std::default::Default::default(),
1515 );
1516 }
1517 });
1518 let subgraph_inits = all_subgraphs.iter().map(|&(sg_id, _)| {
1519 let ffi = sg_id.data().as_ffi();
1520 quote! {
1521 dfir_metrics.subgraphs.insert(
1522 #root::slotmap::KeyData::from_ffi(#ffi).into(),
1523 ::std::default::Default::default(),
1524 );
1525 }
1526 });
1527 handoff_inits.chain(subgraph_inits).collect::<Vec<_>>()
1528 };
1529
1530 Ok(quote! {
1533 {
1534 #prefix
1535
1536 use #root::{var_expr, var_args};
1537
1538 let __dfir_wake_state = ::std::sync::Arc::new(
1539 #root::scheduled::context::WakeState::default()
1540 );
1541
1542 let __dfir_metrics = {
1543 let mut dfir_metrics = #root::scheduled::metrics::DfirMetrics::default();
1544 #( #metrics_init_code )*
1545 ::std::rc::Rc::new(dfir_metrics)
1546 };
1547
1548 #[allow(unused_mut)]
1549 let mut #df = #root::scheduled::context::Context::new(
1550 ::std::clone::Clone::clone(&__dfir_wake_state),
1551 __dfir_metrics,
1552 );
1553
1554 #( #buffer_code )*
1555 #( #back_buffer_code )*
1556 #( #op_prologue_code )*
1557 #( #op_prologue_after_code )*
1558
1559 let mut __dfir_work_done = true;
1564 #[allow(unused_qualifications, unused_mut, unused_variables, clippy::await_holding_refcell_ref)]
1565 let __dfir_inline_tick = async move |#df: &mut #root::scheduled::context::Context| {
1566 let __dfir_metrics = #df.metrics();
1567 #( #back_edge_swap_code )*
1570 #( #subgraph_blocks )*
1571
1572 if false #( || !#defer_tick_buf_idents.is_empty() )* {
1575 #df.schedule_subgraph(true);
1576 }
1577
1578 #( #op_tick_end_code )*
1580
1581 #df.__end_tick();
1582 ::std::mem::take(&mut __dfir_work_done)
1583 };
1584 #root::scheduled::context::Dfir::new(
1585 __dfir_inline_tick,
1586 #df,
1587 #meta_graph_arg,
1588 #diagnostics_arg,
1589 )
1590 }
1591 })
1592 }
1593
1594 pub fn node_color_map(&self) -> SparseSecondaryMap<GraphNodeId, Color> {
1597 let mut node_color_map: SparseSecondaryMap<GraphNodeId, Color> = self
1598 .node_ids()
1599 .filter_map(|node_id| {
1600 let op_color = self.node_color(node_id)?;
1601 Some((node_id, op_color))
1602 })
1603 .collect();
1604
1605 for sg_nodes in self.subgraph_nodes.values() {
1607 let pull_to_push_idx = self.find_pull_to_push_idx(sg_nodes);
1608
1609 for (idx, node_id) in sg_nodes.iter().copied().enumerate() {
1610 let is_pull = idx < pull_to_push_idx;
1611 node_color_map.insert(node_id, if is_pull { Color::Pull } else { Color::Push });
1612 }
1613 }
1614
1615 node_color_map
1616 }
1617
1618 pub fn to_mermaid(&self, write_config: &WriteConfig) -> String {
1620 let mut output = String::new();
1621 self.write_mermaid(&mut output, write_config).unwrap();
1622 output
1623 }
1624
1625 pub fn write_mermaid(
1627 &self,
1628 output: impl std::fmt::Write,
1629 write_config: &WriteConfig,
1630 ) -> std::fmt::Result {
1631 let mut graph_write = Mermaid::new(output);
1632 self.write_graph(&mut graph_write, write_config)
1633 }
1634
1635 pub fn to_dot(&self, write_config: &WriteConfig) -> String {
1637 let mut output = String::new();
1638 let mut graph_write = Dot::new(&mut output);
1639 self.write_graph(&mut graph_write, write_config).unwrap();
1640 output
1641 }
1642
1643 pub fn write_dot(
1645 &self,
1646 output: impl std::fmt::Write,
1647 write_config: &WriteConfig,
1648 ) -> std::fmt::Result {
1649 let mut graph_write = Dot::new(output);
1650 self.write_graph(&mut graph_write, write_config)
1651 }
1652
1653 pub(crate) fn write_graph<W>(
1655 &self,
1656 mut graph_write: W,
1657 write_config: &WriteConfig,
1658 ) -> Result<(), W::Err>
1659 where
1660 W: GraphWrite,
1661 {
1662 fn helper_edge_label(
1663 src_port: &PortIndexValue,
1664 dst_port: &PortIndexValue,
1665 ) -> Option<String> {
1666 let src_label = match src_port {
1667 PortIndexValue::Path(path) => Some(path.to_token_stream().to_string()),
1668 PortIndexValue::Int(index) => Some(index.value.to_string()),
1669 _ => None,
1670 };
1671 let dst_label = match dst_port {
1672 PortIndexValue::Path(path) => Some(path.to_token_stream().to_string()),
1673 PortIndexValue::Int(index) => Some(index.value.to_string()),
1674 _ => None,
1675 };
1676 let label = match (src_label, dst_label) {
1677 (Some(l1), Some(l2)) => Some(format!("{}\n{}", l1, l2)),
1678 (Some(l1), None) => Some(l1),
1679 (None, Some(l2)) => Some(l2),
1680 (None, None) => None,
1681 };
1682 label
1683 }
1684
1685 let node_color_map = self.node_color_map();
1687
1688 graph_write.write_prologue()?;
1690
1691 let mut skipped_handoffs = BTreeSet::new();
1693 let mut subgraph_handoffs = <BTreeMap<GraphSubgraphId, Vec<GraphNodeId>>>::new();
1694 for (node_id, node) in self.nodes() {
1695 if matches!(node, GraphNode::Handoff { .. }) {
1696 if write_config.no_handoffs {
1697 skipped_handoffs.insert(node_id);
1698 continue;
1699 } else {
1700 let pred_node = self.node_predecessor_nodes(node_id).next().unwrap();
1701 let pred_sg = self.node_subgraph(pred_node);
1702 let succ_node = self.node_successor_nodes(node_id).next().unwrap();
1703 let succ_sg = self.node_subgraph(succ_node);
1704 if let Some((pred_sg, succ_sg)) = pred_sg.zip(succ_sg)
1705 && pred_sg == succ_sg
1706 {
1707 subgraph_handoffs.entry(pred_sg).or_default().push(node_id);
1708 }
1709 }
1710 }
1711 graph_write.write_node_definition(
1712 node_id,
1713 &if write_config.op_short_text {
1714 node.to_name_string()
1715 } else if write_config.op_text_no_imports {
1716 let full_text = node.to_pretty_string();
1718 let mut output = String::new();
1719 for sentence in full_text.split('\n') {
1720 if sentence.trim().starts_with("use") {
1721 continue;
1722 }
1723 output.push('\n');
1724 output.push_str(sentence);
1725 }
1726 output.into()
1727 } else {
1728 node.to_pretty_string()
1729 },
1730 if write_config.no_pull_push {
1731 None
1732 } else {
1733 node_color_map.get(node_id).copied()
1734 },
1735 )?;
1736 }
1737
1738 for (edge_id, (src_id, mut dst_id)) in self.edges() {
1740 if skipped_handoffs.contains(&src_id) {
1742 continue;
1743 }
1744
1745 let (src_port, mut dst_port) = self.edge_ports(edge_id);
1746 if skipped_handoffs.contains(&dst_id) {
1747 let mut handoff_succs = self.node_successors(dst_id);
1748 assert_eq!(1, handoff_succs.len());
1749 let (succ_edge, succ_node) = handoff_succs.next().unwrap();
1750 dst_id = succ_node;
1751 dst_port = self.edge_ports(succ_edge).1;
1752 }
1753
1754 let label = helper_edge_label(src_port, dst_port);
1755 let delay_type = self
1756 .node_op_inst(dst_id)
1757 .and_then(|op_inst| (op_inst.op_constraints.input_delaytype_fn)(dst_port));
1758 graph_write.write_edge(src_id, dst_id, delay_type, label.as_deref(), false)?;
1759 }
1760
1761 if !write_config.no_references {
1763 for dst_id in self.node_ids() {
1764 for src_ref_id in self
1765 .node_singleton_references(dst_id)
1766 .iter()
1767 .copied()
1768 .flatten()
1769 {
1770 let delay_type = Some(DelayType::Stratum);
1771 let label = None;
1772 graph_write.write_edge(src_ref_id, dst_id, delay_type, label, true)?;
1773 }
1774 }
1775 }
1776
1777 let loop_subgraphs = self.subgraph_ids().map(|sg_id| {
1785 let loop_id = if write_config.no_loops {
1786 None
1787 } else {
1788 self.subgraph_loop(sg_id)
1789 };
1790 (loop_id, sg_id)
1791 });
1792 let loop_subgraphs = into_group_map(loop_subgraphs);
1793 for (loop_id, subgraph_ids) in loop_subgraphs {
1794 if let Some(loop_id) = loop_id {
1795 graph_write.write_loop_start(loop_id)?;
1796 }
1797
1798 let subgraph_varnames_nodes = subgraph_ids.into_iter().flat_map(|sg_id| {
1800 self.subgraph(sg_id).iter().copied().map(move |node_id| {
1801 let opt_sg_id = if write_config.no_subgraphs {
1802 None
1803 } else {
1804 Some(sg_id)
1805 };
1806 (opt_sg_id, (self.node_varname(node_id), node_id))
1807 })
1808 });
1809 let subgraph_varnames_nodes = into_group_map(subgraph_varnames_nodes);
1810 for (sg_id, varnames) in subgraph_varnames_nodes {
1811 if let Some(sg_id) = sg_id {
1812 graph_write.write_subgraph_start(sg_id)?;
1813 }
1814
1815 let varname_nodes = varnames.into_iter().map(|(varname, node)| {
1817 let varname = if write_config.no_varnames {
1818 None
1819 } else {
1820 varname
1821 };
1822 (varname, node)
1823 });
1824 let varname_nodes = into_group_map(varname_nodes);
1825 for (varname, node_ids) in varname_nodes {
1826 if let Some(varname) = varname {
1827 graph_write.write_varname_start(&varname.0.to_string(), sg_id)?;
1828 }
1829
1830 for node_id in node_ids {
1832 graph_write.write_node(node_id)?;
1833 }
1834
1835 if varname.is_some() {
1836 graph_write.write_varname_end()?;
1837 }
1838 }
1839
1840 if sg_id.is_some() {
1841 graph_write.write_subgraph_end()?;
1842 }
1843 }
1844
1845 if loop_id.is_some() {
1846 graph_write.write_loop_end()?;
1847 }
1848 }
1849
1850 graph_write.write_epilogue()?;
1852
1853 Ok(())
1854 }
1855
1856 pub fn surface_syntax_string(&self) -> String {
1858 let mut string = String::new();
1859 self.write_surface_syntax(&mut string).unwrap();
1860 string
1861 }
1862
1863 pub fn write_surface_syntax(&self, write: &mut impl std::fmt::Write) -> std::fmt::Result {
1865 for (key, node) in self.nodes.iter() {
1866 match node {
1867 GraphNode::Operator(op) => {
1868 writeln!(write, "{:?} = {};", key.data(), op.to_token_stream())?;
1869 }
1870 GraphNode::Handoff { .. } => {
1871 writeln!(write, "// {:?} = <handoff>;", key.data())?;
1872 }
1873 GraphNode::ModuleBoundary { .. } => panic!(),
1874 }
1875 }
1876 writeln!(write)?;
1877 for (_e, (src_key, dst_key)) in self.graph.edges() {
1878 writeln!(write, "{:?} -> {:?};", src_key.data(), dst_key.data())?;
1879 }
1880 Ok(())
1881 }
1882
1883 pub fn mermaid_string_flat(&self) -> String {
1885 let mut string = String::new();
1886 self.write_mermaid_flat(&mut string).unwrap();
1887 string
1888 }
1889
1890 pub fn write_mermaid_flat(&self, write: &mut impl std::fmt::Write) -> std::fmt::Result {
1892 writeln!(write, "flowchart TB")?;
1893 for (key, node) in self.nodes.iter() {
1894 match node {
1895 GraphNode::Operator(operator) => writeln!(
1896 write,
1897 " %% {span}\n {id:?}[\"{row_col} <tt>{code}</tt>\"]",
1898 span = PrettySpan(node.span()),
1899 id = key.data(),
1900 row_col = PrettyRowCol(node.span()),
1901 code = operator
1902 .to_token_stream()
1903 .to_string()
1904 .replace('&', "&")
1905 .replace('<', "<")
1906 .replace('>', ">")
1907 .replace('"', """)
1908 .replace('\n', "<br>"),
1909 ),
1910 GraphNode::Handoff { .. } => {
1911 writeln!(write, r#" {:?}{{"{}"}}"#, key.data(), HANDOFF_NODE_STR)
1912 }
1913 GraphNode::ModuleBoundary { .. } => {
1914 writeln!(
1915 write,
1916 r#" {:?}{{"{}"}}"#,
1917 key.data(),
1918 MODULE_BOUNDARY_NODE_STR
1919 )
1920 }
1921 }?;
1922 }
1923 writeln!(write)?;
1924 for (_e, (src_key, dst_key)) in self.graph.edges() {
1925 writeln!(write, " {:?}-->{:?}", src_key.data(), dst_key.data())?;
1926 }
1927 Ok(())
1928 }
1929}
1930
1931impl DfirGraph {
1933 pub fn loop_ids(&self) -> slotmap::basic::Keys<'_, GraphLoopId, Vec<GraphNodeId>> {
1935 self.loop_nodes.keys()
1936 }
1937
1938 pub fn loops(&self) -> slotmap::basic::Iter<'_, GraphLoopId, Vec<GraphNodeId>> {
1940 self.loop_nodes.iter()
1941 }
1942
1943 pub fn insert_loop(&mut self, parent_loop: Option<GraphLoopId>) -> GraphLoopId {
1945 let loop_id = self.loop_nodes.insert(Vec::new());
1946 self.loop_children.insert(loop_id, Vec::new());
1947 if let Some(parent_loop) = parent_loop {
1948 self.loop_parent.insert(loop_id, parent_loop);
1949 self.loop_children
1950 .get_mut(parent_loop)
1951 .unwrap()
1952 .push(loop_id);
1953 } else {
1954 self.root_loops.push(loop_id);
1955 }
1956 loop_id
1957 }
1958
1959 pub fn node_loop(&self, node_id: GraphNodeId) -> Option<GraphLoopId> {
1961 self.node_loops.get(node_id).copied()
1962 }
1963
1964 pub fn subgraph_loop(&self, subgraph_id: GraphSubgraphId) -> Option<GraphLoopId> {
1966 let &node_id = self.subgraph(subgraph_id).first().unwrap();
1967 let out = self.node_loop(node_id);
1968 debug_assert!(
1969 self.subgraph(subgraph_id)
1970 .iter()
1971 .all(|&node_id| self.node_loop(node_id) == out),
1972 "Subgraph nodes should all have the same loop context."
1973 );
1974 out
1975 }
1976
1977 pub fn loop_parent(&self, loop_id: GraphLoopId) -> Option<GraphLoopId> {
1979 self.loop_parent.get(loop_id).copied()
1980 }
1981
1982 pub fn loop_children(&self, loop_id: GraphLoopId) -> &Vec<GraphLoopId> {
1984 self.loop_children.get(loop_id).unwrap()
1985 }
1986}
1987
1988#[derive(Clone, Debug, Default)]
1990#[cfg_attr(feature = "clap-derive", derive(clap::Args))]
1991pub struct WriteConfig {
1992 #[cfg_attr(feature = "clap-derive", arg(long))]
1994 pub no_subgraphs: bool,
1995 #[cfg_attr(feature = "clap-derive", arg(long))]
1997 pub no_varnames: bool,
1998 #[cfg_attr(feature = "clap-derive", arg(long))]
2000 pub no_pull_push: bool,
2001 #[cfg_attr(feature = "clap-derive", arg(long))]
2003 pub no_handoffs: bool,
2004 #[cfg_attr(feature = "clap-derive", arg(long))]
2006 pub no_references: bool,
2007 #[cfg_attr(feature = "clap-derive", arg(long))]
2009 pub no_loops: bool,
2010
2011 #[cfg_attr(feature = "clap-derive", arg(long))]
2013 pub op_short_text: bool,
2014 #[cfg_attr(feature = "clap-derive", arg(long))]
2016 pub op_text_no_imports: bool,
2017}
2018
2019#[derive(Copy, Clone, Debug)]
2021#[cfg_attr(feature = "clap-derive", derive(clap::Parser, clap::ValueEnum))]
2022pub enum WriteGraphType {
2023 Mermaid,
2025 Dot,
2027}
2028
2029fn into_group_map<K, V>(iter: impl IntoIterator<Item = (K, V)>) -> BTreeMap<K, Vec<V>>
2031where
2032 K: Ord,
2033{
2034 let mut out: BTreeMap<_, Vec<_>> = BTreeMap::new();
2035 for (k, v) in iter {
2036 out.entry(k).or_default().push(v);
2037 }
2038 out
2039}