1use std::io::{ErrorKind, Write};
5use std::process::{Command, Stdio};
6use std::{fmt, io};
7
8use itertools::Itertools;
9
10use crate::algebra::{remove_fn_prefix, remove_prefix, DYTerm, Term, TermType};
11use crate::protocol::ProtocolTypes;
12use crate::trace::{Action, Trace};
13
14const FONT: &str = "Latin Modern Roman";
25const SHAPE: &str = "none";
26const SHAPE_PAYLOAD: &str = "box";
27const SHAPE_LEAVES: &str = "none";
28const SHAPE_LEAVES_PAYLOAD: &str = "parallelogram";
29
30const STYLE: &str = "";
31const COLOR: &str = "#ffff0000";
32const COLOR_LEAVES: &str = "#00000000";
33const COLOR_LEAVES_PAYLOAD: &str = "#ff00ff";
34const COLOR_PAYLOAD: &str = "#ff0000";
35const SHOW_LABELS: bool = false;
36
37pub fn write_graphviz(output: &str, format: &str, dot_script: &str) -> Result<(), io::Error> {
38 let mut child = Command::new("dot")
39 .args(["-o", output, "-T", format])
40 .stdin(Stdio::piped())
41 .spawn()
42 .map_err(|err| {
43 if err.kind() == ErrorKind::NotFound {
44 io::Error::new(
45 ErrorKind::NotFound,
46 "Unable to find dot in PATH. Install graphviz.",
47 )
48 } else {
49 err
50 }
51 })?;
52
53 let mut dot_stdin = child
54 .stdin
55 .take()
56 .ok_or_else(|| io::Error::new(ErrorKind::Other, "Failed to open stdin"))?;
57 dot_stdin.write_all(dot_script.as_bytes().as_ref())?;
58 drop(dot_stdin);
59 child.wait()?;
60 Ok(())
61}
62
63impl<PT: ProtocolTypes> Trace<PT> {
64 #[must_use]
65 pub fn dot_graph(&self, tree_mode: bool) -> String {
66 format!(
67 "strict digraph \"Trace\" \
68 {{ \
69 splines=false;\
70 fontname=\"{}\";\
71 {} \
72 }}",
73 FONT,
74 self.dot_subgraphs(tree_mode).join("\n")
75 )
76 }
77
78 #[must_use]
79 pub fn dot_subgraphs(&self, tree_mode: bool) -> Vec<String> {
80 log::warn!("Calling dot_subgraphs on: {}", self);
81 let mut subgraphs = Vec::new();
82
83 for (i, step) in self.steps.iter().enumerate() {
84 let subgraph_name = format!("Step #{} (Agent {})", i, step.agent);
85
86 let subgraph = match &step.action {
87 Action::Input(input) => input
88 .recipe
89 .dot_subgraph(tree_mode, i, subgraph_name.as_str())
90 .to_string(), Action::Output(_) => format!(
92 "subgraph cluster{} \
93 {{ \
94 peripheries=0;\
95 label=\"{label}\";\
96 \"\" [color=\"#00000000\"];\
97 }}",
98 i,
99 label = (if SHOW_LABELS {
100 subgraph_name.as_str()
101 } else {
102 ""
103 }),
104 ),
105 };
106
107 subgraphs.push(subgraph);
108 }
109
110 subgraphs
111 }
112}
113
114impl<PT: ProtocolTypes> Term<PT> {
115 fn unique_id(&self, tree_mode: bool, cluster_id: usize) -> String {
116 match &self.term {
117 DYTerm::Variable(variable) => {
118 if tree_mode {
119 format!("v_{}_{}", cluster_id, variable.unique_id)
120 } else {
121 format!("v_{}", variable.resistant_id)
122 }
123 }
124 DYTerm::Application(func, _) => {
125 if tree_mode {
126 format!("f_{}_{}", cluster_id, func.unique_id)
127 } else {
128 format!("f_{}", func.resistant_id)
129 }
130 }
131 }
132 }
133
134 fn node_attributes(displayable: impl fmt::Display, color: &str, shape: &str) -> String {
135 format!(
136 "[label=\"{displayable}\",style=\"{STYLE}\",colorscheme=dark28,fillcolor=\"{color}\",shape=\"{shape}\"]"
137 )
138 }
139
140 fn collect_statements(
141 term: &Self,
142 tree_mode: bool,
143 cluster_id: usize,
144 statements: &mut Vec<String>,
145 ) {
146 if !term.is_symbolic() {
147 log::debug!("WITH PAYLOADS: {:?} on term {}", term.all_payloads(), term);
148 }
149 match &term.term {
150 DYTerm::Variable(variable) => {
151 let color = if term.is_symbolic() {
152 COLOR_LEAVES
153 } else {
154 COLOR_LEAVES_PAYLOAD
155 };
156 let shape = if term.is_symbolic() {
157 SHAPE_LEAVES
158 } else {
159 SHAPE_LEAVES_PAYLOAD
160 };
161 statements.push(format!(
162 "{} {} [fontname=\"{}\"];",
163 term.unique_id(tree_mode, cluster_id),
164 Self::node_attributes(variable, color, shape),
165 FONT
166 ));
167 }
168 DYTerm::Application(func, subterms) => {
169 let color = if term.is_symbolic() {
170 if func.arity() == 0 {
171 COLOR_LEAVES
172 } else {
173 COLOR
174 }
175 } else {
176 COLOR_PAYLOAD
177 };
178 let shape = if term.is_symbolic() {
179 if func.arity() == 0 {
180 SHAPE_LEAVES
181 } else {
182 SHAPE
183 }
184 } else {
185 SHAPE_PAYLOAD
186 };
187 statements.push(format!(
188 "{} {} [fontname=\"{}\"];",
189 term.unique_id(tree_mode, cluster_id),
190 Self::node_attributes(
191 if term.is_symbolic() {
192 remove_fn_prefix(&remove_prefix(func.name()))
193 } else if term.is_readable() {
194 format!("BS-RD//{}", remove_fn_prefix(&remove_prefix(func.name())))
195 } else {
196 format!("BS//{}", remove_prefix(func.name()))
197 },
198 color,
199 shape,
200 ),
201 FONT
202 ));
203
204 for subterm in subterms {
205 statements.push(format!(
206 "{} -> {};",
207 term.unique_id(tree_mode, cluster_id),
208 subterm.unique_id(tree_mode, cluster_id)
209 ));
210 Self::collect_statements(subterm, tree_mode, cluster_id, statements);
211 }
212 }
213 }
214 }
215
216 pub fn dot_subgraph(&self, tree_mode: bool, cluster_id: usize, label: &str) -> String {
220 let mut statements = Vec::new();
221 Self::collect_statements(self, tree_mode, cluster_id, &mut statements);
222 format!(
223 "subgraph cluster{} \
224 {{ \
225 peripheries=0;\
226 fontname=\"{font}\";\
227 label=\"{label}\";\
228 \n{}\n\
229 }}",
230 cluster_id,
231 statements.iter().join("\n"),
232 label = (if SHOW_LABELS { label } else { "" }),
233 font = FONT,
234 )
235 }
236}
237
238#[cfg(test)]
239mod tests {
240 use crate::algebra::test_signature::setup_simple_trace;
241
242 #[test_log::test]
243 fn test_dot_graph() {
244 let trace = setup_simple_trace();
245 let _string = trace.dot_graph(true);
246 }
248}