1use super::Document;
4use crate::compile::literal;
5use crate::syntax::ast::{Annotation, Body, Guard, LetDeclaration, NodeDeclaration, Outcome};
6use std::collections::HashSet;
7use temple_dsl::{ParsedExpr, Span, Value};
8
9#[derive(Debug, Clone, PartialEq)]
12pub struct Graph {
13 pub name: Option<String>,
15 pub annotations: Vec<AnnotationView>,
17 pub entries: Vec<String>,
19 pub events: Vec<String>,
21 pub params: Vec<ParamView>,
23 pub lets: Vec<LetView>,
25 pub nodes: Vec<NodeView>,
27 pub edges: Vec<Edge>,
29}
30
31#[derive(Debug, Clone, PartialEq)]
33pub struct AnnotationView {
34 pub name: String,
36 pub value: Option<Value>,
38 pub text: Option<String>,
40 pub span: Span,
42}
43
44#[derive(Debug, Clone, PartialEq)]
46pub struct ParamView {
47 pub name: String,
49 pub default: Option<Value>,
51 pub default_text: String,
53 pub annotations: Vec<AnnotationView>,
55 pub span: Span,
57}
58
59#[derive(Debug, Clone, PartialEq)]
61pub struct LetView {
62 pub name: String,
64 pub params: Option<Vec<String>>,
66 pub expression: String,
68 pub span: Span,
70}
71
72#[derive(Debug, Clone, PartialEq)]
74pub struct NodeView {
75 pub name: String,
77 pub params: Vec<String>,
79 pub annotations: Vec<AnnotationView>,
81 pub lets: Vec<LetView>,
83 pub branches: Vec<BranchView>,
85 pub is_entry: bool,
87 pub uses_when: bool,
89 pub span: Span,
91}
92
93#[derive(Debug, Clone, PartialEq)]
95pub struct BranchView {
96 pub guard: Option<String>,
98 pub outcome: OutcomeView,
100 pub span: Span,
102}
103
104#[derive(Debug, Clone, PartialEq)]
106#[non_exhaustive]
107pub enum OutcomeView {
108 Jump {
110 target: String,
112 args: Vec<String>,
114 },
115 Value {
117 template: String,
119 wake: Option<String>,
121 },
122 Ask {
124 name: String,
126 payload: Option<String>,
128 target: String,
130 args: Vec<String>,
132 },
133 Ignore,
135}
136
137#[derive(Debug, Clone, PartialEq)]
139pub struct Edge {
140 pub from: String,
142 pub to: String,
144 pub branch: usize,
146 pub kind: EdgeKind,
148}
149
150#[derive(Debug, Clone, PartialEq)]
152#[non_exhaustive]
153pub enum EdgeKind {
154 Jump,
156 Ask(String),
158}
159
160impl Document {
161 pub fn graph(&self) -> Graph {
163 let ast = &self.ast;
164 let entries: HashSet<&str> = ast.entry_names().map(|entry| entry.name.as_str()).collect();
165 let nodes: Vec<NodeView> = ast
166 .nodes
167 .iter()
168 .map(|node| self.node_view(node, &entries))
169 .collect();
170 Graph {
171 name: ast.name.as_ref().map(|name| name.name.to_string()),
172 annotations: self.annotation_views(&ast.annotations),
173 entries: ast
174 .entry_names()
175 .map(|entry| entry.name.to_string())
176 .collect(),
177 events: ast
178 .event_names()
179 .map(|event| event.name.to_string())
180 .collect(),
181 params: ast
182 .params
183 .iter()
184 .map(|param| ParamView {
185 name: param.name.name.to_string(),
186 default: literal::value(&self.text, ¶m.default),
187 default_text: self.slice(param.default.span()).to_string(),
188 annotations: self.annotation_views(¶m.annotations),
189 span: param.span,
190 })
191 .collect(),
192 lets: ast
193 .lets
194 .iter()
195 .map(|binding| self.let_view(binding))
196 .collect(),
197 edges: edges(&nodes),
198 nodes,
199 }
200 }
201
202 fn node_view(&self, node: &NodeDeclaration, entries: &HashSet<&str>) -> NodeView {
203 let branches = match &node.body {
204 Body::Single(outcome) => vec![BranchView {
205 guard: None,
206 outcome: self.outcome_view(outcome),
207 span: outcome.span(),
208 }],
209 Body::When { branches, .. } => branches
210 .iter()
211 .map(|branch| BranchView {
212 guard: match &branch.guard {
213 Guard::Else(_) => None,
214 Guard::Expression(guard) => Some(self.slice(guard.span()).to_string()),
215 },
216 outcome: self.outcome_view(&branch.outcome),
217 span: branch.span,
218 })
219 .collect(),
220 };
221 NodeView {
222 name: node.name.name.to_string(),
223 params: node
224 .params
225 .iter()
226 .map(|param| param.name.to_string())
227 .collect(),
228 annotations: self.annotation_views(&node.annotations),
229 lets: node
231 .lets
232 .iter()
233 .map(|binding| LetView {
234 params: None,
235 ..self.let_view(binding)
236 })
237 .collect(),
238 branches,
239 is_entry: entries.contains(node.name.name.as_str()),
240 uses_when: matches!(node.body, Body::When { .. }),
241 span: node.span,
242 }
243 }
244
245 fn let_view(&self, binding: &LetDeclaration) -> LetView {
246 LetView {
247 name: binding.name.name.to_string(),
248 params: binding
249 .params
250 .as_ref()
251 .map(|params| params.iter().map(|param| param.name.to_string()).collect()),
252 expression: self.slice(binding.expression.span()).to_string(),
253 span: binding.span,
254 }
255 }
256
257 fn annotation_views(&self, annotations: &[Annotation]) -> Vec<AnnotationView> {
258 annotations
259 .iter()
260 .map(|annotation| AnnotationView {
261 name: annotation.name.name.to_string(),
262 value: match &annotation.value {
263 None => Some(Value::Bool(true)),
264 Some(value) => literal::value(&self.text, value),
265 },
266 text: annotation
267 .value
268 .as_ref()
269 .map(|value| self.slice(value.span()).to_string()),
270 span: annotation.span,
271 })
272 .collect()
273 }
274
275 fn outcome_view(&self, outcome: &Outcome) -> OutcomeView {
276 let texts = |args: &[ParsedExpr]| {
277 args.iter()
278 .map(|arg| self.slice(arg.span()).to_string())
279 .collect()
280 };
281 match outcome {
282 Outcome::Jump { target, args, .. } => OutcomeView::Jump {
283 target: target.name.to_string(),
284 args: texts(args),
285 },
286 Outcome::Value { template, wake, .. } => OutcomeView::Value {
287 template: self.slice(template.span()).to_string(),
288 wake: wake
289 .as_ref()
290 .map(|wake| self.slice(wake.span()).to_string()),
291 },
292 Outcome::Ask {
293 name,
294 payload,
295 target,
296 args,
297 ..
298 } => OutcomeView::Ask {
299 name: name.name.to_string(),
300 payload: payload
301 .as_ref()
302 .map(|payload| self.slice(payload.span()).to_string()),
303 target: target.name.to_string(),
304 args: texts(args),
305 },
306 Outcome::Ignore { .. } => OutcomeView::Ignore,
307 }
308 }
309}
310
311fn edges(nodes: &[NodeView]) -> Vec<Edge> {
312 let mut edges = Vec::new();
313 for node in nodes {
314 for (branch, view) in node.branches.iter().enumerate() {
315 let (to, kind) = match &view.outcome {
316 OutcomeView::Jump { target, .. } => (target, EdgeKind::Jump),
317 OutcomeView::Ask { name, target, .. } => (target, EdgeKind::Ask(name.clone())),
318 OutcomeView::Value { .. } | OutcomeView::Ignore => continue,
319 };
320 edges.push(Edge {
321 from: node.name.clone(),
322 to: to.clone(),
323 branch,
324 kind,
325 });
326 }
327 }
328 edges
329}
330
331#[cfg(feature = "json")]
332impl Graph {
333 pub fn to_json(&self) -> serde_json::Value {
335 use serde_json::{json, Value as Json};
336 let span = |span: &Span| json!([span.start, span.end]);
337 let value = |value: &Option<Value>| value.clone().map_or(Json::Null, Json::from);
338 let annotations = |annotations: &[AnnotationView]| -> Json {
339 annotations
340 .iter()
341 .map(|annotation| {
342 json!({
343 "name": annotation.name, "value": value(&annotation.value),
344 "text": annotation.text, "span": span(&annotation.span),
345 })
346 })
347 .collect()
348 };
349 let lets = |lets: &[LetView]| -> Json {
350 lets.iter()
351 .map(|binding| {
352 json!({
353 "name": binding.name, "params": binding.params,
354 "expression": binding.expression, "span": span(&binding.span),
355 })
356 })
357 .collect()
358 };
359 let outcome = |outcome: &OutcomeView| match outcome {
360 OutcomeView::Jump { target, args } => {
361 json!({ "kind": "jump", "target": target, "args": args })
362 }
363 OutcomeView::Value { template, wake } => {
364 json!({ "kind": "value", "template": template, "wake": wake })
365 }
366 OutcomeView::Ask {
367 name,
368 payload,
369 target,
370 args,
371 } => json!({
372 "kind": "ask", "name": name, "payload": payload, "target": target, "args": args,
373 }),
374 OutcomeView::Ignore => json!({ "kind": "ignore" }),
375 };
376 let edge = |edge: &Edge| {
377 let (kind, ask) = match &edge.kind {
378 EdgeKind::Jump => ("jump", None),
379 EdgeKind::Ask(name) => ("ask", Some(name)),
380 };
381 json!({ "from": edge.from, "to": edge.to, "branch": edge.branch, "kind": kind, "ask": ask })
382 };
383 json!({
384 "name": self.name,
385 "annotations": annotations(&self.annotations),
386 "entries": self.entries,
387 "events": self.events,
388 "params": self.params.iter().map(|param| json!({
389 "name": param.name, "default": value(¶m.default), "defaultText": param.default_text,
390 "annotations": annotations(¶m.annotations), "span": span(¶m.span),
391 })).collect::<Json>(),
392 "lets": lets(&self.lets),
393 "nodes": self.nodes.iter().map(|node| json!({
394 "name": node.name, "params": node.params, "annotations": annotations(&node.annotations), "lets": lets(&node.lets),
395 "isEntry": node.is_entry, "usesWhen": node.uses_when, "span": span(&node.span),
396 "branches": node.branches.iter().map(|branch| json!({
397 "guard": branch.guard, "outcome": outcome(&branch.outcome), "span": span(&branch.span),
398 })).collect::<Json>(),
399 })).collect::<Json>(),
400 "edges": self.edges.iter().map(edge).collect::<Json>(),
401 })
402 }
403}