Skip to main content

flow_runner/document/
graph.rs

1//! The [`Graph`] a builder draws.
2
3use 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/// Everything a builder needs to draw a flow. Expression texts are exactly
10/// as written in the file; spans are byte offsets into [`Document::text`].
11#[derive(Debug, Clone, PartialEq)]
12pub struct Graph {
13    /// The name after `flow`, when there is one.
14    pub name: Option<String>,
15    /// The annotations on the `flow` declaration.
16    pub annotations: Vec<AnnotationView>,
17    /// The nodes under `entry`, in file order.
18    pub entries: Vec<String>,
19    /// The declared events, in file order.
20    pub events: Vec<String>,
21    /// The params, in file order.
22    pub params: Vec<ParamView>,
23    /// Flow-level lets and helpers.
24    pub lets: Vec<LetView>,
25    /// The nodes, in file order.
26    pub nodes: Vec<NodeView>,
27    /// Jumps and ask continuations, in node and branch order.
28    pub edges: Vec<Edge>,
29}
30
31/// An annotation as written.
32#[derive(Debug, Clone, PartialEq)]
33pub struct AnnotationView {
34    /// The name after `@`.
35    pub name: String,
36    /// The value, or `None` when it isn't a literal. A bare `@name` is `true`.
37    pub value: Option<Value>,
38    /// The value as written; `None` for a bare `@name`.
39    pub text: Option<String>,
40    /// Where the annotation is.
41    pub span: Span,
42}
43
44/// A `param` declaration as written.
45#[derive(Debug, Clone, PartialEq)]
46pub struct ParamView {
47    /// The param's name.
48    pub name: String,
49    /// The default, or `None` when it isn't a literal.
50    pub default: Option<Value>,
51    /// The default as written.
52    pub default_text: String,
53    /// The annotations on it.
54    pub annotations: Vec<AnnotationView>,
55    /// Where the declaration is, without its annotations.
56    pub span: Span,
57}
58
59/// A `let` or helper declaration as written.
60#[derive(Debug, Clone, PartialEq)]
61pub struct LetView {
62    /// The name it binds.
63    pub name: String,
64    /// `Some` for a helper `let name(a, b) = ...`.
65    pub params: Option<Vec<String>>,
66    /// The expression as written.
67    pub expression: String,
68    /// Where the declaration is.
69    pub span: Span,
70}
71
72/// A `node` declaration as written.
73#[derive(Debug, Clone, PartialEq)]
74pub struct NodeView {
75    /// The node's name.
76    pub name: String,
77    /// Its parameter names.
78    pub params: Vec<String>,
79    /// The annotations on it.
80    pub annotations: Vec<AnnotationView>,
81    /// Its lets, in order.
82    pub lets: Vec<LetView>,
83    /// Its branches, or its single outcome as one branch.
84    pub branches: Vec<BranchView>,
85    /// Whether it is listed under `entry`.
86    pub is_entry: bool,
87    /// False for a node written as a single outcome, without `when`.
88    pub uses_when: bool,
89    /// Where the declaration is, without its annotations.
90    pub span: Span,
91}
92
93/// One branch of a node: a `when` branch, or the node's single outcome.
94#[derive(Debug, Clone, PartialEq)]
95pub struct BranchView {
96    /// `None` for `else`, or for a node's single outcome.
97    pub guard: Option<String>,
98    /// What the branch does.
99    pub outcome: OutcomeView,
100    /// Where the branch is.
101    pub span: Span,
102}
103
104/// What a branch does, with each expression as written.
105#[derive(Debug, Clone, PartialEq)]
106#[non_exhaustive]
107pub enum OutcomeView {
108    /// `target(args)`.
109    Jump {
110        /// The node jumped to.
111        target: String,
112        /// The arguments.
113        args: Vec<String>,
114    },
115    /// A value, and when to wake.
116    Value {
117        /// The value.
118        template: String,
119        /// The `wake` expression.
120        wake: Option<String>,
121    },
122    /// `ask name(payload) -> target(args)`.
123    Ask {
124        /// The ask's name.
125        name: String,
126        /// What to ask with.
127        payload: Option<String>,
128        /// The node the answer continues at.
129        target: String,
130        /// Its arguments.
131        args: Vec<String>,
132    },
133    /// `ignore`.
134    Ignore,
135}
136
137/// A way from one node to another.
138#[derive(Debug, Clone, PartialEq)]
139pub struct Edge {
140    /// The node it leaves.
141    pub from: String,
142    /// The node it reaches.
143    pub to: String,
144    /// Index of the branch in `from` the edge leaves by.
145    pub branch: usize,
146    /// How it is taken.
147    pub kind: EdgeKind,
148}
149
150/// How an [`Edge`] is taken.
151#[derive(Debug, Clone, PartialEq)]
152#[non_exhaustive]
153pub enum EdgeKind {
154    /// A jump.
155    Jump,
156    /// An ask continuation, with the ask's name.
157    Ask(String),
158}
159
160impl Document {
161    /// The flow as a [`Graph`] to draw.
162    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, &param.default),
187                    default_text: self.slice(param.default.span()).to_string(),
188                    annotations: self.annotation_views(&param.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            // a helper in a node is an error; show it as a plain let
230            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    /// The graph as JSON, for builders written in other languages.
334    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(&param.default), "defaultText": param.default_text,
390                "annotations": annotations(&param.annotations), "span": span(&param.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}