Skip to main content

scrusted_yaml/
source.rs

1//! One file as written: its tree after `$extends`, and what its top `$` keys say (SPEC 4.2, 4.5,
2//! 4.7). Nothing is computed.
3
4use indexmap::IndexMap;
5use regex::Regex;
6use scrusted_feel::Value;
7use std::sync::Arc;
8
9use crate::files::Files;
10use crate::node::{EntryId, KeyKind, NodeId, Tree, js_string};
11use crate::patch::Patch;
12use crate::problem::{Place, Problems};
13use crate::schema::Schema;
14use crate::{merged, reader};
15
16/// `$` keys that are words of the language at the top of a file, not data.
17pub const ROOT_KEYWORDS: &[&str] = &["$vars", "$functions", "$import", "$schema", "$dsl", "$extends", "$tests"];
18
19/// What the application hands over: text, or data already parsed (front matter).
20#[derive(Debug, Clone)]
21pub enum Input {
22    /// YAML text.
23    Text(String),
24    /// Parsed data; problems have no lines.
25    Data(Value),
26}
27
28/// One variable a file declares under `$vars` (SPEC 4.5).
29#[derive(Debug, Clone, PartialEq)]
30pub struct Variable {
31    /// Its name.
32    pub name: String,
33    /// `optional: true`
34    pub optional: bool,
35    /// `secret: true`: kept out of debug output, problems and traces.
36    pub secret: bool,
37    /// `host: true`: the application sets it itself.
38    pub host: bool,
39    /// `type`, as written.
40    pub ty: Option<String>,
41    /// `about`
42    pub about: Option<String>,
43    /// `default`
44    pub default: Option<Value>,
45}
46
47impl Variable {
48    /// The application must pass it: no default and not optional.
49    pub fn required(&self) -> bool {
50        !self.optional && self.default.is_none()
51    }
52
53    /// Why a value does not fit the declared type.
54    pub fn mismatch(&self, value: &Value) -> Option<String> {
55        if value.is_null() {
56            return None;
57        }
58        let fits = match self.ty.as_deref()? {
59            "text" => matches!(value, Value::String(_)),
60            "number" => matches!(value, Value::Number(_)),
61            "boolean" => matches!(value, Value::Bool(_)),
62            "list" => matches!(value, Value::List(_)),
63            _ => return None,
64        };
65        if fits {
66            None
67        } else {
68            Some(format!("variable \"{}\" must be a {}; variables are not converted", self.name, self.ty.as_deref().unwrap_or("")))
69        }
70    }
71}
72
73/// The inputs of a file: what `$vars` declares, and the names a DSL makes known.
74#[derive(Debug, Clone, Default)]
75pub struct Variables {
76    /// Declared variables, in order.
77    pub declared: IndexMap<String, Variable>,
78    patterns: Vec<Regex>,
79    known: Vec<String>,
80}
81
82/// The values of the variables for one resolve, and what is wrong with them.
83pub struct VarValues {
84    /// By name: defaults filled in, empty text turned into null.
85    pub values: scrusted_feel::Map,
86    /// Required variables that are null.
87    pub missing: Vec<String>,
88    /// Values that do not fit their type.
89    pub mismatches: Vec<String>,
90}
91
92impl Variables {
93    /// Reads a `$vars` map. With `for_checking`, the names only become known.
94    pub fn add(&mut self, tree: &Tree, node: Option<NodeId>, problems: &mut Problems, for_checking: bool) {
95        let Some(node) = node else { return };
96        if !tree.is_map(node) {
97            problems.error(&tree.place(node), "$vars must be a map of variable names");
98            return;
99        }
100        for e in tree.entries_of(node) {
101            let entry = tree.entry(*e);
102            let name = entry.key.raw.to_string();
103            if name.len() > 2 && name.starts_with('/') && name.ends_with('/') {
104                match Regex::new(&format!("^(?:{})$", &name[1..name.len() - 1])) {
105                    Ok(re) => self.patterns.push(re),
106                    Err(error) => problems.error(&tree.entry_place(*e), format!("not a regular expression: {error}")),
107                }
108            } else if for_checking {
109                self.known.push(name);
110            } else {
111                let settings = tree.to_data(entry.value);
112                if !settings.is_null() && !tree.is_map(entry.value) {
113                    problems.error(
114                        &tree.place(entry.value),
115                        format!("variable \"{name}\" is declared with a map: {{ default: …, optional: true }}"),
116                    );
117                    continue;
118                }
119                let get = |k: &str| settings.as_map().and_then(|m| m.get(k)).cloned();
120                let text = |k: &str| get(k).and_then(|v| v.as_str().map(str::to_string));
121                let variable = Variable {
122                    name: name.clone(),
123                    optional: get("optional") == Some(Value::Bool(true)),
124                    secret: get("secret") == Some(Value::Bool(true)),
125                    host: get("host") == Some(Value::Bool(true)),
126                    ty: text("type"),
127                    about: text("about"),
128                    default: settings.as_map().and_then(|m| m.get("default")).filter(|v| !v.is_null()).cloned(),
129                };
130                self.declared.insert(name, variable);
131            }
132        }
133    }
134
135    /// True when `vars.NAME` is no typo: declared, matched by a pattern, or known from a DSL.
136    pub fn knows(&self, name: &str) -> bool {
137        self.declared.contains_key(name) || self.known.iter().any(|k| k == name) || self.patterns.iter().any(|p| p.is_match(name))
138    }
139
140    /// The values formulas see for these inputs.
141    pub fn values(&self, input: &scrusted_feel::Map) -> VarValues {
142        let mut values = scrusted_feel::Map::new();
143        for (k, v) in input {
144            let v = if v.as_str() == Some("") { Value::Null } else { v.clone() };
145            values.insert(k.clone(), v);
146        }
147        let mut missing = Vec::new();
148        let mut mismatches = Vec::new();
149        for var in self.declared.values() {
150            let current = values.get(var.name.as_str()).cloned().unwrap_or(Value::Null);
151            let current = if current.is_null() { var.default.clone().unwrap_or(Value::Null) } else { current };
152            if current.is_null() && var.required() {
153                missing.push(var.name.clone());
154            }
155            if let Some(m) = var.mismatch(&current) {
156                mismatches.push(m);
157            }
158            values.insert(var.name.as_str().into(), current);
159        }
160        VarValues { values, missing, mismatches }
161    }
162
163    /// The names of the secret variables.
164    pub fn secrets(&self) -> Vec<String> {
165        self.declared.values().filter(|v| v.secret).map(|v| v.name.clone()).collect()
166    }
167}
168
169/// A function a file declares under `$functions` without `!`: the application passes it.
170#[derive(Debug, Clone, PartialEq)]
171pub struct HostFunctionDecl {
172    /// Its name.
173    pub name: String,
174    /// As written in the key; None when the key has no brackets.
175    pub parameters: Option<Vec<String>>,
176    /// `about`
177    pub about: Option<String>,
178    /// The entry that declares it.
179    pub entry: EntryId,
180}
181
182/// The key of a function: `from_gear(wanted)` is the name `from_gear` and the parameter `wanted`.
183pub struct Signature {
184    /// The name.
185    pub name: String,
186    /// None when the key has no brackets.
187    pub parameters: Option<Vec<String>>,
188}
189
190impl Signature {
191    /// Splits a key at `(`, `,` and `)`.
192    pub fn new(key: &str) -> Signature {
193        match key.find('(') {
194            Some(open) if open > 0 && key.ends_with(')') => Signature {
195                name: key[..open].trim().to_string(),
196                parameters: Some(key[open + 1..key.len() - 1].split(',').map(|p| p.trim().to_string()).filter(|p| !p.is_empty()).collect()),
197            },
198            _ => Signature { name: key.to_string(), parameters: None },
199        }
200    }
201
202    /// The FEEL function definition for a body written without one.
203    pub fn define(&self, body: &str) -> String {
204        format!("function({}) {body}", self.parameters.as_deref().unwrap_or(&[]).join(", "))
205    }
206}
207
208/// One line of `$import`.
209#[derive(Debug, Clone)]
210pub struct ImportSpec {
211    /// The path as written.
212    pub path: String,
213    /// The file's name, as `Files` gave it.
214    pub file: String,
215    /// The file's text.
216    pub text: String,
217    /// The name it is imported under.
218    pub name: String,
219    /// The entry of `$import`.
220    pub entry: EntryId,
221    /// The file was found.
222    pub found: bool,
223}
224
225/// A file as written, after `$extends`.
226pub struct Model {
227    /// The file's name.
228    pub file: String,
229    /// The arena.
230    pub tree: Tree,
231    /// The root map.
232    pub root: NodeId,
233    /// `$vars`, and the names its DSL makes known.
234    pub variables: Variables,
235    /// `$functions` with a formula, by name.
236    pub functions: IndexMap<String, EntryId>,
237    /// The FEEL text of a function whose parameters are in its key.
238    pub function_text: std::collections::HashMap<EntryId, String>,
239    /// `$functions` the application passes, by name.
240    pub hosted: IndexMap<String, HostFunctionDecl>,
241    /// Every import, by name.
242    pub imported: IndexMap<String, ImportSpec>,
243    /// The schema, from `$schema` or the `$dsl` file.
244    pub schema: Option<Schema>,
245}
246
247/// Why a module or Markdown import is refused (SPEC 2.2).
248pub fn code_hint(names: &[String]) -> String {
249    let example = names.first().map(|n| format!("{n}(…)")).unwrap_or_else(|| "fileExists(path)".into());
250    format!("Scrusted-yaml does not import code. Declare `{example}` under `$functions` without `!`, and pass it to `resolve`.")
251}
252
253impl Model {
254    /// The entries that are the file's data: everything but the top keywords.
255    pub fn data(&self) -> Vec<EntryId> {
256        self.tree.entries_of(self.root).iter().copied().filter(|e| !ROOT_KEYWORDS.contains(&&*self.tree.entry(*e).key.name)).collect()
257    }
258
259    /// `$tests` as plain data.
260    pub fn tests(&self) -> Vec<Value> {
261        match self.tree.get(self.root, "$tests").map(|e| self.tree.to_data(self.tree.entry(e).value)) {
262            Some(Value::List(items)) => items.to_vec(),
263            _ => Vec::new(),
264        }
265    }
266
267    fn read_functions(&mut self, problems: &mut Problems) {
268        let Some(e) = self.tree.get(self.root, "$functions") else { return };
269        let node = self.tree.entry(e).value;
270        if !self.tree.is_map(node) {
271            problems.error(&self.tree.place(node), "$functions must be a map: name(parameter)!: formula");
272            return;
273        }
274        for f in self.tree.entries_of(node).to_vec() {
275            let entry = self.tree.entry(f).clone();
276            let signature = Signature::new(&entry.key.name);
277            let at = self.tree.entry_place(f);
278            match entry.key.kind() {
279                KeyKind::Plain => {
280                    let settings = self.tree.to_data(entry.value);
281                    if !settings.is_null() && !self.tree.is_map(entry.value) {
282                        problems.error(&at, format!("\"{}\" declares a function the application passes, with a map: {{ about: … }}; for a formula, write \"{}!\"", entry.key.raw, entry.key.raw));
283                        continue;
284                    }
285                    if self.functions.contains_key(&signature.name) || self.hosted.contains_key(&signature.name) {
286                        problems.error(&at, format!("the function \"{}\" is declared twice in $functions; keep one", signature.name));
287                        continue;
288                    }
289                    let about = settings.as_map().and_then(|m| m.get("about")).and_then(|v| v.as_str().map(str::to_string));
290                    self.hosted.insert(
291                        signature.name.clone(),
292                        HostFunctionDecl { name: signature.name.clone(), parameters: signature.parameters.clone(), about, entry: f },
293                    );
294                }
295                KeyKind::Marked => problems.error(&at, format!("a function is a formula: write \"{}(…)!: …\"", signature.name)),
296                KeyKind::Formula => {
297                    if self.hosted.contains_key(&signature.name) {
298                        problems.error(&at, format!("the function \"{}\" is declared twice in $functions; keep one", signature.name));
299                    }
300                    if signature.parameters.is_some()
301                        && let Some(s) = self.tree.scalar_of(entry.value)
302                    {
303                        self.function_text.insert(f, signature.define(&s.source));
304                    }
305                    self.functions.insert(signature.name.clone(), f);
306                }
307            }
308        }
309    }
310
311    fn read_imports(&mut self, loader: &Loader<'_>, problems: &mut Problems) {
312        let Some(e) = self.tree.get(self.root, "$import") else { return };
313        let node = self.tree.entry(e).value;
314        if !self.tree.is_map(node) {
315            problems.error(&self.tree.place(node), "$import must be a map: path: names");
316            return;
317        }
318        for i in self.tree.entries_of(node).to_vec() {
319            let entry = self.tree.entry(i).clone();
320            let path = entry.key.raw.to_string();
321            let at = self.tree.entry_place(i);
322            let wanted = self.tree.to_data(entry.value);
323            if [".ts", ".js"].iter().any(|x| path.ends_with(x)) {
324                let names: Vec<String> = match &wanted {
325                    Value::List(l) => l.iter().map(js_string).collect(),
326                    Value::String(s) => vec![s.to_string()],
327                    _ => Vec::new(),
328                };
329                problems.error(&at, format!("cannot import \"{path}\": {}", code_hint(&names)));
330                continue;
331            }
332            if path.ends_with(".md") {
333                problems.error(&at, format!("cannot import \"{path}\": Scrusted-yaml does not import Markdown. Read it in the application and pass what a formula needs as a variable, or declare a function under `$functions` without `!` and pass it to `resolve`."));
334                continue;
335            }
336            if !(path.ends_with(".yml") || path.ends_with(".yaml")) {
337                problems.error(&at, format!("cannot import \"{path}\": there is no importer for this kind of file (only .yml, .yaml)"));
338                continue;
339            }
340            let Value::String(name) = &wanted else {
341                problems.error(&at, format!("\"{path}\" is imported under one name: {path}: name"));
342                continue;
343            };
344            let found = loader.find(&self.tree, i, &path, "import", problems);
345            let spec = ImportSpec {
346                path: path.clone(),
347                file: found.as_ref().map(|f| f.name.clone()).unwrap_or_else(|| path.clone()),
348                text: found.as_ref().map(|f| f.text.clone()).unwrap_or_default(),
349                name: name.to_string(),
350                entry: i,
351                found: found.is_some(),
352            };
353            self.imported.insert(name.to_string(), spec);
354        }
355    }
356}
357
358/// Reads a file and the files it names with `$extends` and `$dsl`, through the application's `Files`.
359pub struct Loader<'a> {
360    /// Where files come from.
361    pub files: &'a dyn Files,
362}
363
364impl Loader<'_> {
365    /// The model of a file. None when it cannot be read at all; the problems say why. With `base`,
366    /// the input is a patch of it, as if it named it with `$extends`.
367    pub fn load(&self, input: &Input, file: &str, base: Option<(&str, &Input)>, problems: &mut Problems) -> Option<Model> {
368        let mut tree = Tree::default();
369        let chain = vec![self.files.key(file)];
370        let root = match base {
371            Some((base_file, base_input)) => {
372                let patch = self.parse(&mut tree, input, file, problems)?;
373                if let Some(e) = tree.get(patch, "$extends") {
374                    problems.error(&tree.entry_place(e), "a patch given its base by the application does not name one with $extends");
375                    return None;
376                }
377                let mut chain = chain.clone();
378                chain.push(self.files.key(base_file));
379                let target = self.tree(&mut tree, base_input, base_file, &chain, problems)?;
380                Patch { tree: &mut tree, problems }.apply(patch, target);
381                target
382            }
383            None => self.tree(&mut tree, input, file, &chain, problems)?,
384        };
385        let mut model = Model {
386            file: file.to_string(),
387            tree,
388            root,
389            variables: Variables::default(),
390            functions: IndexMap::new(),
391            function_text: Default::default(),
392            hosted: IndexMap::new(),
393            imported: IndexMap::new(),
394            schema: None,
395        };
396        let vars = model.tree.get(root, "$vars").map(|e| model.tree.entry(e).value);
397        model.variables.add(&model.tree, vars, problems, false);
398        model.read_functions(problems);
399        model.read_imports(self, problems);
400        let dsl = self.read_dsl(&mut model, problems);
401        let schema = model.tree.get(root, "$schema").map(|e| model.tree.entry(e).value).or_else(|| {
402            let d = dsl?;
403            model.tree.get(d, "$schema").map(|e| model.tree.entry(e).value)
404        });
405        if let Some(schema) = schema {
406            model.schema = Some(Schema::new(&model.tree, schema, problems));
407        }
408        Some(model)
409    }
410
411    fn read_dsl(&self, model: &mut Model, problems: &mut Problems) -> Option<NodeId> {
412        let e = model.tree.get(model.root, "$dsl")?;
413        let value = model.tree.entry(e).value;
414        let Some(path) = model.tree.scalar_of(value).and_then(|s| s.value.as_str().map(str::to_string)) else {
415            problems.error(&model.tree.entry_place(e), "$dsl names one file by its path");
416            return None;
417        };
418        let dsl = self.read(&mut model.tree, e, &path, &[], problems)?;
419        let vars = model.tree.get(dsl, "$vars").map(|v| model.tree.entry(v).value);
420        let mut variables = std::mem::take(&mut model.variables);
421        variables.add(&model.tree, vars, problems, true);
422        model.variables = variables;
423        Some(dsl)
424    }
425
426    /// A file another file names. A problem is reported on the line that names it.
427    pub fn find(&self, tree: &Tree, from: EntryId, path: &str, purpose: &str, problems: &mut Problems) -> Option<crate::files::Source> {
428        let file = tree.entry(from).pos.file.to_string();
429        let from_name = if file.is_empty() { None } else { Some(file.as_str()) };
430        match self.files.read(path, from_name) {
431            Ok(Some(found)) => Some(found),
432            Ok(None) => {
433                problems.error(&tree.entry_place(from), format!("cannot {purpose} \"{path}\": the file does not exist"));
434                None
435            }
436            Err(error) => {
437                problems.error(&tree.entry_place(from), error.to_string());
438                None
439            }
440        }
441    }
442
443    fn read(&self, tree: &mut Tree, from: EntryId, path: &str, chain: &[String], problems: &mut Problems) -> Option<NodeId> {
444        let found = self.find(tree, from, path, "read", problems)?;
445        let key = self.files.key(&found.name);
446        if chain.contains(&key) {
447            problems.error(&tree.entry_place(from), format!("\"{path}\" extends itself, directly or through other files"));
448            return None;
449        }
450        let mut chain = chain.to_vec();
451        chain.push(key);
452        self.tree(tree, &Input::Text(found.text), &found.name, &chain, problems)
453    }
454
455    fn tree(&self, tree: &mut Tree, input: &Input, file: &str, chain: &[String], problems: &mut Problems) -> Option<NodeId> {
456        let root = self.parse(tree, input, file, problems)?;
457        let Some(base) = tree.get(root, "$extends") else { return Some(root) };
458        let value = tree.entry(base).value;
459        let Some(path) = tree.scalar_of(value).and_then(|s| s.value.as_str().map(str::to_string)) else {
460            problems.error(&tree.entry_place(base), "$extends names one file by its path");
461            return None;
462        };
463        let target = self.read(tree, base, &path, chain, problems)?;
464        Patch { tree, problems }.apply(root, target);
465        Some(target)
466    }
467
468    fn parse(&self, tree: &mut Tree, input: &Input, file: &str, problems: &mut Problems) -> Option<NodeId> {
469        let root = match input {
470            Input::Text(text) => reader::read_text(tree, text, file, problems)?,
471            Input::Data(value) => {
472                if value.is_null() {
473                    tree.map(crate::node::Pos { file: file.into(), line: 0, column: 0 })
474                } else {
475                    let root = reader::read_value(tree, value, file);
476                    if !tree.is_map(root) {
477                        problems.error(
478                            &Place { file: file.to_string(), line: 1, column: 1, key: String::new() },
479                            "the root of a file must be a map of keys",
480                        );
481                        return None;
482                    }
483                    root
484                }
485            }
486        };
487        merged::restore(tree, root, problems);
488        Some(root)
489    }
490}
491
492/// For messages: the shared pieces of an import spec.
493pub type Imported = Arc<ImportSpec>;