Skip to main content

flow_runner/
flow.rs

1//! A compiled flow: its node table, and what a host can read from it.
2
3use crate::common::diagnostic::Diagnostic;
4use crate::syntax::lexer::Mode;
5use indexmap::IndexSet;
6use smol_str::SmolStr;
7use std::collections::{HashMap, HashSet};
8use std::sync::Arc;
9use temple_dsl::{ExprUnit, Functions, InputRead, Span, TemplateUnit, Value};
10
11/// Bytes in a flow hash.
12pub(crate) const HASH_LEN: usize = 32;
13
14/// A compiled flow. Compile it once with [`Flow::compile`], store it with
15/// [`Flow::to_bytes`] and load it with [`Flow::from_bytes`]. It is immutable
16/// and can be shared between threads.
17#[derive(Debug, Clone)]
18pub struct Flow {
19    pub(crate) name: SmolStr,
20    pub(crate) edition: u32,
21    pub(crate) annotations: Vec<Annotation>,
22    pub(crate) entries: Vec<NodeId>,
23    pub(crate) events: IndexSet<SmolStr>,
24    pub(crate) params: Vec<Param>,
25    pub(crate) lets: Vec<Let>,
26    pub(crate) helpers: Vec<Helper>,
27    pub(crate) functions: Functions,
28    pub(crate) nodes: Vec<Node>,
29    pub(crate) node_ids: HashMap<SmolStr, NodeId>,
30    /// Where each param sits in `params`.
31    pub(crate) param_positions: HashMap<SmolStr, usize>,
32    /// Every ask name, first use first.
33    pub(crate) asks: IndexSet<SmolStr>,
34    pub(crate) hash: [u8; HASH_LEN],
35    pub(crate) warnings: Vec<Diagnostic>,
36    pub(crate) source: Arc<str>,
37}
38
39/// Where a node sits in the flow's node table. Jumps and asks refer to
40/// nodes by id, so a run never looks a name up.
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
42pub(crate) struct NodeId(pub(crate) u32);
43
44impl NodeId {
45    pub(crate) fn index(self) -> usize {
46        self.0 as usize
47    }
48}
49
50/// `@name = value` on a flow, a param or a node, with its value evaluated.
51#[derive(Debug, Clone, PartialEq)]
52pub struct Annotation {
53    /// The name after `@`.
54    pub name: String,
55    /// The value; `true` for a bare `@name`.
56    pub value: Value,
57}
58
59/// A flow parameter: a constant the host may set when an instance starts.
60#[derive(Debug, Clone, PartialEq)]
61pub struct Param {
62    /// The param's name.
63    pub name: String,
64    /// The value an instance gets when the host doesn't set one.
65    pub default: Value,
66    /// The annotations on the `param` declaration.
67    pub annotations: Vec<Annotation>,
68}
69
70/// A `let name = expression`, at flow or node level, compiled.
71#[derive(Debug, Clone)]
72pub(crate) struct Let {
73    pub name: SmolStr,
74    pub expression: ExprUnit,
75}
76
77/// A helper, `let name(a, b) = expression` at flow level, compiled.
78#[derive(Debug, Clone)]
79pub(crate) struct Helper {
80    pub name: SmolStr,
81    pub params: Vec<SmolStr>,
82    pub body: ExprUnit,
83}
84
85/// A node, compiled.
86#[derive(Debug, Clone)]
87pub(crate) struct Node {
88    pub name: SmolStr,
89    pub params: Vec<SmolStr>,
90    pub annotations: Vec<Annotation>,
91    pub lets: Vec<Let>,
92    pub branches: Vec<Branch>,
93    /// True when some `ask` continues here.
94    pub resumes_ask: bool,
95    pub is_entry: bool,
96    pub span: Span,
97}
98
99/// One branch of a node, compiled.
100#[derive(Debug, Clone)]
101pub(crate) struct Branch {
102    /// `None` is `else`, or a node's only outcome.
103    pub guard: Option<ExprUnit>,
104    pub outcome: Outcome,
105    /// The guard holds only while an event is delivered, so the branch
106    /// can't be taken again after a jump.
107    pub needs_event: bool,
108    pub span: Span,
109}
110
111/// What a branch does, compiled: nodes by id, units ready to run.
112#[derive(Debug, Clone)]
113pub(crate) enum Outcome {
114    Jump {
115        node: NodeId,
116        args: Vec<ExprUnit>,
117    },
118    Value {
119        template: TemplateUnit,
120        wake: Option<ExprUnit>,
121    },
122    Ask {
123        name: SmolStr,
124        payload: Option<ExprUnit>,
125        node: NodeId,
126        args: Vec<ExprUnit>,
127    },
128    Ignore,
129}
130
131impl Outcome {
132    /// The outcome's expressions and values, in source order.
133    fn units(&self) -> impl Iterator<Item = UnitRef<'_>> {
134        let (payload, template, args, wake) = match self {
135            Outcome::Jump { args, .. } => (None, None, args.as_slice(), None),
136            Outcome::Value { template, wake } => {
137                (None, Some(template), [].as_slice(), wake.as_ref())
138            }
139            Outcome::Ask { payload, args, .. } => (payload.as_ref(), None, args.as_slice(), None),
140            Outcome::Ignore => (None, None, [].as_slice(), None),
141        };
142        payload
143            .map(UnitRef::Expression)
144            .into_iter()
145            .chain(template.map(UnitRef::Template))
146            .chain(args.iter().map(UnitRef::Expression))
147            .chain(wake.map(UnitRef::Expression))
148    }
149}
150
151impl Node {
152    fn units(&self) -> impl Iterator<Item = UnitRef<'_>> {
153        let lets = self
154            .lets
155            .iter()
156            .map(|binding| UnitRef::Expression(&binding.expression));
157        let branches = self.branches.iter().flat_map(|branch| {
158            let guard = branch.guard.iter().map(UnitRef::Expression);
159            guard.chain(branch.outcome.units())
160        });
161        lets.chain(branches)
162    }
163
164    /// Where each of the node's expressions and values is in the source,
165    /// and how it reads.
166    pub(crate) fn unit_spans(&self) -> impl Iterator<Item = (Span, Mode)> + '_ {
167        self.units().map(|unit| match unit {
168            UnitRef::Expression(unit) => (unit.span(), Mode::Expression),
169            UnitRef::Template(unit) => (unit.span(), Mode::Output),
170        })
171    }
172
173    pub(crate) fn reads(&self) -> Vec<InputRead> {
174        self.units().flat_map(|unit| unit.reads()).collect()
175    }
176}
177
178/// Either kind of compiled unit, for questions both can answer.
179enum UnitRef<'a> {
180    Expression(&'a ExprUnit),
181    Template(&'a TemplateUnit),
182}
183
184impl UnitRef<'_> {
185    fn reads(&self) -> Vec<InputRead> {
186        match self {
187            UnitRef::Expression(unit) => unit.reads(),
188            UnitRef::Template(unit) => unit.reads(),
189        }
190    }
191}
192
193/// What a builder or host can read about one node.
194#[derive(Debug, Clone, PartialEq)]
195pub struct NodeInfo<'a> {
196    /// The node's name.
197    pub name: &'a str,
198    /// The node's parameter names, in order.
199    pub params: Vec<&'a str>,
200    /// The annotations on the `node` declaration.
201    pub annotations: &'a [Annotation],
202    /// True when the flow lists the node under `entry`.
203    pub is_entry: bool,
204    /// True when an `ask` continues here.
205    pub resumes_ask: bool,
206    /// Nodes this node can jump to, in branch order, without repeats.
207    pub jumps_to: Vec<&'a str>,
208    /// Each ask in this node, in branch order.
209    pub asks: Vec<AskInfo<'a>>,
210    /// Number of branches, counting `else` or the single outcome.
211    pub branch_count: usize,
212}
213
214/// One `ask name(payload) -> node(args)` in a node.
215#[derive(Debug, Clone, Copy, PartialEq, Eq)]
216pub struct AskInfo<'a> {
217    /// The ask's name, for the host to resolve.
218    pub name: &'a str,
219    /// The node the run continues at with the answer.
220    pub node: &'a str,
221}
222
223impl Flow {
224    /// The name after `flow`.
225    pub fn name(&self) -> &str {
226        &self.name
227    }
228
229    /// The language edition the flow is written in.
230    pub fn edition(&self) -> u32 {
231        self.edition
232    }
233
234    /// The flow's version as hex. It changes when what the flow does
235    /// changes, and not when only its layout, comments or annotations do.
236    pub fn hash(&self) -> String {
237        hex(&self.hash)
238    }
239
240    /// The nodes a new run may start at.
241    pub fn entries(&self) -> impl Iterator<Item = &str> {
242        self.entries.iter().map(|&id| self.node_name(id))
243    }
244
245    /// Declared events. `tick` is always accepted too.
246    pub fn events(&self) -> impl Iterator<Item = &str> {
247        self.events.iter().map(SmolStr::as_str)
248    }
249
250    /// Params in declaration order, with their defaults.
251    pub fn params(&self) -> &[Param] {
252        &self.params
253    }
254
255    /// Every ask name the flow can produce, e.g. to check that the host
256    /// resolves each of them before deploying.
257    pub fn asks(&self) -> impl Iterator<Item = &str> {
258        self.asks.iter().map(SmolStr::as_str)
259    }
260
261    /// The annotations on the `flow` declaration.
262    pub fn annotations(&self) -> &[Annotation] {
263        &self.annotations
264    }
265
266    /// Problems that didn't stop the flow compiling.
267    pub fn warnings(&self) -> &[Diagnostic] {
268        &self.warnings
269    }
270
271    /// Every node, in source order.
272    pub fn nodes(&self) -> impl Iterator<Item = NodeInfo<'_>> {
273        self.nodes.iter().map(|node| self.info(node))
274    }
275
276    /// The node called `name`.
277    pub fn node(&self, name: &str) -> Option<NodeInfo<'_>> {
278        self.node_by_name(name)
279            .map(|id| self.info(&self.nodes[id.index()]))
280    }
281
282    fn info<'a>(&'a self, node: &'a Node) -> NodeInfo<'a> {
283        let mut jumps_to = Vec::new();
284        let mut seen = HashSet::new();
285        let mut asks = Vec::new();
286        for branch in &node.branches {
287            match &branch.outcome {
288                Outcome::Jump { node: target, .. } => {
289                    if seen.insert(*target) {
290                        jumps_to.push(self.node_name(*target));
291                    }
292                }
293                Outcome::Ask {
294                    name, node: target, ..
295                } => asks.push(AskInfo {
296                    name: name.as_str(),
297                    node: self.node_name(*target),
298                }),
299                _ => {}
300            }
301        }
302        NodeInfo {
303            name: &node.name,
304            params: node.params.iter().map(SmolStr::as_str).collect(),
305            annotations: &node.annotations,
306            is_entry: node.is_entry,
307            resumes_ask: node.resumes_ask,
308            jumps_to,
309            asks,
310            branch_count: node.branches.len(),
311        }
312    }
313
314    pub(crate) fn node_by_name(&self, name: &str) -> Option<NodeId> {
315        self.node_ids.get(name).copied()
316    }
317
318    pub(crate) fn node_name(&self, id: NodeId) -> &str {
319        &self.nodes[id.index()].name
320    }
321
322    /// The source the flow was compiled from, for reports such as
323    /// [`RunError::report`](crate::RunError::report).
324    pub fn source(&self) -> &str {
325        &self.source
326    }
327}
328
329/// Bytes as lowercase hex.
330pub(crate) fn hex(bytes: &[u8]) -> String {
331    const DIGITS: &[u8; 16] = b"0123456789abcdef";
332    let mut out = String::with_capacity(2 * bytes.len());
333    for &byte in bytes {
334        out.push(char::from(DIGITS[usize::from(byte >> 4)]));
335        out.push(char::from(DIGITS[usize::from(byte & 0xf)]));
336    }
337    out
338}