Skip to main content

flow_runner/document/
mod.rs

1//! Editing a flow as text. A [`Document`] gives a visual builder a [`Graph`]
2//! to draw and applies checked [`Edit`]s that rewrite only the text they
3//! touch, so comments and layout elsewhere survive a trip through the builder.
4
5mod edits;
6mod graph;
7mod outline;
8mod text;
9
10pub use edits::{Declaration, Edit};
11pub use graph::{
12    AnnotationView, BranchView, Edge, EdgeKind, Graph, LetView, NodeView, OutcomeView, ParamView,
13};
14
15use self::outline::Outline;
16use crate::common::diagnostic::{Diagnostic, Diagnostics};
17use crate::common::error::{too_large, EditError};
18use crate::common::limits::MAX_SOURCE_BYTES;
19use crate::compile;
20use crate::syntax;
21use crate::syntax::ast::FlowAst;
22use std::collections::HashMap;
23
24/// A `.flow` file open for editing. The text is the source of truth; the
25/// graph is a view of it.
26///
27/// ```
28/// use flow_runner::{Document, Edit};
29///
30/// let mut doc = Document::parse("edition 2026\nflow f\nentry a\n\nnode a = { \"ok\": true }\n");
31/// doc.apply(Edit::RenameNode { from: "a".into(), to: "start".into() }).unwrap();
32/// assert_eq!(doc.text(), "edition 2026\nflow f\nentry start\n\nnode start = { \"ok\": true }\n");
33/// assert!(doc.diagnostics().is_empty());
34/// ```
35#[derive(Debug, Clone)]
36pub struct Document {
37    text: String,
38    ast: FlowAst,
39    /// The syntax errors in the text as it stands. An edit may not add one.
40    syntax_errors: Vec<String>,
41    diagnostics: Diagnostics,
42}
43
44impl Document {
45    /// Open a file. Never fails: problems are in
46    /// [`diagnostics`](Self::diagnostics), and the graph shows every
47    /// declaration that parsed. A file over [`MAX_SOURCE_BYTES`] isn't read
48    /// at all.
49    pub fn parse(text: impl Into<String>) -> Document {
50        let text = text.into();
51        if text.len() > MAX_SOURCE_BYTES {
52            let error = compile::too_large_source(&text);
53            return Document {
54                text,
55                ast: FlowAst::default(),
56                syntax_errors: vec![error.message.clone()],
57                diagnostics: Diagnostics::new(vec![error]),
58            };
59        }
60        let (ast, parse_diagnostics) = syntax::parse(&text);
61        Document::parsed(text, ast, parse_diagnostics)
62    }
63
64    fn parsed(text: String, ast: FlowAst, parse_diagnostics: Vec<Diagnostic>) -> Document {
65        let syntax_errors = parse_diagnostics
66            .iter()
67            .filter(|diagnostic| diagnostic.is_error())
68            .map(|diagnostic| diagnostic.message.clone())
69            .collect();
70        let diagnostics = compile::diagnostics(compile::parsed(&text, &ast, parse_diagnostics));
71        Document {
72            text,
73            ast,
74            syntax_errors,
75            diagnostics,
76        }
77    }
78
79    /// The file as it stands, to save.
80    pub fn text(&self) -> &str {
81        &self.text
82    }
83
84    /// Every error and warning, as [`Flow::check`](crate::Flow::check)
85    /// reports them.
86    pub fn diagnostics(&self) -> &Diagnostics {
87        &self.diagnostics
88    }
89
90    /// Apply one edit. On error the document is unchanged. An edit that
91    /// parses but leaves the flow wrong, such as removing a node others jump
92    /// to, is applied, and the problem shows in the diagnostics. An edit that
93    /// would change more of the file than it asks for is refused.
94    pub fn apply(&mut self, edit: Edit) -> Result<(), EditError> {
95        let mut changes = self.plan(&edit)?;
96        let line_break = self.line_break();
97        if line_break != "\n" {
98            // text copied from the file already has `\r\n`
99            for change in &mut changes {
100                change.text = change.text.replace("\r\n", "\n").replace('\n', line_break);
101            }
102        }
103        let text = text::splice(&self.text, changes);
104        if text.len() > MAX_SOURCE_BYTES {
105            return Err(EditError::Invalid(too_large(
106                "the flow it would make",
107                text.len(),
108                MAX_SOURCE_BYTES,
109            )));
110        }
111        let (ast, parse_diagnostics) = syntax::parse(&text);
112        if let Some(message) = self.new_syntax_error(&parse_diagnostics) {
113            return Err(EditError::Invalid(format!(
114                "the edit doesn't parse where it goes: {message}"
115            )));
116        }
117        if Outline::of(&self.ast).after(&edit, &ast) != Some(Outline::of(&ast)) {
118            return Err(EditError::Invalid(
119                "the edit would change more of the file than it asks for".into(),
120            ));
121        }
122        *self = Document::parsed(text, ast, parse_diagnostics);
123        Ok(())
124    }
125
126    /// A syntax error in `after` that the text as it stands doesn't have.
127    fn new_syntax_error<'d>(&self, after: &'d [Diagnostic]) -> Option<&'d str> {
128        let mut before: HashMap<&str, usize> = HashMap::new();
129        for message in &self.syntax_errors {
130            *before.entry(message).or_default() += 1;
131        }
132        after
133            .iter()
134            .filter(|diagnostic| diagnostic.is_error())
135            .map(|diagnostic| diagnostic.message.as_str())
136            .find(|message| match before.get_mut(message) {
137                Some(count) if *count > 0 => {
138                    *count -= 1;
139                    false
140                }
141                _ => true,
142            })
143    }
144}