scrusted-yaml 0.2.0

Validates, loads and resolves scripted-yaml files: YAML with FEEL formulas in marked keys, reloaded live.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
//! One file as written: its tree after `$extends`, and what its top `$` keys say (SPEC 4.2, 4.5,
//! 4.7). Nothing is computed.

use indexmap::IndexMap;
use regex::Regex;
use scrusted_feel::Value;
use std::sync::Arc;

use crate::files::Files;
use crate::node::{EntryId, KeyKind, NodeId, Tree, js_string};
use crate::patch::Patch;
use crate::problem::{Place, Problems};
use crate::schema::Schema;
use crate::{merged, reader};

/// `$` keys that are words of the language at the top of a file, not data.
pub const ROOT_KEYWORDS: &[&str] = &["$vars", "$functions", "$import", "$schema", "$dsl", "$extends", "$tests"];

/// What the application hands over: text, or data already parsed (front matter).
#[derive(Debug, Clone)]
pub enum Input {
    /// YAML text.
    Text(String),
    /// Parsed data; problems have no lines.
    Data(Value),
}

/// One variable a file declares under `$vars` (SPEC 4.5).
#[derive(Debug, Clone, PartialEq)]
pub struct Variable {
    /// Its name.
    pub name: String,
    /// `optional: true`
    pub optional: bool,
    /// `secret: true`: kept out of debug output, problems and traces.
    pub secret: bool,
    /// `host: true`: the application sets it itself.
    pub host: bool,
    /// `type`, as written.
    pub ty: Option<String>,
    /// `about`
    pub about: Option<String>,
    /// `default`
    pub default: Option<Value>,
}

impl Variable {
    /// The application must pass it: no default and not optional.
    pub fn required(&self) -> bool {
        !self.optional && self.default.is_none()
    }

    /// Why a value does not fit the declared type.
    pub fn mismatch(&self, value: &Value) -> Option<String> {
        if value.is_null() {
            return None;
        }
        let fits = match self.ty.as_deref()? {
            "text" => matches!(value, Value::String(_)),
            "number" => matches!(value, Value::Number(_)),
            "boolean" => matches!(value, Value::Bool(_)),
            "list" => matches!(value, Value::List(_)),
            _ => return None,
        };
        if fits {
            None
        } else {
            Some(format!("variable \"{}\" must be a {}; variables are not converted", self.name, self.ty.as_deref().unwrap_or("")))
        }
    }
}

/// The inputs of a file: what `$vars` declares, and the names a DSL makes known.
#[derive(Debug, Clone, Default)]
pub struct Variables {
    /// Declared variables, in order.
    pub declared: IndexMap<String, Variable>,
    patterns: Vec<Regex>,
    known: Vec<String>,
}

/// The values of the variables for one resolve, and what is wrong with them.
pub struct VarValues {
    /// By name: defaults filled in, empty text turned into null.
    pub values: scrusted_feel::Map,
    /// Required variables that are null.
    pub missing: Vec<String>,
    /// Values that do not fit their type.
    pub mismatches: Vec<String>,
}

