Skip to main content

flow_runner/document/
edits.rs

1//! The edits a builder can make, and how each becomes text changes.
2
3use super::text::{literal_text, Change};
4use super::Document;
5use crate::common::diagnostic::Diagnostics;
6use crate::common::error::{already_declared, twice, EditError, ELSE_LAST};
7use crate::syntax;
8use crate::syntax::ast::{
9    Annotation, Body, Branch, Guard, Identifier, NameList, NodeDeclaration, Outcome,
10    ParamDeclaration,
11};
12use crate::syntax::names::{annotation_problem, event_problem, name_problem};
13use std::collections::HashSet;
14use std::ops::Range;
15use temple_dsl::{Span, Value};
16
17/// How far a branch is indented in a `when` block an edit writes.
18const BRANCH_INDENT: &str = "  ";
19
20/// A change a builder can make. Text fields hold flow syntax exactly as it
21/// would be typed: a guard is a temple expression, an outcome is a jump, a
22/// value, an ask or `ignore`, and a body is everything after `node name =`.
23/// A guard or outcome can't hold a `#` comment, which would hide the rest of
24/// the line it lands on.
25#[derive(Debug, Clone, PartialEq)]
26#[non_exhaustive]
27pub enum Edit {
28    /// Add `node name(params) = body` after node `after`, or at the end.
29    AddNode {
30        /// The new node's name.
31        name: String,
32        /// Its parameter names.
33        params: Vec<String>,
34        /// Everything after `=`.
35        body: String,
36        /// The node to add it after; `None` for the end of the file.
37        after: Option<String>,
38    },
39    /// Remove a node and its annotations. Jumps to it become errors to fix.
40    RemoveNode {
41        /// The node.
42        name: String,
43    },
44    /// Rename a node and every jump, ask continuation and entry naming it.
45    RenameNode {
46        /// The node.
47        from: String,
48        /// Its new name.
49        to: String,
50    },
51    /// Add `guard: outcome` before branch `before`, or before `else` when
52    /// `None`. A node with a single outcome gains a `when` block, with its
53    /// old outcome as `else`.
54    AddBranch {
55        /// The node.
56        node: String,
57        /// The new branch's guard.
58        guard: String,
59        /// The new branch's outcome.
60        outcome: String,
61        /// The branch to add it before.
62        before: Option<usize>,
63    },
64    /// Remove branch `index` of a node's `when`.
65    RemoveBranch {
66        /// The node.
67        node: String,
68        /// The branch, counting from 0.
69        index: usize,
70    },
71    /// Move a branch; `else` has to stay last.
72    MoveBranch {
73        /// The node.
74        node: String,
75        /// Where the branch is, counting from 0.
76        from: usize,
77        /// Where it goes.
78        to: usize,
79    },
80    /// Replace a branch's guard. `"else"` makes the last branch the `else`.
81    SetGuard {
82        /// The node.
83        node: String,
84        /// The branch, counting from 0.
85        index: usize,
86        /// The new guard.
87        guard: String,
88    },
89    /// Replace a branch's outcome. A single-outcome node's outcome is index 0.
90    SetOutcome {
91        /// The node.
92        node: String,
93        /// The branch, counting from 0.
94        index: usize,
95        /// The new outcome.
96        outcome: String,
97    },
98    /// Set `@name = value` on the flow, a param or a node.
99    SetAnnotation {
100        /// The declaration it sits on.
101        on: Declaration,
102        /// The name after `@`.
103        name: String,
104        /// Its value.
105        value: Value,
106    },
107    /// Remove `@name` from the flow, a param or a node.
108    RemoveAnnotation {
109        /// The declaration it sits on.
110        on: Declaration,
111        /// The name after `@`.
112        name: String,
113    },
114    /// Add `param name = default` after the other params.
115    AddParam {
116        /// The param's name.
117        name: String,
118        /// Its default.
119        default: Value,
120    },
121    /// Remove a param and its annotations.
122    RemoveParam {
123        /// The param.
124        name: String,
125    },
126    /// Declare an event.
127    AddEvent {
128        /// The event.
129        name: String,
130    },
131    /// Remove an event from `events`.
132    RemoveEvent {
133        /// The event.
134        name: String,
135    },
136    /// List a node under `entry`.
137    AddEntry {
138        /// The node.
139        node: String,
140    },
141    /// Remove a node from `entry`.
142    RemoveEntry {
143        /// The node.
144        node: String,
145    },
146}
147
148/// The declaration an annotation sits on.
149#[derive(Debug, Clone, PartialEq, Eq)]
150#[non_exhaustive]
151pub enum Declaration {
152    /// The `flow` declaration.
153    Flow,
154    /// The param with this name.
155    Param(String),
156    /// The node with this name.
157    Node(String),
158}
159
160impl Document {
161    /// The text changes `edit` makes.
162    pub(super) fn plan(&self, edit: &Edit) -> Result<Vec<Change>, EditError> {
163        match edit {
164            Edit::AddNode {
165                name,
166                params,
167                body,
168                after,
169            } => self.add_node(name, params, body, after.as_deref()),
170            Edit::RemoveNode { name } => {
171                let node = self.node(name)?;
172                Ok(vec![self.remove_declaration(&node.annotations, node.span)])
173            }
174            Edit::RenameNode { from, to } => self.rename_node(from, to),
175            Edit::AddBranch {
176                node,
177                guard,
178                outcome,
179                before,
180            } => self.add_branch(node, guard, outcome, *before),
181            Edit::RemoveBranch { node, index } => self.remove_branch(node, *index),
182            Edit::MoveBranch { node, from, to } => self.move_branch(node, *from, *to),
183            Edit::SetGuard { node, index, guard } => self.set_guard(node, *index, guard),
184            Edit::SetOutcome {
185                node,
186                index,
187                outcome,
188            } => self.set_outcome(node, *index, outcome),
189            Edit::SetAnnotation { on, name, value } => self.set_annotation(on, name, value),
190            Edit::RemoveAnnotation { on, name } => {
191                let (annotations, _) = self.declaration(on)?;
192                let annotation = annotations
193                    .iter()
194                    .find(|annotation| annotation.name.name == name.as_str())
195                    .ok_or_else(|| EditError::NotFound(format!("annotation `@{name}`")))?;
196                Ok(vec![self.remove_span(annotation.span)])
197            }
198            Edit::AddParam { name, default } => self.add_param(name, default),
199            Edit::RemoveParam { name } => {
200                let param = self.param(name)?;
201                Ok(vec![self.remove_declaration(&param.annotations, param.span)])
202            }
203            Edit::AddEvent { name } => self.add_event(name),
204            Edit::RemoveEvent { name } => self.remove_listed(&self.ast.events, name, "event"),
205            Edit::AddEntry { node } => self.add_entry(node),
206            Edit::RemoveEntry { node } => self.remove_listed(&self.ast.entries, node, "entry"),
207        }
208    }
209
210    fn node(&self, name: &str) -> Result<&NodeDeclaration, EditError> {
211        self.ast
212            .nodes
213            .iter()
214            .find(|node| node.name.name == name)
215            .ok_or_else(|| EditError::NotFound(format!("node `{name}`")))
216    }
217
218    fn param(&self, name: &str) -> Result<&ParamDeclaration, EditError> {
219        self.ast
220            .params
221            .iter()
222            .find(|param| param.name.name == name)
223            .ok_or_else(|| EditError::NotFound(format!("param `{name}`")))
224    }
225
226    /// What a top-level name is declared as, if it is: a param, a let, a
227    /// helper or a node.
228    fn declared_as(&self, name: &str) -> Option<&'static str> {
229        let ast = &self.ast;
230        if ast.params.iter().any(|param| param.name.name == name) {
231            return Some("a param");
232        }
233        if let Some(binding) = ast.lets.iter().find(|binding| binding.name.name == name) {
234            return Some(if binding.params.is_some() {
235                "a helper"
236            } else {
237                "a let"
238            });
239        }
240        ast.nodes
241            .iter()
242            .any(|node| node.name.name == name)
243            .then_some("a node")
244    }
245
246    fn check_new_name(&self, name: &str) -> Result<(), EditError> {
247        if let Some(problem) = name_problem(name) {
248            return Err(EditError::BadName(problem));
249        }
250        match self.declared_as(name) {
251            Some(what) => Err(EditError::BadName(already_declared(name, what))),
252            None => Ok(()),
253        }
254    }
255
256    fn add_node(
257        &self,
258        name: &str,
259        params: &[String],
260        body: &str,
261        after: Option<&str>,
262    ) -> Result<Vec<Change>, EditError> {
263        self.check_new_name(name)?;
264        let mut seen = HashSet::new();
265        for param in params {
266            if let Some(problem) = name_problem(param) {
267                return Err(EditError::BadName(problem));
268            }
269            if !seen.insert(param) {
270                return Err(EditError::BadName(twice("parameter", param)));
271            }
272        }
273        let head = if params.is_empty() {
274            format!("node {name} = ")
275        } else {
276            format!("node {name}({}) = ", params.join(", "))
277        };
278        let declaration = format!("{head}{}", body.trim());
279        syntax::parse_node(&declaration)
280            .map_err(|errors| syntax_error(errors, head.len(), body))?;
281        let at = match after {
282            Some(after) => self.next_free_line(self.node(after)?.span.end as usize),
283            None => self.text.len(),
284        };
285        let lead = if at == 0 || self.text[..at].ends_with('\n') {
286            "\n"
287        } else {
288            "\n\n"
289        };
290        let rest = &self.text[at..];
291        let trail = if rest.is_empty() || rest.starts_with('\n') || rest.starts_with("\r\n") {
292            ""
293        } else {
294            "\n"
295        };
296        Ok(vec![Change::insert(
297            at,
298            format!("{lead}{declaration}\n{trail}"),
299        )])
300    }
301
302    fn rename_node(&self, from: &str, to: &str) -> Result<Vec<Change>, EditError> {
303        if !self.syntax_errors.is_empty() {
304            return Err(EditError::Invalid(
305                "fix the syntax errors first: a rename can't see references inside declarations that don't parse".into(),
306            ));
307        }
308        let node = self.node(from)?;
309        if from == to {
310            return Ok(Vec::new());
311        }
312        self.check_new_name(to)?;
313        let mut changes = vec![Change::replace(node.name.span, to)];
314        let mut retarget = |target: &Identifier| {
315            if target.name == from {
316                changes.push(Change::replace(target.span, to));
317            }
318        };
319        for outcome in self.ast.outcomes() {
320            if let Outcome::Jump { target, .. } | Outcome::Ask { target, .. } = outcome {
321                retarget(target);
322            }
323        }
324        for entry in self.ast.entry_names() {
325            retarget(entry);
326        }
327        Ok(changes)
328    }
329
330    fn add_branch(
331        &self,
332        node: &str,
333        guard: &str,
334        outcome: &str,
335        before: Option<usize>,
336    ) -> Result<Vec<Change>, EditError> {
337        check_guard(guard)?;
338        check_outcome(outcome)?;
339        let guard = guard.trim();
340        let branch = format!("{guard}: {}", outcome.trim());
341        let declaration = self.node(node)?;
342        let (branches, block) = match &declaration.body {
343            Body::When { branches, span } => (branches, *span),
344            Body::Single(old) => {
345                if before.is_some_and(|before| before > 0) {
346                    return Err(EditError::Invalid(
347                        "this node has one outcome; a new branch goes before it".into(),
348                    ));
349                }
350                if guard == "else" {
351                    return Err(EditError::Invalid(ELSE_LAST.into()));
352                }
353                return Ok(vec![self.when_block(declaration, old, &branch)]);
354            }
355        };
356        let else_at = branches
357            .iter()
358            .position(|branch| matches!(branch.guard, Guard::Else(_)));
359        let at = before.or(else_at).unwrap_or(branches.len());
360        if at > branches.len() {
361            return Err(missing_branch(node, at));
362        }
363        let after_else = else_at.is_some_and(|else_at| at > else_at);
364        if after_else || (guard == "else" && at < branches.len()) {
365            return Err(EditError::Invalid(ELSE_LAST.into()));
366        }
367        Ok(vec![self.insert_branch(branches, block, at, &branch)])
368    }
369
370    /// A single outcome made into a `when` block: `branch`, then the old
371    /// outcome as `else`.
372    fn when_block(&self, declaration: &NodeDeclaration, old: &Outcome, branch: &str) -> Change {
373        let span = old.span();
374        let start = span.start as usize;
375        let base = if self.starts_line(start) {
376            self.indent_at(start)
377        } else {
378            self.indent_at(declaration.span.start as usize)
379        };
380        let inner = format!("{base}{BRANCH_INDENT}");
381        let text = format!(
382            "when {{\n{inner}{branch}\n{inner}else: {}\n{base}}}",
383            self.slice(span)
384        );
385        Change::replace(span, text)
386    }
387
388    /// `branch` put in at position `at` of a `when` block.
389    fn insert_branch(&self, branches: &[Branch], block: Span, at: usize, branch: &str) -> Change {
390        if let Some(next) = branches.get(at) {
391            let start = next.span.start as usize;
392            if self.starts_line(start) {
393                let indent = self.indent_at(start);
394                return Change::insert(self.line_start(start), format!("{indent}{branch}\n"));
395            }
396            return Change::insert(start, format!("{branch}, "));
397        }
398        match branches.last() {
399            Some(last)
400                if self.starts_line(last.span.start as usize)
401                    && self.ends_line(last.span.end as usize) =>
402            {
403                let indent = self.indent_at(last.span.start as usize);
404                Change::insert(
405                    self.line_after(last.span.end as usize),
406                    format!("{indent}{branch}\n"),
407                )
408            }
409            Some(last) => Change::insert(last.span.end as usize, format!(", {branch}")),
410            None => {
411                let close = block.end as usize - 1;
412                Change::insert(close, format!("\n{BRANCH_INDENT}{branch}\n"))
413            }
414        }
415    }
416
417    /// The branches of node `name`'s `when`, for an edit that would `action`
418    /// one.
419    fn when_branches(&self, name: &str, action: &str) -> Result<&[Branch], EditError> {
420        match &self.node(name)?.body {
421            Body::When { branches, .. } => Ok(branches),
422            Body::Single(_) => Err(EditError::Invalid(format!(
423                "node `{name}` has a single outcome, so it has no branches to {action}"
424            ))),
425        }
426    }
427
428    fn remove_branch(&self, node: &str, index: usize) -> Result<Vec<Change>, EditError> {
429        let branches = self.when_branches(node, "remove")?;
430        let branch = branches
431            .get(index)
432            .ok_or_else(|| missing_branch(node, index))?;
433        Ok(vec![self.remove_span(branch.span)])
434    }
435
436    fn move_branch(&self, node: &str, from: usize, to: usize) -> Result<Vec<Change>, EditError> {
437        let branches = self.when_branches(node, "move")?;
438        if from >= branches.len() || to >= branches.len() {
439            return Err(missing_branch(node, from.max(to)));
440        }
441        let mut order: Vec<usize> = (0..branches.len()).collect();
442        let moved = order.remove(from);
443        order.insert(to, moved);
444        let else_at = order
445            .iter()
446            .position(|&index| matches!(branches[index].guard, Guard::Else(_)));
447        if else_at.is_some_and(|else_at| else_at + 1 != order.len()) {
448            return Err(EditError::Invalid(ELSE_LAST.into()));
449        }
450        // with one branch to a line, each takes its line's comment along, so
451        // comments stay with the branch they describe
452        let whole_lines = branches
453            .iter()
454            .all(|branch| self.ends_line(branch.span.end as usize));
455        let extent = |branch: &Branch| {
456            if whole_lines {
457                let end = self.line_end(branch.span.end as usize);
458                Span::new(branch.span.start as usize, end)
459            } else {
460                branch.span
461            }
462        };
463        Ok(order
464            .iter()
465            .enumerate()
466            .filter(|(position, index)| position != *index)
467            .map(|(position, &index)| {
468                Change::replace(
469                    extent(&branches[position]),
470                    self.slice(extent(&branches[index])),
471                )
472            })
473            .collect())
474    }
475
476    fn set_guard(&self, node: &str, index: usize, guard: &str) -> Result<Vec<Change>, EditError> {
477        check_guard(guard)?;
478        let guard = guard.trim();
479        let branches = self.when_branches(node, "change")?;
480        let branch = branches
481            .get(index)
482            .ok_or_else(|| missing_branch(node, index))?;
483        if guard == "else" && index + 1 != branches.len() {
484            return Err(EditError::Invalid(ELSE_LAST.into()));
485        }
486        let span = match &branch.guard {
487            Guard::Else(span) => *span,
488            Guard::Expression(expression) => expression.span(),
489        };
490        Ok(vec![Change::replace(span, guard)])
491    }
492
493    fn set_outcome(
494        &self,
495        node: &str,
496        index: usize,
497        outcome: &str,
498    ) -> Result<Vec<Change>, EditError> {
499        check_outcome(outcome)?;
500        let declaration = self.node(node)?;
501        let span = match &declaration.body {
502            Body::Single(old) if index == 0 => old.span(),
503            Body::When { branches, .. } if index < branches.len() => branches[index].outcome.span(),
504            _ => return Err(missing_branch(node, index)),
505        };
506        Ok(vec![Change::replace(span, outcome.trim())])
507    }
508
509    /// The annotations and span of a flow, param or node declaration.
510    fn declaration(&self, on: &Declaration) -> Result<(&[Annotation], Span), EditError> {
511        match on {
512            Declaration::Flow => self
513                .ast
514                .flow_span
515                .map(|span| (self.ast.annotations.as_slice(), span))
516                .ok_or_else(|| EditError::NotFound("`flow` declaration".into())),
517            Declaration::Param(name) => self
518                .param(name)
519                .map(|param| (param.annotations.as_slice(), param.span)),
520            Declaration::Node(name) => self
521                .node(name)
522                .map(|node| (node.annotations.as_slice(), node.span)),
523        }
524    }
525
526    fn set_annotation(
527        &self,
528        on: &Declaration,
529        name: &str,
530        value: &Value,
531    ) -> Result<Vec<Change>, EditError> {
532        if let Some(problem) = annotation_problem(name) {
533            return Err(EditError::BadName(problem));
534        }
535        let text = format!("@{name} = {}", literal_text(value)?);
536        let (annotations, span) = self.declaration(on)?;
537        if let Some(existing) = annotations
538            .iter()
539            .find(|annotation| annotation.name.name == name)
540        {
541            return Ok(vec![Change::replace(existing.span, text)]);
542        }
543        let start = span.start as usize;
544        if !self.starts_line(start) {
545            // another declaration comes first on this line: annotate in place
546            return Ok(vec![Change::insert(start, format!("{text} "))]);
547        }
548        Ok(vec![Change::insert(
549            self.line_start(start),
550            format!("{}{text}\n", self.indent_at(start)),
551        )])
552    }
553
554    fn add_param(&self, name: &str, default: &Value) -> Result<Vec<Change>, EditError> {
555        self.check_new_name(name)?;
556        let line = format!("param {name} = {}", literal_text(default)?);
557        if let Some(last) = self.ast.params.last() {
558            return Ok(vec![self.insert_lines(
559                self.next_free_line(last.span.end as usize),
560                format!("{line}\n"),
561            )]);
562        }
563        let at = self.after_header(&self.ast.events);
564        Ok(vec![self.insert_lines(at, format!("\n{line}\n"))])
565    }
566
567    fn add_event(&self, name: &str) -> Result<Vec<Change>, EditError> {
568        if let Some(problem) = event_problem(name) {
569            return Err(EditError::BadName(problem));
570        }
571        if self.ast.event_names().any(|event| event.name == name) {
572            return Err(EditError::BadName(already_declared(name, "an event")));
573        }
574        Ok(self.add_listed(&self.ast.events, name, "events"))
575    }
576
577    fn add_entry(&self, node: &str) -> Result<Vec<Change>, EditError> {
578        self.node(node)?;
579        if self.ast.entry_names().any(|entry| entry.name == node) {
580            return Err(EditError::Invalid(already_declared(node, "an entry")));
581        }
582        Ok(self.add_listed(&self.ast.entries, node, "entry"))
583    }
584
585    /// Add a name to the last `entry` or `events` declaration, or start one
586    /// after the entries and the flow declaration.
587    fn add_listed(&self, lists: &[NameList], name: &str, keyword: &str) -> Vec<Change> {
588        if let Some(last) = lists.last().and_then(|list| list.names.last()) {
589            return vec![Change::insert(last.span.end as usize, format!(", {name}"))];
590        }
591        vec![self.insert_lines(self.after_header(lists), format!("{keyword} {name}\n"))]
592    }
593
594    /// Where lines go after `lists`, the entries and the flow declaration:
595    /// past the last of them, or at the end of a file without any.
596    fn after_header(&self, lists: &[NameList]) -> usize {
597        let ast = &self.ast;
598        lists
599            .iter()
600            .chain(&ast.entries)
601            .map(|list| list.span.end)
602            .chain(ast.flow_span.map(|span| span.end))
603            .max()
604            .map_or(self.text.len(), |end| self.next_free_line(end as usize))
605    }
606
607    /// Remove one name from `entry` or `events`, and the declaration with it
608    /// when it was the only name.
609    fn remove_listed(
610        &self,
611        lists: &[NameList],
612        name: &str,
613        what: &str,
614    ) -> Result<Vec<Change>, EditError> {
615        let (list, position) = lists
616            .iter()
617            .find_map(|list| {
618                let position = list.names.iter().position(|listed| listed.name == name)?;
619                Some((list, position))
620            })
621            .ok_or_else(|| EditError::NotFound(format!("{what} `{name}`")))?;
622        if list.names.len() == 1 {
623            return Ok(vec![self.remove_span(list.span)]);
624        }
625        let Range { start, end } = list.names[position].span.range();
626        let next = list
627            .names
628            .get(position + 1)
629            .map(|next| next.span.start as usize);
630        let own_line =
631            self.starts_line(start) && next.map_or(true, |next| !self.same_line(end, next));
632        if !own_line {
633            // the next name takes its place, or, for the last, the text from
634            // the name before it goes, comma and all
635            return Ok(vec![match next {
636                Some(next) => Change::remove(start, next),
637                None => Change::remove(list.names[position - 1].span.end as usize, end),
638            }]);
639        }
640        // on a line of its own, with its comment: the line goes, and the last
641        // name also takes the comma before it
642        let mut changes = vec![Change::remove(self.line_start(start), self.line_after(end))];
643        if next.is_none() {
644            let previous = list.names[position - 1].span.end as usize;
645            if let Some(comma) = self.text[previous..].find(',') {
646                changes.push(Change::remove(previous + comma, previous + comma + 1));
647            }
648        }
649        Ok(changes)
650    }
651}
652
653/// Check that a guard parses on its own.
654fn check_guard(guard: &str) -> Result<(), EditError> {
655    let trimmed = guard.trim();
656    if trimmed == "else" {
657        return Ok(());
658    }
659    syntax::parse_guard(trimmed).map_err(|errors| syntax_error(errors, 0, guard))
660}
661
662/// Check that an outcome parses on its own.
663fn check_outcome(outcome: &str) -> Result<(), EditError> {
664    syntax::parse_outcome(outcome.trim()).map_err(|errors| syntax_error(errors, 0, outcome))
665}
666
667fn missing_branch(node: &str, index: usize) -> EditError {
668    EditError::NotFound(format!("branch {index} of node `{node}`"))
669}
670
671/// Why `given`, an edit's text, doesn't parse. `errors` point into the text
672/// parsed, which holds `given` trimmed from byte `at` on; they are moved to
673/// point into `given`. A span before `at`, in text the edit wrote around
674/// it, points at its start.
675fn syntax_error(errors: Diagnostics, at: usize, given: &str) -> EditError {
676    let given_at = given.len() - given.trim_start().len();
677    let place = |offset: u32| {
678        (offset as usize)
679            .saturating_sub(at)
680            .saturating_add(given_at)
681            .min(given.len())
682    };
683    EditError::Syntax(Diagnostics::new(
684        errors
685            .into_iter()
686            .map(|mut diagnostic| {
687                diagnostic.span =
688                    Span::new(place(diagnostic.span.start), place(diagnostic.span.end));
689                diagnostic
690            })
691            .collect(),
692    ))
693}