1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
use quote::ToTokens;
use syn::{Ident, Path};
use petgraph::{graph::NodeIndex, Graph};
use std::collections::{hash_map::RandomState, HashMap, HashSet};
use super::*;
pub(crate) struct ConnectionGraph<'a> {
pub(crate) graph: Graph<Ident, Path>,
#[cfg_attr(not(feature = "graph"), allow(dead_code))]
pub(crate) sccs: Vec<Vec<NodeIndex>>,
#[cfg_attr(not(feature = "graph"), allow(dead_code))]
pub(crate) unsent_messages: HashMap<&'a Path, (&'a Ident, NodeIndex)>,
#[cfg_attr(not(feature = "graph"), allow(dead_code))]
pub(crate) unconsumed_messages: HashMap<&'a Path, Vec<(&'a Ident, NodeIndex)>>,
}
impl<'a> ConnectionGraph<'a> {
pub(crate) fn construct(ssfs: &'a [SubSysField]) -> Self {
let mut outgoing_lut = HashMap::<&Path, Vec<(&Ident, NodeIndex)>>::with_capacity(128);
let mut consuming_lut = HashMap::<&Path, (&Ident, NodeIndex)>::with_capacity(128);
let mut graph = Graph::<Ident, Path>::new();
for ssf in ssfs {
let node_index = graph.add_node(ssf.generic.clone());
for outgoing in ssf.messages_to_send.iter() {
outgoing_lut.entry(outgoing).or_default().push((&ssf.generic, node_index));
}
if let Some(_first_consument) =
consuming_lut.insert(&ssf.message_to_consume, (&ssf.generic, node_index))
{
}
}
for (message_ty, (_consuming_subsystem_ident, consuming_node_index)) in consuming_lut.iter()
{
if let Some(origin_subsystems) = outgoing_lut.get(message_ty) {
for (_origin_subsystem_ident, sending_node_index) in origin_subsystems.iter() {
graph.add_edge(
*sending_node_index,
*consuming_node_index,
(*message_ty).clone(),
);
}
}
}
let outgoing_set = HashSet::<_, RandomState>::from_iter(outgoing_lut.keys().cloned());
let consuming_set = HashSet::<_, RandomState>::from_iter(consuming_lut.keys().cloned());
let mut unsent_messages = consuming_lut;
unsent_messages.retain(|k, _v| !outgoing_set.contains(k));
let mut unconsumed_messages = outgoing_lut;
unconsumed_messages.retain(|k, _v| !consuming_set.contains(k));
let scc = Self::extract_scc(&graph);
Self { graph, sccs: scc, unsent_messages, unconsumed_messages }
}
fn extract_scc(graph: &Graph<Ident, Path>) -> Vec<Vec<NodeIndex>> {
use petgraph::visit::EdgeRef;
let sccs = petgraph::algo::kosaraju_scc(&graph);
let sccs = Vec::from_iter(sccs.into_iter().filter(|scc| {
match scc.len() {
1 => {
let node_idx = scc[0];
graph
.edges_directed(node_idx, petgraph::Direction::Outgoing)
.find(|edge| edge.target() == node_idx)
.is_some()
},
0 => false,
_n => true,
}
}));
match sccs.len() {
0 => println!("✅ Found no strongly connected components, hence no cycles exist"),
1 => println!(
"⚡ Found 1 strongly connected component which includes at least one cycle"
),
n => println!(
"⚡ Found {n} strongly connected components which includes at least one cycle each"
),
}
let greek_alphabet = greek_alphabet();
for (scc_idx, scc) in sccs.iter().enumerate() {
let scc_tag = greek_alphabet.get(scc_idx).copied().unwrap_or('_');
let mut acc = Vec::with_capacity(scc.len());
assert!(scc.len() > 0);
let mut node_idx = scc[0].clone();
let print_idx = scc_idx + 1;
let mut visited = HashMap::new();
for step in 0..scc.len() {
if let Some(edge) =
graph.edges_directed(node_idx, petgraph::Direction::Outgoing).find(|edge| {
scc.iter().find(|&scc_node_idx| *scc_node_idx == edge.target()).is_some()
}) {
let next = edge.target();
visited.insert(node_idx, step);
let subsystem_name = &graph[node_idx].to_string();
let message_name = &graph[edge.id()].to_token_stream().to_string();
acc.push(format!("{subsystem_name} ~~{{{message_name:?}}}~~> "));
node_idx = next;
if let Some(step) = visited.get(&next) {
assert!(acc.len() >= *step);
acc.drain(..step);
break
}
} else {
eprintln!("cycle({print_idx:03}) ∈ {scc_tag}: Missing connection in hypothesized cycle after {step} steps, this is a bug 🐛");
break
}
}
let acc = String::from_iter(acc);
println!("cycle({print_idx:03}) ∈ {scc_tag}: {acc} *");
}
sccs
}
#[cfg(feature = "graph")]
pub(crate) fn graphviz(self, dest: &mut impl std::io::Write) -> std::io::Result<()> {
use self::graph_helpers::*;
use petgraph::{
dot::{self, Dot},
visit::{EdgeRef, IntoEdgeReferences, IntoNodeReferences},
};
let config = &[
dot::Config::GraphContentOnly,
dot::Config::EdgeNoLabel,
dot::Config::NodeNoLabel,
][..];
let Self { mut graph, unsent_messages, unconsumed_messages, sccs } = self;
let greek_alphabet = greek_alphabet();
const COLOR_SCHEME_N: usize = 10; const UPPER_BOUND: usize = 10;
assert!(UPPER_BOUND <= GREEK_ALPHABET_SIZE);
assert!(UPPER_BOUND <= COLOR_SCHEME_N);
let n = sccs.len();
let n = if n > UPPER_BOUND {
eprintln!("Too many ({n}) strongly connected components, only annotating the first {UPPER_BOUND}");
UPPER_BOUND
} else {
n
};
let mut scc_lut = HashMap::<NodeIndex, HashSet<char>>::with_capacity(n);
let mut color_lut = HashMap::<char, usize>::with_capacity(COLOR_SCHEME_N);
for (scc_idx, scc) in sccs.into_iter().take(UPPER_BOUND).enumerate() {
for node_idx in scc {
let _ = scc_lut.entry(node_idx).or_default().insert(greek_alphabet[scc_idx]);
}
color_lut.insert(greek_alphabet[scc_idx], scc_idx + 1);
}
let color_lut = &color_lut;
let unconsumed_idx = graph.add_node(quote::format_ident!("SENT_TO_NONONE"));
for (message_name, subsystems) in unconsumed_messages {
for (_sub_name, sub_node_idx) in subsystems {
graph.add_edge(sub_node_idx, unconsumed_idx, message_name.clone());
}
}
let unsent_idx = graph.add_node(quote::format_ident!("NEVER_SENT_ANYWHERE"));
for (message_name, (_sub_name, sub_node_idx)) in unsent_messages {
graph.add_edge(unsent_idx, sub_node_idx, message_name.clone());
}
let unsent_node_label = r#"label="✨",fillcolor=black,shape=doublecircle,style=filled,fontname="NotoColorEmoji""#;
let unconsumed_node_label = r#"label="💀",fillcolor=black,shape=doublecircle,style=filled,fontname="NotoColorEmoji""#;
let edge_attr = |_graph: &Graph<Ident, Path>,
edge: <&Graph<Ident, Path> as IntoEdgeReferences>::EdgeRef|
-> String {
let source = edge.source();
let sink = edge.target();
let message_name =
edge.weight().get_ident().expect("Must have a trailing identifier. qed");
if let Some(edge_intersecting_scc_tags) = scc_lut.get(&source).and_then(|source_set| {
scc_lut.get(&sink).and_then(move |sink_set| {
let intersection =
HashSet::<_, RandomState>::from_iter(source_set.intersection(sink_set));
if intersection.is_empty() {
None
} else {
Some(intersection)
}
})
}) {
if edge_intersecting_scc_tags.len() != 1 {
unreachable!("Strongly connected components are disjunct by definition. qed");
}
let scc_tag = edge_intersecting_scc_tags.iter().next().unwrap();
let color = get_color_by_tag(scc_tag, color_lut);
let scc_tag_str = cycle_tags_to_annotation(edge_intersecting_scc_tags, color_lut);
format!(
r#"color="{color}",fontcolor="{color}",xlabel=<{scc_tag_str}>,label="{message_name}""#,
)
} else {
format!(r#"label="{message_name}""#,)
}
};
let node_attr =
|_graph: &Graph<Ident, Path>,
(node_index, subsystem_name): <&Graph<Ident, Path> as IntoNodeReferences>::NodeRef|
-> String {
if node_index == unsent_idx {
unsent_node_label.to_owned().clone()
} else if node_index == unconsumed_idx {
unconsumed_node_label.to_owned().clone()
} else if let Some(edge_intersecting_scc_tags) = scc_lut.get(&node_index) {
if edge_intersecting_scc_tags.len() != 1 {
unreachable!(
"Strongly connected components are disjunct by definition. qed"
);
};
let scc_tag = edge_intersecting_scc_tags.iter().next().unwrap();
let color = get_color_by_tag(scc_tag, color_lut);
let scc_tag_str =
cycle_tags_to_annotation(edge_intersecting_scc_tags, color_lut);
format!(
r#"color="{color}",fontcolor="{color}",xlabel=<{scc_tag_str}>,label="{subsystem_name}""#,
)
} else {
format!(r#"label="{subsystem_name}""#)
}
};
let dot = Dot::with_attr_getters(
&graph, config, &edge_attr, &node_attr,
);
dest.write_all(
format!(
r#"digraph {{
node [colorscheme={}]
{:?}
}}"#,
color_scheme(),
&dot
)
.as_bytes(),
)?;
Ok(())
}
}
const GREEK_ALPHABET_SIZE: usize = 24;
fn greek_alphabet() -> [char; GREEK_ALPHABET_SIZE] {
let mut alphabet = ['\u{03B1}'; 24];
alphabet
.iter_mut()
.enumerate()
.for_each(|(i, c)| {
*c = char::from_u32(*c as u32 + i as u32).unwrap();
});
alphabet
}
#[cfg(feature = "graph")]
mod graph_helpers {
use super::HashMap;
pub(crate) const fn color_scheme() -> &'static str {
"rdylgn10"
}
pub(crate) fn get_color_by_idx(color_idx: usize) -> String {
let scheme = color_scheme();
format!("/{scheme}/{color_idx}")
}
pub(crate) fn get_color_by_tag(scc_tag: &char, color_lut: &HashMap<char, usize>) -> String {
get_color_by_idx(color_lut.get(scc_tag).copied().unwrap_or_default())
}
pub(crate) fn cycle_tags_to_annotation<'a>(
cycle_tags: impl IntoIterator<Item = &'a char>,
color_lut: &HashMap<char, usize>,
) -> String {
let cycle_annotation = String::from_iter(itertools::Itertools::intersperse(
cycle_tags.into_iter().map(|scc_tag| {
let color = get_color_by_tag(scc_tag, color_lut);
format!(r#"<B><FONT COLOR="{color}">{scc_tag}</FONT></B>"#)
}),
",".to_owned(),
));
cycle_annotation
}
}
#[cfg(test)]
mod tests {
#[test]
#[should_panic]
fn check_ident() {
let _ident = quote::format_ident!("x💀x");
}
#[test]
fn kosaraju_scc_check_nodes_cannot_be_part_of_two_clusters() {
let mut graph = petgraph::graph::DiGraph::<char, &str>::new();
let a_idx = graph.add_node('A');
let b_idx = graph.add_node('B');
let c_idx = graph.add_node('C');
let d_idx = graph.add_node('D');
let e_idx = graph.add_node('E');
let f_idx = graph.add_node('F');
graph.add_edge(a_idx, b_idx, "10");
graph.add_edge(b_idx, c_idx, "11");
graph.add_edge(c_idx, a_idx, "12");
graph.add_edge(a_idx, d_idx, "20");
graph.add_edge(d_idx, c_idx, "21");
graph.add_edge(b_idx, e_idx, "30");
graph.add_edge(e_idx, c_idx, "31");
graph.add_edge(c_idx, f_idx, "40");
let mut sccs = dbg!(petgraph::algo::kosaraju_scc(&graph));
dbg!(graph);
sccs.sort_by(|a, b| {
if a.len() < b.len() {
std::cmp::Ordering::Greater
} else {
std::cmp::Ordering::Less
}
});
assert_eq!(sccs.len(), 2); assert_eq!(sccs[0].len(), 5); }
}