impl Variables {
    /// Reads a `$vars` map. With `for_checking`, the names only become known.
    pub fn add(&mut self, tree: &Tree, node: Option<NodeId>, problems: &mut Problems, for_checking: bool) {
        let Some(node) = node else { return };
        if !tree.is_map(node) {
            problems.error(&tree.place(node), "$vars must be a map of variable names");
            return;
        }
        for e in tree.entries_of(node) {
            let entry = tree.entry(*e);
            let name = entry.key.raw.to_string();
            if name.len() > 2 && name.starts_with('/') && name.ends_with('/') {
                match Regex::new(&format!("^(?:{})$", &name[1..name.len() - 1])) {
                    Ok(re) => self.patterns.push(re),
                    Err(error) => problems.error(&tree.entry_place(*e), format!("not a regular expression: {error}")),
                }
            } else if for_checking {
                self.known.push(name);
            } else {
                let settings = tree.to_data(entry.value);
                if !settings.is_null() && !tree.is_map(entry.value) {
                    problems.error(
                        &tree.place(entry.value),
                        format!("variable \"{name}\" is declared with a map: {{ default: …, optional: true }}"),
                    );
                    continue;
                }
                let get = |k: &str| settings.as_map().and_then(|m| m.get(k)).cloned();
                let text = |k: &str| get(k).and_then(|v| v.as_str().map(str::to_string));
                let variable = Variable {
                    name: name.clone(),
                    optional: get("optional") == Some(Value::Bool(true)),
                    secret: get("secret") == Some(Value::Bool(true)),
                    host: get("host") == Some(Value::Bool(true)),
                    ty: text("type"),
                    about: text("about"),
                    default: settings.as_map().and_then(|m| m.get("default")).filter(|v| !v.is_null()).cloned(),
                };
                self.declared.insert(name, variable);
            }
        }
    }

    /// True when `vars.NAME` is no typo: declared, matched by a pattern, or known from a DSL.
    pub fn knows(&self, name: &str) -> bool {
        self.declared.contains_key(name) || self.known.iter().any(|k| k == name) || self.patterns.iter().any(|p| p.is_match(name))
    }

    /// The values formulas see for these inputs.
    pub fn values(&self, input: &scrusted_feel::Map) -> VarValues {
        let mut values = scrusted_feel::Map::new();
        for (k, v) in input {
            let v = if v.as_str() == Some("") { Value::Null } else { v.clone() };
            values.insert(k.clone(), v);
        }
        let mut missing = Vec::new();
        let mut mismatches = Vec::new();
        for var in self.declared.values() {
            let current = values.get(var.name.as_str()).cloned().unwrap_or(Value::Null);
            let current = if current.is_null() { var.default.clone().unwrap_or(Value::Null) } else { current };
            if current.is_null() && var.required() {
                missing.push(var.name.clone());
            }
            if let Some(m) = var.mismatch(&current) {
                mismatches.push(m);
            }
            values.insert(var.name.as_str().into(), current);
        }
        VarValues { values, missing, mismatches }
    }

    /// The names of the secret variables.
    pub fn secrets(&self) -> Vec<String> {
        self.declared.values().filter(|v| v.secret).map(|v| v.name.clone()).collect()
    }
}

/// A function a file declares under `$functions` without `!`: the application passes it.
#[derive(Debug, Clone, PartialEq)]
pub struct HostFunctionDecl {
    /// Its name.
    pub name: String,
    /// As written in the key; None when the key has no brackets.
    pub parameters: Option<Vec<String>>,
    /// `about`
    pub about: Option<String>,
    /// The entry that declares it.
    pub entry: EntryId,
}

/// The key of a function: `from_gear(wanted)` is the name `from_gear` and the parameter `wanted`.
pub struct Signature {
    /// The name.
    pub name: String,
    /// None when the key has no brackets.
    pub parameters: Option<Vec<String>>,
}

impl Signature {
    /// Splits a key at `(`, `,` and `)`.
    pub fn new(key: &str) -> Signature {
        match key.find('(') {
            Some(open) if open > 0 && key.ends_with(')') => Signature {
                name: key[..open].trim().to_string(),
                parameters: Some(key[open + 1..key.len() - 1].split(',').map(|p| p.trim().to_string()).filter(|p| !p.is_empty()).collect()),
            },
            _ => Signature { name: key.to_string(), parameters: None },
        }
    }

    /// The FEEL function definition for a body written without one.
    pub fn define(&self, body: &str) -> String {
        format!("function({}) {body}", self.parameters.as_deref().unwrap_or(&[]).join(", "))
    }
}

