Skip to main content

flow_runner/compile/
mod.rs

1//! From a parsed file to a runnable [`Flow`]: resolve names, check every
2//! expression and value against the names in scope, and enforce the rules
3//! that keep a run finite and predictable.
4//!
5//! One [`Compiler`] walks the tree; its methods are split by concern:
6//! [`declarations`] reads the top-level declarations, [`nodes`] each node,
7//! [`units`] each temple unit, [`events`] how units test `input.event`, and
8//! [`rules`] the checks that need every node compiled. [`hash`] is the
9//! flow's version.
10
11mod declarations;
12mod events;
13mod hash;
14mod hints;
15pub(crate) mod literal;
16mod nodes;
17mod rules;
18mod scope;
19mod units;
20
21use crate::common::diagnostic::{Diagnostic, Diagnostics};
22use crate::common::error::too_large;
23use crate::common::limits::{MAX_HINTS, MAX_HINT_CELLS, MAX_SOURCE_BYTES};
24use crate::flow::{Flow, Node, NodeId, HASH_LEN};
25use crate::syntax;
26use crate::syntax::ast::{FlowAst, EDITIONS};
27use crate::syntax::lexer::Mode;
28use scope::Scope;
29use smol_str::SmolStr;
30use std::collections::HashMap;
31use std::sync::Arc;
32use temple_dsl::Span;
33
34impl Flow {
35    /// Compile a `.flow` source. On success the flow may still carry
36    /// [`warnings`](Self::warnings).
37    pub fn compile(src: &str) -> Result<Flow, Diagnostics> {
38        if src.len() > MAX_SOURCE_BYTES {
39            return Err(Diagnostics::new(vec![too_large_source(src)]));
40        }
41        let (ast, diagnostics) = syntax::parse(src);
42        parsed(src, &ast, diagnostics)
43    }
44
45    /// Every error and warning in a source, without keeping the result.
46    pub fn check(src: &str) -> Diagnostics {
47        diagnostics(Flow::compile(src))
48    }
49}
50
51/// The error for a source over [`MAX_SOURCE_BYTES`].
52pub(crate) fn too_large_source(src: &str) -> Diagnostic {
53    Diagnostic::error(
54        Span::new(0, 0),
55        too_large("the flow", src.len(), MAX_SOURCE_BYTES),
56    )
57}
58
59/// Compile an already parsed file. `diagnostics` are the parser's.
60pub(crate) fn parsed(
61    src: &str,
62    ast: &FlowAst,
63    mut diagnostics: Vec<Diagnostic>,
64) -> Result<Flow, Diagnostics> {
65    if diagnostics.iter().any(Diagnostic::is_error) {
66        return Err(Diagnostics::new(diagnostics));
67    }
68    let mut compiler = Compiler {
69        src,
70        ast,
71        diagnostics: Vec::new(),
72        hints_left: MAX_HINTS,
73        hint_cells_left: MAX_HINT_CELLS,
74    };
75    let flow = compiler.flow();
76    diagnostics.append(&mut compiler.diagnostics);
77    match flow {
78        Some(mut flow) if !diagnostics.iter().any(Diagnostic::is_error) => {
79            flow.warnings = diagnostics;
80            flow.source = Arc::from(src);
81            Ok(flow)
82        }
83        _ => Err(Diagnostics::new(diagnostics)),
84    }
85}
86
87/// The diagnostics a compile produced, whether it succeeded or not.
88pub(crate) fn diagnostics(result: Result<Flow, Diagnostics>) -> Diagnostics {
89    match result {
90        Ok(flow) => Diagnostics::new(flow.warnings),
91        Err(errors) => errors,
92    }
93}
94
95/// What a name in a flow can be declared as.
96#[derive(Clone, Copy, PartialEq, Eq)]
97enum Kind {
98    Param,
99    Let,
100    Helper,
101    Node,
102    Parameter,
103    NodeLet,
104}
105
106impl Kind {
107    fn noun(self) -> &'static str {
108        match self {
109            Kind::Param => "a param",
110            Kind::Let => "a let",
111            Kind::Helper => "a helper",
112            Kind::Node => "a node",
113            Kind::Parameter => "a parameter",
114            Kind::NodeLet => "a node let",
115        }
116    }
117}
118
119/// Every declared name in one namespace, and what each is.
120type Declarations = HashMap<SmolStr, Kind>;
121
122struct Compiler<'a> {
123    src: &'a str,
124    ast: &'a FlowAst,
125    diagnostics: Vec<Diagnostic>,
126    /// Did-you-mean searches left, and the table cells they may still fill.
127    hints_left: usize,
128    hint_cells_left: u64,
129}
130
131impl Compiler<'_> {
132    fn push(&mut self, diagnostic: Diagnostic) {
133        self.diagnostics.push(diagnostic);
134    }
135
136    fn error(&mut self, span: Span, message: impl Into<String>) {
137        self.push(Diagnostic::error(span, message));
138    }
139
140    /// Whether any diagnostic from index `from` on is an error.
141    fn errors_since(&self, from: usize) -> bool {
142        self.diagnostics[from..].iter().any(Diagnostic::is_error)
143    }
144
145    /// Whether `searches` did-you-mean searches, filling at most `cells()`
146    /// table cells, still fit. The searches are used up even when the cells
147    /// don't fit, so working out what they cost stays bounded too.
148    fn afford_hints(&mut self, searches: usize, cells: impl FnOnce() -> u64) -> bool {
149        if searches > self.hints_left {
150            return false;
151        }
152        self.hints_left -= searches;
153        let cells = cells();
154        if cells > self.hint_cells_left {
155            return false;
156        }
157        self.hint_cells_left -= cells;
158        true
159    }
160
161    /// The closest name to `target`, while hints last.
162    fn hint<'n>(
163        &mut self,
164        target: &str,
165        candidates: impl Iterator<Item = &'n str> + Clone,
166    ) -> Option<&'n str> {
167        if self.afford_hints(1, || hints::closest_cost(target, candidates.clone())) {
168            hints::closest(target, candidates)
169        } else {
170            None
171        }
172    }
173
174    fn flow(&mut self) -> Option<Flow> {
175        let ast = self.ast;
176        let name = match &ast.name {
177            Some(name) => name.name.clone(),
178            None => {
179                self.error(Span::new(0, 0), "missing `flow <name>` declaration");
180                SmolStr::default()
181            }
182        };
183        let edition = ast.edition.unwrap_or(EDITIONS[0]);
184        let globals = self.declare_globals();
185        let params = self.params();
186        let mut scope = Scope::default();
187        let (helpers, functions) = self.helpers(&globals, &mut scope);
188        let lets = self.flow_lets(&mut scope);
189
190        // a source within MAX_SOURCE_BYTES holds far fewer than u32::MAX nodes
191        let node_ids: HashMap<SmolStr, NodeId> = ast
192            .nodes
193            .iter()
194            .enumerate()
195            .map(|(index, node)| (node.name.name.clone(), NodeId(index as u32)))
196            .collect();
197        let mut nodes = Vec::new();
198        for node in &ast.nodes {
199            if let Some(compiled) = self.node(node, &globals, &mut scope, &node_ids) {
200                nodes.push(compiled);
201            }
202        }
203        let entries = self.check_entries(&node_ids);
204        let events = self.check_events();
205        let annotations = self.annotations(&ast.annotations);
206        if nodes.len() != ast.nodes.len() || node_ids.len() != nodes.len() {
207            // the rules below need every node compiled, under a name of its own
208            return None;
209        }
210
211        for &entry in &entries {
212            nodes[entry.index()].is_entry = true;
213        }
214        let shared = lets
215            .iter()
216            .map(|binding| &binding.expression)
217            .chain(helpers.iter().map(|helper| &helper.body));
218        let unit_spans = nodes
219            .iter()
220            .flat_map(Node::unit_spans)
221            .chain(shared.clone().map(|unit| (unit.span(), Mode::Expression)));
222        self.check_event_tests(unit_spans, &events);
223        self.check_asks(&mut nodes, shared);
224        self.check_jump_loops(&nodes);
225        // with an entry missing, what can be reached isn't known
226        let entries_known = ast
227            .entry_names()
228            .all(|entry| node_ids.contains_key(&entry.name));
229        if !entries.is_empty() && entries_known {
230            self.check_reachability(&nodes, &entries);
231        }
232        if self.errors_since(0) {
233            return None;
234        }
235
236        let mut flow = Flow {
237            name,
238            edition,
239            annotations,
240            entries,
241            events,
242            param_positions: params
243                .iter()
244                .enumerate()
245                .map(|(position, param)| (SmolStr::new(&param.name), position))
246                .collect(),
247            params,
248            lets,
249            helpers,
250            functions: functions?,
251            asks: nodes::ask_names(&nodes),
252            nodes,
253            node_ids,
254            hash: [0; HASH_LEN],
255            warnings: Vec::new(),
256            source: Arc::from(""),
257        };
258        flow.hash = hash::of(&flow, self.src);
259        Some(flow)
260    }
261}