/// One line of `$import`.
#[derive(Debug, Clone)]
pub struct ImportSpec {
    /// The path as written.
    pub path: String,
    /// The file's name, as `Files` gave it.
    pub file: String,
    /// The file's text.
    pub text: String,
    /// The name it is imported under.
    pub name: String,
    /// The entry of `$import`.
    pub entry: EntryId,
    /// The file was found.
    pub found: bool,
}

/// A file as written, after `$extends`.
pub struct Model {
    /// The file's name.
    pub file: String,
    /// The arena.
    pub tree: Tree,
    /// The root map.
    pub root: NodeId,
    /// `$vars`, and the names its DSL makes known.
    pub variables: Variables,
    /// `$functions` with a formula, by name.
    pub functions: IndexMap<String, EntryId>,
    /// The FEEL text of a function whose parameters are in its key.
    pub function_text: std::collections::HashMap<EntryId, String>,
    /// `$functions` the application passes, by name.
    pub hosted: IndexMap<String, HostFunctionDecl>,
    /// Every import, by name.
    pub imported: IndexMap<String, ImportSpec>,
    /// The schema, from `$schema` or the `$dsl` file.
    pub schema: Option<Schema>,
}

/// Why a module or Markdown import is refused (SPEC 2.2).
pub fn code_hint(names: &[String]) -> String {
    let example = names.first().map(|n| format!("{n}(…)")).unwrap_or_else(|| "fileExists(path)".into());
    format!("Scrusted-yaml does not import code. Declare `{example}` under `$functions` without `!`, and pass it to `resolve`.")
}

impl Model {
    /// The entries that are the file's data: everything but the top keywords.
    pub fn data(&self) -> Vec<EntryId> {
        self.tree.entries_of(self.root).iter().copied().filter(|e| !ROOT_KEYWORDS.contains(&&*self.tree.entry(*e).key.name)).collect()
    }

    /// `$tests` as plain data.
    pub fn tests(&self) -> Vec<Value> {
        match self.tree.get(self.root, "$tests").map(|e| self.tree.to_data(self.tree.entry(e).value)) {
            Some(Value::List(items)) => items.to_vec(),
            _ => Vec::new(),
        }
    }

    fn read_functions(&mut self, problems: &mut Problems) {
        let Some(e) = self.tree.get(self.root, "$functions") else { return };
        let node = self.tree.entry(e).value;
        if !self.tree.is_map(node) {
            problems.error(&self.tree.place(node), "$functions must be a map: name(parameter)!: formula");
            return;
        }
        for f in self.tree.entries_of(node).to_vec() {
            let entry = self.tree.entry(f).clone();
            let signature = Signature::new(&entry.key.name);
            let at = self.tree.entry_place(f);
            match entry.key.kind() {
                KeyKind::Plain => {
                    let settings = self.tree.to_data(entry.value);
                    if !settings.is_null() && !self.tree.is_map(entry.value) {
                        problems.error(&at, format!("\"{}\" declares a function the application passes, with a map: {{ about: … }}; for a formula, write \"{}!\"", entry.key.raw, entry.key.raw));
                        continue;
                    }
                    if self.functions.contains_key(&signature.name) || self.hosted.contains_key(&signature.name) {
                        problems.error(&at, format!("the function \"{}\" is declared twice in $functions; keep one", signature.name));
                        continue;
                    }
                    let about = settings.as_map().and_then(|m| m.get("about")).and_then(|v| v.as_str().map(str::to_string));
                    self.hosted.insert(
                        signature.name.clone(),
                        HostFunctionDecl { name: signature.name.clone(), parameters: signature.parameters.clone(), about, entry: f },
                    );
                }
                KeyKind::Marked => problems.error(&at, format!("a function is a formula: write \"{}(…)!: …\"", signature.name)),
                KeyKind::Formula => {
                    if self.hosted.contains_key(&signature.name) {
                        problems.error(&at, format!("the function \"{}\" is declared twice in $functions; keep one", signature.name));
                    }
                    if signature.parameters.is_some()
                        && let Some(s) = self.tree.scalar_of(entry.value)
                    {
                        self.function_text.insert(f, signature.define(&s.source));
                    }
                    self.functions.insert(signature.name.clone(), f);
                }
            }
        }
    }

    fn read_imports(&mut self, loader: &Loader<'_>, problems: &mut Problems) {
        let Some(e) = self.tree.get(self.root, "$import") else { return };
        let node = self.tree.entry(e).value;
        if !self.tree.is_map(node) {
            problems.error(&self.tree.place(node), "$import must be a map: path: names");
            return;
        }
        for i in self.tree.entries_of(node).to_vec() {
            let entry = self.tree.entry(i).clone();
            let path = entry.key.raw.to_string();
            let at = self.tree.entry_place(i);
            let wanted = self.tree.to_data(entry.value);
            if [".ts", ".js"].iter().any(|x| path.ends_with(x)) {
                let names: Vec<String> = match &wanted {
                    Value::List(l) => l.iter().map(js_string).collect(),
                    Value::String(s) => vec![s.to_string()],
                    _ => Vec::new(),
                };
                problems.error(&at, format!("cannot import \"{path}\": {}", code_hint(&names)));
                continue;
            }
            if path.ends_with(".md") {
                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`."));
                continue;
            }
            if !(path.ends_with(".yml") || path.ends_with(".yaml")) {
                problems.error(&at, format!("cannot import \"{path}\": there is no importer for this kind of file (only .yml, .yaml)"));
                continue;
            }
            let Value::String(name) = &wanted else {
                problems.error(&at, format!("\"{path}\" is imported under one name: {path}: name"));
                continue;
            };
            let found = loader.find(&self.tree, i, &path, "import", problems);
            let spec = ImportSpec {
                path: path.clone(),
                file: found.as_ref().map(|f| f.name.clone()).unwrap_or_else(|| path.clone()),
                text: found.as_ref().map(|f| f.text.clone()).unwrap_or_default(),
                name: name.to_string(),
                entry: i,
                found: found.is_some(),
            };
            self.imported.insert(name.to_string(), spec);
        }
    }
}

/// Reads a file and the files it names with `$extends` and `$dsl`, through the application's `Files`.
pub struct Loader<'a> {
    /// Where files come from.
    pub files: &'a dyn Files,
}

impl Loader<'_> {
    /// The model of a file. None when it cannot be read at all; the problems say why. With `base`,
    /// the input is a patch of it, as if it named it with `$extends`.
    pub fn load(&self, input: &Input, file: &str, base: Option<(&str, &Input)>, problems: &mut Problems) -> Option<Model> {
        let mut tree = Tree::default();
        let chain = vec![self.files.key(file)];
        let root = match base {
            Some((base_file, base_input)) => {
                let patch = self.parse(&mut tree, input, file, problems)?;
                if let Some(e) = tree.get(patch, "$extends") {
                    problems.error(&tree.entry_place(e), "a patch given its base by the application does not name one with $extends");
                    return None;
                }
                let mut chain = chain.clone();
                chain.push(self.files.key(base_file));
                let target = self.tree(&mut tree, base_input, base_file, &chain, problems)?;
                Patch { tree: &mut tree, problems }.apply(patch, target);
                target
            }
            None => self.tree(&mut tree, input, file, &chain, problems)?,
        };
        let mut model = Model {
            file: file.to_string(),
            tree,
            root,
            variables: Variables::default(),
            functions: IndexMap::new(),
            function_text: Default::default(),
            hosted: IndexMap::new(),
            imported: IndexMap::new(),
            schema: None,
        };
        let vars = model.tree.get(root, "$vars").map(|e| model.tree.entry(e).value);
        model.variables.add(&model.tree, vars, problems, false);
        model.read_functions(problems);
        model.read_imports(self, problems);
        let dsl = self.read_dsl(&mut model, problems);
        let schema = model.tree.get(root, "$schema").map(|e| model.tree.entry(e).value).or_else(|| {
            let d = dsl?;
            model.tree.get(d, "$schema").map(|e| model.tree.entry(e).value)
        });
        if let Some(schema) = schema {
            model.schema = Some(Schema::new(&model.tree, schema, problems));
        }
        Some(model)
    }

    fn read_dsl(&self, model: &mut Model, problems: &mut Problems) -> Option<NodeId> {
        let e = model.tree.get(model.root, "$dsl")?;
        let value = model.tree.entry(e).value;
        let Some(path) = model.tree.scalar_of(value).and_then(|s| s.value.as_str().map(str::to_string)) else {
            problems.error(&model.tree.entry_place(e), "$dsl names one file by its path");
            return None;
        };
        let dsl = self.read(&mut model.tree, e, &path, &[], problems)?;
        let vars = model.tree.get(dsl, "$vars").map(|v| model.tree.entry(v).value);
        let mut variables = std::mem::take(&mut model.variables);
        variables.add(&model.tree, vars, problems, true);
        model.variables = variables;
        Some(dsl)
    }

    /// A file another file names. A problem is reported on the line that names it.
    pub fn find(&self, tree: &Tree, from: EntryId, path: &str, purpose: &str, problems: &mut Problems) -> Option<crate::files::Source> {
        let file = tree.entry(from).pos.file.to_string();
        let from_name = if file.is_empty() { None } else { Some(file.as_str()) };
        match self.files.read(path, from_name) {
            Ok(Some(found)) => Some(found),
            Ok(None) => {
                problems.error(&tree.entry_place(from), format!("cannot {purpose} \"{path}\": the file does not exist"));
                None
            }
            Err(error) => {
                problems.error(&tree.entry_place(from), error.to_string());
                None
            }
        }
    }

    fn read(&self, tree: &mut Tree, from: EntryId, path: &str, chain: &[String], problems: &mut Problems) -> Option<NodeId> {
        let found = self.find(tree, from, path, "read", problems)?;
        let key = self.files.key(&found.name);
        if chain.contains(&key) {
            problems.error(&tree.entry_place(from), format!("\"{path}\" extends itself, directly or through other files"));
            return None;
        }
        let mut chain = chain.to_vec();
        chain.push(key);
        self.tree(tree, &Input::Text(found.text), &found.name, &chain, problems)
    }

    fn tree(&self, tree: &mut Tree, input: &Input, file: &str, chain: &[String], problems: &mut Problems) -> Option<NodeId> {
        let root = self.parse(tree, input, file, problems)?;
        let Some(base) = tree.get(root, "$extends") else { return Some(root) };
        let value = tree.entry(base).value;
        let Some(path) = tree.scalar_of(value).and_then(|s| s.value.as_str().map(str::to_string)) else {
            problems.error(&tree.entry_place(base), "$extends names one file by its path");
            return None;
        };
        let target = self.read(tree, base, &path, chain, problems)?;
        Patch { tree, problems }.apply(root, target);
        Some(target)
    }

    fn parse(&self, tree: &mut Tree, input: &Input, file: &str, problems: &mut Problems) -> Option<NodeId> {
        let root = match input {
            Input::Text(text) => reader::read_text(tree, text, file, problems)?,
            Input::Data(value) => {
                if value.is_null() {
                    tree.map(crate::node::Pos { file: file.into(), line: 0, column: 0 })
                } else {
                    let root = reader::read_value(tree, value, file);
                    if !tree.is_map(root) {
                        problems.error(
                            &Place { file: file.to_string(), line: 1, column: 1, key: String::new() },
                            "the root of a file must be a map of keys",
                        );
                        return None;
                    }
                    root
                }
            }
        };
        merged::restore(tree, root, problems);
        Some(root)
    }
}

/// For messages: the shared pieces of an import spec.
pub type Imported = Arc<ImportSpec>;